Facebook Graph API - Post on Group wall as Group - facebook-graph-api

I am trying to post to Facebook Group Wall via Graph API. When i make the post, owner of the post is set as my personal id. Would someone know how to make Group has the owner of the post. Below is my current code:
form_fields = {
"message": 'This is message title',
"link": 'http://facebook.com',
"name": 'This is message title',
"access_token": 'token here'
}
form_fields['description'] = 'This is message body'
form_data = urllib.urlencode(form_fields)
response = urlfetch.fetch( url="https://graph.facebook.com/%s/feed" % group_id,
payload=form_data,
method=urlfetch.POST,
deadline=10
)

You can't do it. That's one of the differences between the group and pages, in a page when you do a post as an admin the user of the post is the page and not your userid, so there is no way that you can make a group to be the owner of a post using the Graph api. See this link http://www.facebook.com/help/?page=904 and search the question "How are Pages different from Groups?".

Related

How to download a file on client after an Ajax request

I have a django app where users can save their contacts. I am not building a flow to allow users to download their contacts locally.
To do so, I built a CTA ("download") that if clicked
Gets the id of the contact selected
Triggers an Ajax request to my views
In the view I get the contact id, retrieve the data from my DB and create a VCF card out of it. (A contact card - basically a text file)
Now I would like to have such file downloaded on the client's machine but I don't know how to do it.
I managed to do it if I redirect to a new url where the view does exactly what my view below does, I want to allow users to download the file without being redirected to a new page. Also, trying to avoid storing the contact ids in the URL.
That's why I am trying to use ajax but I think that's creating problems because and Ajax request waits JsonReponse from the view.
I tried both a GET or POST but it's not working.
This is my view currently:
def get(self, request, *args, **kwargs):
#Get the ids
ids = request.GET.getlist('contact_ids[]')
# Get contqacts associated with ids
contacts = Contact.objects.filter(id__in=ids)
# Transform contacts into long text
text = Vcard().GroupVcards(contacts)
#Create file on the fly and attach it to the response (is this correct actually?)
response = HttpResponse(content_type='text/plain')
response['Content-Disposition'] = 'attachment;filename=ven.vcf'
response.writelines(text)
#return
return response
This is the Jquery triggering the ajax
$('.Vcard').on('click', function(e) {
let id = $(this).data('contact_id')
$.ajax({
type: "GET",
url: Urls['action:DownloadContact'](),
data: {
csrfmiddlewaretoken: csrftoken,
'contact_ids': [id],
},
error: function(response){
console.log(response)
console.log('error')
},
success: function(response) {
console.log(response)
console.log('success')
}
});
})

Re-implementing Social Logins (in Django)

TL;DR: Is it OK to not store (Google/Facebook) OAuth2 access tokens, but rather request new ones on every login?
I'll explain:
To add social logins ("Login with Google/Facebook") to a Django app, you have Python Social Auth. The problem with it, at least for me, is that it's much more complicated than I'd like, requires a lot of configurations, creates additional tables in the database, and in general feels like a lot of moving parts I don't understand for a rather simple task.
So, I read a bit about Google's and Facebook's flows, and they're simple enough:
The server has an ID and a secret.
The clients/users have their standard login credentials.
Then:
The server redirects the user to Google/Facebook, and provides its ID and a redirection URI.
After the user has logged in, Google/Facebook redirects them to that URI with a code.
The server sends its ID, secret, and the received code to Google/Facebook, and gets an access token in exchange, which it can now use to make API calls on behalf of the user.
Even the most basic permissions are enough to query Google/Facebook for the user's email, which can then be matched against Django's standard User model (and if it doesn't exist, a password-less user can created).
The access token can now be discarded, as it was only necessary to translate the Google/Facebook login to an actual email (validated by them), which is used as the only user identifier - no more confusion due to different accounts when logging via different social services; no additional tables; no unnecessary complexity.
Here's the code, just to show how little is necessary:
# views.py
def login_view(request):
return render(request, 'login.html', {
'google_url': 'https://accounts.google.com/o/oauth2/v2/auth?' + urllib.parse.urlencode({
'client_id': GOOGLE_ID,
'redirect_uri': request.build_absolute_uri(reverse('oauth_google')),
'scope': 'profile email',
'response_type': 'code',
}),
}) # use this url in the template as a social login
def oauth_google(request):
code = request.GET['code']
response = requests.post('https://www.googleapis.com/oauth2/v4/token', {
'code': code,
'client_id': GOOGLE_ID,
'client_secret': GOOGLE_SECRET,
'redirect_uri': request.build_absolute_uri(reverse('oauth_google')),
'grant_type': 'authorization_code',
}).json()
id_token = response['id_token']
response = requests.get('https://www.googleapis.com/oauth2/v3/tokeninfo', {
'id_token': id_token,
}).json()
email = response['email']
user = User.objects.filter(username=email).first()
if not user:
user = User(username=email)
user.save()
auth.login(request, user)
return redirect('index')
# urls.py
urlpatterns = [
...
path('oauth/google', views.oauth_google, name='oauth_google'),
]
My question is: what am I missing? If it's really that simple, why couldn't I find any answers on StackOverflow / tutorials on the web describing just that?
The only reason I can think of is that access tokens come with an expiration time (anywhere between 1 hour and 60 days); so maybe I'm supposed to keep reusing the same access token as long as it's valid (which will require storing it, and would explain why Python Social Auth needs additional tables). Will Google/Facebook get mad at me for requesting new access tokens too frequently and block me? I couldn't find any mention of this in their documentation.
EDIT
Here's the Facebook code, in case anyone finds these snippets useful:
# views.py
def login_view(request):
return render(request, 'login.html', {
'facebook_url': 'https://www.facebook.com/v3.2/dialog/oauth?' + urllib.parse.urlencode({
'client_id': FACEBOOK_ID,
'redirect_uri': request.build_absolute_uri(reverse('oauth_facebook')),
'scope': 'email',
}),
}) # use this url in the template as a social login
def oauth_facebook(request):
code = request.GET['code']
response = requests.get('https://graph.facebook.com/v3.2/oauth/access_token', {
'code': code,
'client_id': FACEBOOK_ID,
'client_secret': FACEBOOK_SECRET,
'redirect_uri': request.build_absolute_uri(reverse('oauth_facebook')),
}).json()
access_token = response['access_token']
response = requests.get('https://graph.facebook.com/me', {
'access_token': access_token,
'fields': 'email',
}).json()
email = response['email']
user = User.objects.filter(username=email).first()
if not user:
user = User(username=email)
user.save()
auth.login(request, user)
return redirect('index')
# urls.py
urlpatterns = [
...
path('oauth/facebook', views.oauth_facebook, name='oauth_facebook'),
]

Facebook profile picture URL stops working

I have created an app with react native, where the user is able to log in with facebook. I request the users first_name, last_name and picture.width(520)(which is the users profile picture).
When the user log ins for the first time it works fine. In the profile section you can actually see the picture, however after a day or so if you log in again the profile picture wont load. In the database I can still see the same URL given to me by the request, it just wont load.
Does FB change the URL or how can I permanently get a URL that points to the users profile picture?
The actual request:
const infoRequest = new GraphRequest('/me',
{
parameters: {
fields: {
string: 'first_name,last_name,picture.width(520)'
}
}
}, (error, result) => {
//save picture URL to database
})

How to get user details using JWT token

I'm using angular 5 front end and django as back end. I use JWT token to communicate between django to angular. How can I get logged user details in backend using token.
EG:
class PostSerializer(ModelSerializer):
class Meta:
model = PostDetail
fields = [
'title',
'upvote',
]
Here upvote is a many to many field contain all voted user list. I want to add one more field "user_vote_status" to check the vote status of logged in user.
How can I figure out this issue, please help me.
Here it is. JWT is made of three parts divided by "." The center part contains the user details. So you get that with split and decode that part with window.atob
function getUserInfo() {
const token = getToken();
let payload;
if (token) {
payload = token.split(".")[1];
payload = window.atob(payload);
return JSON.parse(payload);
} else {
return null;
}
}
function getToken() {
return localStorage.getItem("jwt-token");
}
You can get usernamec in any django view by this way
#api_view(['POST'])
def apiname(request):
username = request.user.username
as from angular front end, you need to send jwt token in headers
Authorization: JWT "token"

how to publish photos on facebook wall from an external ( django + python) application

I want to publish my photos from django application to the facebook wall, i use photos.upload method I am not using graph API. but I am not able to publish it even i took permissions to publish photos as well but still not working......
Please help me how could i achieve it please give me some sample code that will help me
you can publish photos by using this it work form me...
request.facebook(
method = "stream_publish",
args={
'message' : "Test Message with Picture",
'attachment' : simplejson.dumps({ 'media': [
{'type': 'image',
'src': 'http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-your-cat-is-bursting-with-joy1.jpg',
'href': 'http://xxxx/xx/5157d6da/'}]}),
'uid' : 'uid'})