I'm building a Python web app with the Evernote API. When users log in they're redirected to a page on the Evernote site to authorize the application. When they come back everything works fine (can see and edit notes etc.)
The challenge now is to avoid having to redirect the user to the Evernote site every time they log on.
I read on the Evernote forums that I need to save the access token and the notestore url to achieve this. I now save these to the users accounts after the first successful authorization.
But how do I use the access token and notestore url to authorize?
I found this sample code on the Evernote website that's supposed to achieve this, but it's in Java and I can't seem to make it work in Python.
// Retrieved during authentication:
String authToken = ...
String noteStoreUrl = ...
String userAgent = myCompanyName + " " + myAppName + "/" + myAppVersion;
THttpClient noteStoreTrans = new THttpClient(noteStoreUrl);
userStoreTrans.setCustomHeader("User-Agent", userAgent);
TBinaryProtocol noteStoreProt = new TBinaryProtocol(noteStoreTrans);
NoteStore.Client noteStore = new NoteStore.Client(noteStoreProt, noteStoreProt);
Basically, if you got the notestore url and access token from a previous authorization, how do you use them to re-authorize?
If you have the access token, you will use that as a constructor argument for the EvernoteClient class.
For example:
client = EvernoteClient(token=your_access_token)
note_store = client.get_note_store()
notebooks = note_store.listNotebooks();
for n in notebooks:
print n.name
For more examples, check out the Python Quick-start Guide.
Related
I am trying to get a Facebook page feed through Google app script.
As of now I tried different scripts but I am getting only app token with the request and if i change it with a usertoken from graph api I got messages but no images and titles
How to get the user token and get the correct fields for as a json ,
var url = 'https://graph.facebook.com'
+ '/love.to.traavel/feed'
+ '?access_token='+ encodeURIComponent(getToken());
// + '?access_token=' + service.getAccessToken();
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
Logger.log(jsondata); //check this and adjust following for loop and ht
var posts = {};
for (var i in jsondata) {
posts[i] = {"post":jsondata[i].message};
}
return posts;
You should use a Page Token, not a User Token
You need to ask for fields you want to get, with the fields parameter: https://graph.facebook.com/love.to.traavel/feed?fields=field1,field2,...&access_token=xxx
You get a user token by authorizing your App: https://developers.facebook.com/docs/facebook-login/platforms
Be aware that extended user tokens are valid for 60 days only, so you have to refresh it once in a while. There is no user token that is valid forever. You cannot authorize through code only, it needs user interaction. The easiest way is to just generate a user token by selecting your App in the API Explorer and authorize it, like you did already. Then hardcode it in the script code.
Alternatively, you can try implementing this with the manual login flow, check out the docs for that. You can try adding the functionality using this for a custom interface where you go through the login process: https://developers.google.com/apps-script/guides/html/
Since you donĀ“t own the page, you should read this too: https://developers.facebook.com/docs/apps/review/feature/#reference-PAGES_ACCESS
I have a website built in django 1.7, python 3.4. I want to enable my users to invite their gmail contacts to my website (like linkedin & many other websites do). I am using Oauth2.0 and am able to get permission to access their contacts. But i am not getting an idea how to proceed and what steps to take.
Can somebody help me to get an overview of all the steps that i need to take and a little explanation as to how to do that.
Even a link to suitable post would be helpful.
See, When you need to implement these features in your website, you will have to understand the APIs etc to utilize it to the fullest.
Go through this https://developers.google.com/google-apps/contacts/v3/?csw=1#audience
Let's talk only about google only. The rest providers can also be managed with similar steps. Here you are using django-allauth for this task.
The basic steps involved are:
Get your app created and configured with the provider. for that you will need a developer profile in google(or facebook etc.). You will have to create an app in google developer console and you will find a plenty of tutorial for this on internet. That has been done by you as you have signup with google activated on your site. That is server side of Oauth2.0
Now you need to define the scope of authorization you need. You might only need the access to view the public profile thing. that may include first name, last name, email, id, gender, etc. For your app, you need contacts of users and for that you will have to include it in the scope too.
That is done in settings.py only.
'google': {'SCOPE': ['profile', 'email', 'https://www.googleapis.com/auth/contacts'],
'AUTH_PARAMS': {'access_type': 'online'}}
}
Now here, you have got the access to the contacts. Now, you only need to extract the contacts with the consent of data owner(user).
For this purpose,you may follow the first link in the answer. What you have to do is you have to send a get request to some url('https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token). The request goes to provider only(google) with the authorization token it has provided you for that particular user. That you will find in the db table socialtoken. Once you send proper request, the response you will get is the contacts of the user in xml format.
Once you get it, you can easily parse it to extract the required information.
Things are simple if you understand the flow. django-allauth only helpy you upto signup & signin where you can get different permissions through defining the scope.
For extracting the contacts, you can write your own code.
A simple example is:
def get_email_google(request):
# social = request.user.social_auth.get(provider='google-oauth2')
user =request.user
# Code dependent upon django-allauth. Will change if we shift to another module
# if request.user.userprofile.get_provider() != "google":
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
url = 'https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token + '&max-results=100'
req = urllib2.Request(url, headers={'User-Agent' : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30"})
contacts = urllib2.urlopen(req).read()
contacts_xml = etree.fromstring(contacts)
# print
# return render(request, 'search/random_text_print.html', locals())
result = []
for entry in contacts_xml.findall('{http://www.w3.org/2005/Atom}entry'):
for address in entry.findall('{http://schemas.google.com/g/2005}email'):
email = address.attrib.get('address')
result.append(email)
return render(request, 'search/random_text_print.html', locals())
user =request.user
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
SCOPES = ['SCOPE_URL']
creds = client.AccessTokenCredentials(access_token, 'USER_AGENT')
service = build('calendar', 'v3', credentials=creds)
I have developed an app so that users can upload images to a page's album. I do not want users to have to authorize and so I used the access token from the app to upload the images for them. This works fine if the admin is logged in and the access token hasn't expired - it only seems to last for a couple hours. I have looked through stackoverflow and facebook and tried many different things and nothing seems to work. Here is some of the code I am using:
try {
$facebook->setAccessToken("APP_ACCESS_TOKEN_FROM_GRAPH_API_TOOL");
$token_url="https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=fb_exchange_token&fb_exchange_token=".$facebook->getAccessToken();
$page_id = 'PAGE_ID';
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$page_info['access_token'] = $params['access_token'];
$page_info = $facebook->api("/".$page_id."?fields=access_token");
if( !empty($page_info['access_token']) ) {
$photo_details['access_token'] = $page_info['access_token'];
$upload_photo = $facebook->api('/'.$page_id.'/photos', 'post', $photo_details);
Am I dreaming? Is this possible and I just screwed up the code? Any help would be much appreciated even just to point me in the right direction...
Currently, your code uses your own Access Token, not the App Access token.
To get the app access token, you need to make a get request to https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials as documented at https://developers.facebook.com/docs/technical-guides/opengraph/publishing-with-app-token/
in your implementation, and assuming that APP_SECRET and APP_ID are defined as constants, you'd get the app access token through :
$appAccessToken = str_replace("access_token=","",$facebook->api("https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials"));
$facebook->setAccessToken($appAccessToken);
This is my first post, and I have a problem I could not make it work django OMAB socialauth of three things I just need to google, facebook, and twitter, google works well with open id, but not much twitter and I put in my
settings. py:
TWITTER_CONSUMER_KEY = '00' this is no real
TWITTER_CONSUMER_SECRET = '00' this is no real
FACEBOOK_APP_ID = '' ihave no key
FACEBOOK_API_SECRET = ''
LINKEDIN_CONSUMER_KEY = ''
LINKEDIN_CONSUMER_SECRET = ''
ORKUT_CONSUMER_KEY = ''
ORKUT_CONSUMER_SECRET = ''ihave no key
GOOGLE_OAUTH2_CLIENT_ID = ''
GOOGLE_OAUTH2_CLIENT_SECRET = ''
SOCIAL_AUTH_CREATE_USERS = True
SOCIAL_AUTH_FORCE_RANDOM_USERNAME = False
SOCIAL_AUTH_DEFAULT_USERNAME = 'socialauth_user'
SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
LOGIN_ERROR_URL = '/login/error/'
#SOCIAL_AUTH_USER_MODEL = 'app.CustomUser'
SOCIAL_AUTH_ERROR_KEY = 'socialauth_error'
GITHUB_APP_ID = ''
GITHUB_API_SECRET = ''
FOURSQUARE_CONSUMER_KEY = ''
FOURSQUARE_CONSUMER_SECRET = ''
LOGIN_URL = '/login-form/'
LOGIN_REDIRECT_URL = '/'
LOGIN_ERROR_URL = '/login-error/'
I am using the example that comes in the zip of OMAB socialauth django , but not working.
When I created my twitter app, I wrote my domain www.sisvei.com , I am testing locally socialauth django ie 127.0.0.1:8000, then sign in with twitter sends me to this url:
http://127.0.0.1:8000/login/error/ and a message saying is the Incorrect authentication service
this happens with facebook and google oauth and oauth2
I'm new to django and I this much work comprising this part of django socialath hopefully help me, thank you very much.
You need to be more specific on "why it doesn't work". Where are you getting the errors?
When debugging a third-party oauth/openid app in Django, generally it boils down to:
configuration & keys - did you make sure to obtain all of the necessary API keys for the services you will be using, and to add them to your configuration?
urls - did you remember to add the necessary urlpatterns to your base urls.py file?
authentication setup on the server - often, you'll need to have a file available or respond with a specific header when the authentication service hits your server. Have you checked to make sure that is set up?
databases - have you run syncdb after installing the app? Are all the tables set up?
templates - if the third party app requires you to set up templates, do you have them set up?
custom views - are you using custom views? If so, try using the built-in views that came with the third party app first, to see if they work
After those are confirmed, you're going to want to be able to see what requests are taking place. Use the debugger included in Chrome/Safari, or get the web developer add-on for Firefox, and look at the network requests as they happen. Do you see HTTP responses other than 200 (say, 404, 500, 403, etc?) those mean that the services aren't responding correctly.
From your error, it looks like you have not correctly set up your callback URL on Twitter. It should be sending you to www.sisvei.com, not 127.0.0.1. Alternatively, check the URL when you get to the Twitter login page -- is the callback URL in the URL, and is it pointing to 127.0.0.1? Then Django is sending it the wrong callback URL.
Finally this:
I wrote my domain www.sisvei.com python does not support this
Is unclear. As far as I know, Python doesn't care what the domain is.
WAIT A MINUTE ...
Are you using runserver? Are you getting the following error?
Error: "www.sisvei.com" is not a valid port number or address:port pair.
If so, there is an easy fix! Just run it like so:
python manage.py runserver www.sisvei.com:80
That should resolve your error if that's what's happening. You're probably running it as
python manage.py runserver 127.0.0.1
127.0.0.1 is a reserved IP address that points back to localhost, your own computer. As a result, it is not possible to use it for authentication or any other purpose outside of programs running on your own machine. See this article for more info.
I'm not sure, but I might be having similar problems, oscar. For me, SocialAuth was generating an AuthenticationURL for facebook, foursquare and hotmail, but not for google, twitter or any of the other address it supports. I think it may be something wrong with the API, so I posted an issue on the social-auth google group...you may want to check there to see if anyone updates!!
https://code.google.com/p/socialauth/issues/detail?id=282&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Modified
I was creating a twitter application with Django. I used the twitter lib from http://github.com/henriklied/django-twitter-oauth for OAuth , as specified in the twitter example pages .
But I am not too sure how to redirect user to my application home page once the authentication with twitter is over .
The code for
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_url=REQUEST_TOKEN_URL
)
oauth_request.sign_request(signature_method, consumer, None)
resp = fetch_response(oauth_request, connection)
token = oauth.OAuthToken.from_string(resp)
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, token=token, http_url=AUTHORIZATION_URL
)
print(oauth_request.to_url());
oauth_request.sign_request(signature_method, consumer, token)
return oauth_request.to_url()
response = HttpResponseRedirect(auth_url)
request.session['unauthed_token'] = token.to_string()
I even tried passing a "oauth_callback" parameter along with "auth_url" .
But after the authentication , it's not redirecting back to my application which is at
"http://localhost:8000/myApp/twitter/"
Any clues ? Any pointers ?
Thanks
Jijoy
The callback needs to be something like http://local.dev:8080. Twitter doesn't recognize localhost. One thing you probably need to do is go to your etc/hosts file and make sure you add the line 127.0.0.l local.dev
Check if you have enter the callback url in the details of your Twitter App in http://dev.twitter.com/apps.