Need help about capture access token from facebook uri

This is the place for queries that don't fit in any of the other categories.

Need help about capture access token from facebook uri

Postby Gianka » Wed Nov 27, 2013 3:36 am

Hello.
I'm a newbie so my knowledge is not far from just print "hello world"
i want to update the app Hermes, written in python wich retrieve infos from facebook friends, https://garage.maemo.org/projects/hermes/
Authorization of the app is not working anymore because of some api changes in facebook.
But i discovered a workaround, to gain access token. i just go to this url
https://www.facebook.com/dialog/oauth?client_id=5916f12942feea4b3247d42a84371112&redirect_uri=https://www.facebook.com/connect/login_success.html&scope=user_about_me,friends_about_me,user_birthday,friends_birthday,user_website,friends_website,user_work_history,friends_work_history&response_type=token
and copy/paste the access token in the gconf path of the app
Anyway can somebody suggest me the right changes to apply in the code to let the access token being captured from the app?
i guess i have to modify just these two files:
api.py
Code: Select all
 import urllib, urllib2
 import simplejson

 class FacebookApi():
     """Facebook backend for Hermes, using the Graph API:
     
           http://developers.facebook.com/docs/reference/api/
       
        Copyright (c) Andrew Flegg <andrew@bleb.org> 2010.
        Released under the Artistic Licence."""
       
       
     # -----------------------------------------------------------------------
     def __init__(self, oauth):
         self._oauth = oauth


     # -----------------------------------------------------------------------
     def authenticate(self):
         '''Authenticate the user with Facebook.'''
         
         self._oauth.authorise('https://graph.facebook.com/oauth/authorize',
                               'https://graph.facebook.com/oauth/access_token',
                               {'scope': 'user_about_me,friends_about_me,user_birthday,friends_birthday,user_website,friends_website,user_work_history,friends_work_history'})


     # -----------------------------------------------------------------------
     def get_user(self):
         '''Return the name of the authenticated user.'''
         
         data = self._request('https://graph.facebook.com/me')
         return data['name']


     # -----------------------------------------------------------------------
     def get_friends(self):
         '''Return the full list of people being followed by the user.
         
            The result is a list of users:
            http://developers.facebook.com/docs/reference/api/user/'''

         users = self._request('https://graph.facebook.com/me/friends', {'fields': 'id,name,link,birthday,website,picture'})['data']
         for user in users:
             if 'picture' in user:
                 user['picture'] = 'https://graph.facebook.com/%s/picture?type=large&access_token=%s' % (user['id'], self._oauth.get_access_token())
         return users
     
     
     # -----------------------------------------------------------------------
     def _request(self, url, args = None):
         """Make an authenticated request to Facebook and check the
            JSON response. Return the dictionary if no errors."""
         
         json = self._oauth.request(url, args)
 #        print json
         data = simplejson.loads(json)
         if 'error' in data:
             raise Exception(data['error'])
         
         return data


and oauth2.py
Code: Select all
 import webbrowser
 import urllib, urllib2
 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
 import urlparse, cgi

 class OAuth2:
     """Implementation of OAuth2 protocol, as described by Facebook:
     
            http://developers.facebook.com/docs/authentication/#web_server_auth

        Uses a local web server to retrieve the code and hence the access token.
       
        Copyright (c) Andrew Flegg <andrew@bleb.org> 2010.
        Released under the Artistic Licence."""


     # -----------------------------------------------------------------------
     def __init__(self, client_id, client_secret, access_token = None):
         '''Create a new OAuth 2.0 client, with the folowing arguments:
         
                client_id - Identifier of the application.
                client_secret - Secret API key of the application.
                access_token - Current access token, if any.'''
         
         self._client_id     = client_id
         self._client_secret = client_secret
         self._access_token  = access_token


     # -----------------------------------------------------------------------
     def authorise(self, authorise_url, access_token_url, args = None):
         '''Open a browser window to allow the user to log in and
            authorise this client.'''

         redirect_uri = 'http://localhost:3435/success'
         webbrowser.open_new('%s?client_id=%s&redirect_uri=%s&%s' % (authorise_url, self._client_id, redirect_uri, args and urllib.urlencode(args) or ''))
         handler = OAuthCodeHandler()
         code = handler.run()

         result = urllib2.urlopen('%s?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s' % (access_token_url, self._client_id, redirect_uri, self._client_secret, code)).read()
         params = cgi.parse_qs(result)
         if 'access_token' in params:
             self._access_token = params['access_token'][0]
         else:
             print result, params
             raise Exception('Unable to retrieve access_token from Facebook')


     # -----------------------------------------------------------------------
     def request(self, url, args = None):
         '''Make an authenticated request to the given URL. If no
            access token is currently set, an exception will be thrown.
           
            An optional dictionary of parameters can be specified.'''
           
         if not self._access_token:
             raise Exception("Unauthorised")
         
         query_url = '%s?access_token=%s&%s' % (url, self._access_token, args and urllib.urlencode(args) or '')
 #        print query_url
         result = urllib2.urlopen(query_url).read()
         return result
     

     # -----------------------------------------------------------------------
     def get_access_token(self):
         """Get the access token in use by this OAuth 2.0 client,
            so that it can be persisted."""
           
         return self._access_token


 # ---------------------------------------------------------------------------
 class OAuthCodeHandler(HTTPServer):
     """Handles the response from an OAuth2 handler and allows the
        retrieval of the code."""

     # -----------------------------------------------------------------------
     def __init__(self, success_response = '<h1>Success</h1><p>Please now close this window.</p>',
                        failure_response = '<h1>Failed</h1><p>%s</p>'):
         '''Create a new handler, with optional overrides of the
            success and failure response messages.'''
         
         HTTPServer.__init__(self, ('127.0.0.1', 3435), OAuthHttpRequestHandler)
         self._success_response = success_response
         self._failure_response = failure_response
         self._code = None
         
         
     # -----------------------------------------------------------------------
     def run(self):
         '''Start a server and wait for a redirect. Return the code
            if/when successful.'''
           
         self.handle_request()
         return self._code


     # -----------------------------------------------------------------------
     def set_code(self, code):
         '''Called by the handler to feed us back the code.'''
         
         self._code = code
         
     def get_success_response(self):
         return self._success_response

     def get_failure_response(self):
         return self._failure_response


 # ---------------------------------------------------------------------------
 class OAuthHttpRequestHandler(BaseHTTPRequestHandler):
     def do_GET(self):
         qs = urlparse.urlparse(self.path).query
         params = cgi.parse_qs(qs)
         
         if 'code' in params:
             self.server.set_code(params['code'][0])

             self.send_response(200)
             self.send_header('Content-type', 'text/html')
             self.end_headers()
             self.wfile.write(self.server.get_success_response())
         else:
             print qs, params
             self.send_response(500)
             self.send_header('Content-type', 'text/html')
             self.end_headers()
             self.wfile.write(self.server.get_failure_response())
         
         return


any suggestions?
Last edited by Gianka on Wed Nov 27, 2013 12:06 pm, edited 3 times in total.
Gianka
 
Posts: 3
Joined: Wed Nov 27, 2013 3:16 am

Re: Need help about capture access token from facebook uri

Postby Kebap » Wed Nov 27, 2013 11:51 am

Can you please edit the code to not include the line numbers? So we can actually copy and run it for testing? Thanks. :mrgreen:
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 377
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe

Re: Need help about capture access token from facebook uri

Postby Gianka » Wed Nov 27, 2013 12:06 pm

edited
Gianka
 
Posts: 3
Joined: Wed Nov 27, 2013 3:16 am

Re: Need help about capture access token from facebook uri

Postby Gianka » Tue Dec 03, 2013 11:47 pm

bump
Gianka
 
Posts: 3
Joined: Wed Nov 27, 2013 3:16 am


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests