def get_oauth_access_token(self, request, oauth_request_token):
        """
        Get the access token using the oauth request token and the data
        provided on the request. Should raise the appropriate exception
        if the data is invalid. Returns an object like:
        {
            'oauth_token_secret': 'ASDF',
            'user_id': '1234',
            'oauth_token': '123-asdf',
            'screen_name': 'mattsniderjs'
        }
        """
        code = request.GET.get('code')

        if not code:
            raise SocialOauthDictFailed

        url_prefix = 'https' if request.is_secure() else 'http'
        url_prefix += '://%s' % request.META['HTTP_HOST']

        data = facebook.get_access_token_from_code(
            code, self.get_callback_url(url_prefix), self.facebook_ck,
            self.facebook_cs)

        if not (data.get('access_token') and data.get('expires')):
            raise SocialOauthDictFailed

        return data['access_token'], datetime.now() + timedelta(
            milliseconds=int(data['expires']))
Exemple #2
0
def get_user():
    "Returns currently logged in user, registering a new user if necessary"
    user = get_logged_in_user()
    if not 'facebook_user_details' in g:
        abort(403)
    if not user:
        fb_code = g.facebook_user_details['code']
        fb_access_token = facebook.get_access_token_from_code(
            fb_code,
            '',
            app_id,
            app_key
        )['access_token']

        graph = facebook.GraphAPI(fb_access_token)
        fb_details = graph.get_object('me')

        username = fb_details['name']
        email = fb_details['email']
        facebook_id = g.facebook_user_details['user_id']

        user = User(username, email, facebook_id)
        db.session.add(user)
        db.session.commit()

    return jsonify(user = user.dictify())
 def _get_access_token_from_code(self, code):
     return facebook.get_access_token_from_code(
         code,
         tur_settings["facebook_code_redirect_uri"],
         tur_settings["facebook_app_id"],
         tur_settings["facebook_app_secret"]
     )
Exemple #4
0
	def get(self):
		# Check signed request for uid
		uid = self.request.GET['userID']
		signedRequest = self.request.GET['signedRequest']
		if not uid or not signedRequest:
			return self.abort(400)

		parsed_request = facebook.parse_signed_request(self.request.GET['signedRequest'], FACEBOOK_APP_SECRET)
		if not parsed_request or uid != parsed_request['user_id']:
			return self.abort(403)

		try:
			result = facebook.get_access_token_from_code(parsed_request["code"], "", FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
			profile = facebook.GraphAPI(result['access_token']).get_object("me")
		except facebook.GraphAPIError:
			return self.abort(403)

		# Fetch existant user or create new one
		user = entities.User.get_by_key_name(profile['id'])
		if not user:
			api_key = ''. join(random.choice(string.hexdigits) for x in range(64))
			user = entities.User(key_name = str(profile['id']),
								uid = int(profile['id']),
								first_name = profile['first_name'], last_name = profile['last_name'],
								api_key = api_key, access_token = result['access_token'], active = True)
		else:
			user.access_token = result['access_token']
		user.put();

		profile['api_key'] = user.api_key
		profile['access_token'] = user.access_token
		self.response.out.write(json.dumps(profile))
Exemple #5
0
def get_access_token_from_code(code,root_url):
  logging.debug("Getting FB info")
  access = facebook.get_access_token_from_code(
            code,_get_redirect_uri(root_url),
            _APPLICATION_ID,_APPLICATION_SECRET)
  logging.info(access)
  return access["access_token"]
Exemple #6
0
 def authenticate(cls, app, type_auth=None, app_user=None):
     if app.community.type == 'page':
         if not app.community.token:
             token = cls.get_long_lived_page_token(
                 app.app_id, app.app_secret, app.app_access_token,
                 app.community.external_id)
             app.community.token = token
             app.community.save()
         else:
             token = app.community.token
     else:  # community type = group
         if type_auth == 'write':  # User access_token
             code = cls.get_code(app.app_id, app.app_secret,
                                 app.redirect_uri, app_user.access_token)
             access_token_info = facebook.get_access_token_from_code(
                 code, app.redirect_uri, app.app_id, app.app_secret)
             token = access_token_info['access_token']
             app_user.access_token = token
             app_user.access_token_exp = calculate_token_expiration_time(
                 access_token_info['expires_in'])
             app_user.save()
         else:
             if app.app_access_token:
                 token = app.app_access_token
             else:
                 token = facebook.get_app_access_token(
                     app.app_id, app.app_secret)
                 app.app_access_token = token
                 app.save()
     cls.graph = facebook.GraphAPI(token)
    def get_oauth_access_token(self, request, oauth_request_token):
        """
        Get the access token using the oauth request token and the data
        provided on the request. Should raise the appropriate exception
        if the data is invalid. Returns an object like:
        {
            'oauth_token_secret': 'ASDF',
            'user_id': '1234',
            'oauth_token': '123-asdf',
            'screen_name': 'mattsniderjs'
        }
        """
        code = request.GET.get('code')

        if not code:
            raise SocialOauthDictFailed

        url_prefix = 'https' if request.is_secure() else 'http'
        url_prefix += '://%s' % request.META['HTTP_HOST']

        data = facebook.get_access_token_from_code(
            code, self.get_callback_url(url_prefix), self.facebook_ck,
            self.facebook_cs)

        if not (data.get('access_token') and data.get('expires')):
            raise SocialOauthDictFailed

        return data['access_token'], datetime.now() + timedelta(
            milliseconds=int(data['expires']))
Exemple #8
0
 def process_token(self, client_token, auth_data):
     callback_url = auth_data["callback_url"]
     
     auth_response = facebook.get_access_token_from_code(client_token,
                                                        callback_url,
                                                        self.__app_id,
                                                        self.__app_secret)
     
     if "access_token" not in auth_response:
         return { "error" : "Unable to authenticate code." }
     
     access_token = auth_response["access_token"]
     
     graph = facebook.GraphAPI(access_token)
     extension_response = graph.extend_access_token(self.__app_id, self.__app_secret)
     
     extended_token = extension_response.get("access_token")
     
     result = {}
     result["main_token"] = extended_token
     
     if "main_token" not in result:
         result["error"] = "Page not found."
     
     return result
Exemple #9
0
    def get(self, request, *args, **kwargs):
        """Set up success url."""

        redirect_url = settings.LOGIN_REDIRECT_URL
        if not 'error' in request.GET and \
           request.session['facebook_state'] == request.GET['state']:
            login_redirect_uri = 'http://%s%s' % (
                Site.objects.get_current().domain,
                reverse('facebook_login_callback')
            )
            access_token = facebook.get_access_token_from_code(
                request.GET['code'],
                login_redirect_uri,
                settings.FACEBOOK_APP_ID,
                settings.FACEBOOK_APP_SECRET
            )
            redirect_url = request.session.get(
                'facebook_login_redirect_url',
                settings.LOGIN_REDIRECT_URL
            )
            user = authenticate(
                access_token=access_token['access_token'],
                access_token_expiry_seconds=access_token['expires']
            )

            if user is None:
                raise ValidationError("Invalid Login")

            if not user.is_active:
                raise ValidationError("User is inactive")

            auth_login(request, user)

        return redirect(redirect_url)
Exemple #10
0
def login_view(request):
    try:
        parameters = facebook.get_access_token_from_code(
            request.GET['code'], settings.REDIRECT_URI,
            settings.SOCIAL_AUTH_FACEBOOK_KEY,
            settings.SOCIAL_AUTH_FACEBOOK_SECRET)
        access_token = parameters['access_token']

        #Another approach could be to read the url & parse it as JSON
        '''url_access = 'https://graph.facebook.com/v2.3/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}'\
                    .format(settings.SOCIAL_AUTH_FACEBOOK_KEY, settings.REDIRECT_URI, settings.SOCIAL_AUTH_FACEBOOK_SECRET,code)
            response = urllib.urlopen(url_access)
            self.access_token = json.loads(response.read())['access_token']'''

        #Extend the token validity

        graph = facebook.GraphAPI(access_token=access_token)
        extend_object = graph.extend_access_token(
            app_id=settings.SOCIAL_AUTH_FACEBOOK_KEY,
            app_secret=settings.SOCIAL_AUTH_FACEBOOK_SECRET)
        global EXTENDED_TOKEN
        EXTENDED_TOKEN = extend_object['access_token']

    except Exception, e:
        print e
 def _get_access_token_from_code(self, code):
     return facebook.get_access_token_from_code(
         code,
         tur_settings["facebook_code_redirect_uri"],
         tur_settings["facebook_app_id"],
         tur_settings["facebook_app_secret"]
     )
Exemple #12
0
def get_access_token_from_code(code, root_url):
    logging.debug("Getting FB info")
    access = facebook.get_access_token_from_code(code,
                                                 _get_redirect_uri(root_url),
                                                 _APPLICATION_ID,
                                                 _APPLICATION_SECRET)
    logging.info(access)
    return access["access_token"]
Exemple #13
0
    def oauth_callback(self, request):
        try:
            callback_url = SecureCookie.unserialize(request.cookies["facebook_oauth"], self.client_secret)["callback_url"]
        except KeyError:
            return False

        access_token = facebook.get_access_token_from_code(request.args.get("code"), callback_url, self.client_id, self.client_secret)["access_token"]
        user = facebook.GraphAPI(access_token).get_object("me")
        
        return (int(user["id"]), dict(user, access_token=access_token))
Exemple #14
0
        def do_GET(self):
            global ACCESS_TOKEN
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()

            code = urlparse.parse_qs(urlparse.urlparse(self.path).query).get('code')
            code = code[0] if code else None
            if code is None:
                self.wfile.write("Sorry, authentication failed.")
                sys.exit(1)
            ACCESS_TOKEN = facebook.get_access_token_from_code(code,
                FBAuth.REDIRECT_URI, FBAuth.APP_ID, FBAuth.APP_SECRET)['access_token']
            open(FBAuth.LOCAL_FILE,'w').write(ACCESS_TOKEN)
            self.wfile.write("You have successfully logged in to facebook. "
                             "You can close this window now.")
Exemple #15
0
def userLogin(user_name):
    all_users_auth = {}
    current_auth = {}
    os.system('rm -rf %s/current_user.log' % tmp_folder)
    if user_name: # try to load user auth from cache
        if os.path.isfile(tmp_folder+'/users.json'):
            all_users_auth = json.load(open(tmp_folder+'/users.json'))
            if all_users_auth.get(user_name):
                current_auth = all_users_auth[user_name]
        open(tmp_folder+'/current_user.log','w').write(user_name)
    else:
        exit("ERROR: Please login with --login [USERNAME].")

    if not current_auth: # new user, ask for auth and save to cache
        print facebook.auth_url(app_id, redirect_uri, perms)
        code = str(raw_input("Please copy and paste the verification number following https://www.facebook.com/?code= "))
        access_token = facebook.get_access_token_from_code(code, redirect_uri, app_id, app_secret)["access_token"]
        current_auth["ACCESS_TOKEN"] = access_token
        all_users_auth[user_name] = current_auth
        json.dump(all_users_auth, open(tmp_folder+'/users.json', 'w'))
    return facebook.GraphAPI(current_auth["ACCESS_TOKEN"])
Exemple #16
0
    def get(self):
        # Check signed request for uid
        uid = self.request.GET["userID"]
        signedRequest = self.request.GET["signedRequest"]
        if not uid or not signedRequest:
            return self.abort(400)

        parsed_request = facebook.parse_signed_request(self.request.GET["signedRequest"], FACEBOOK_APP_SECRET)
        if not parsed_request or uid != parsed_request["user_id"]:
            return self.abort(403)

        try:
            result = facebook.get_access_token_from_code(
                parsed_request["code"], "", FACEBOOK_APP_ID, FACEBOOK_APP_SECRET
            )
            profile = facebook.GraphAPI(result["access_token"]).get_object("me")
        except facebook.GraphAPIError:
            return self.abort(403)

            # Fetch existant user or create new one
        user = entities.User.get_by_key_name(profile["id"])
        if not user:
            api_key = "".join(random.choice(string.hexdigits) for x in range(64))
            user = entities.User(
                key_name=str(profile["id"]),
                uid=int(profile["id"]),
                first_name=profile["first_name"],
                last_name=profile["last_name"],
                api_key=api_key,
                access_token=result["access_token"],
                active=True,
            )
        else:
            user.access_token = result["access_token"]
        user.put()

        profile["api_key"] = user.api_key
        profile["access_token"] = user.access_token
        self.response.out.write(json.dumps(profile))
Exemple #17
0
    def do_GET(self):

        global ACCESS_TOKEN
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        code = urlparse.parse_qs(urlparse.urlparse(
            self.path).query).get('code')
        code = code[0] if code else None

        if code is None:
            self.wfile.write("Sorry, authentication failed.")
            sys.exit(1)

        response = get_access_token_from_code(code, REDIRECT_URI, APP_ID,
                                              APP_SECRET)

        ACCESS_TOKEN = response['access_token']

        open(LOCAL_FILE, 'w').write(ACCESS_TOKEN)
        self.wfile.write("You have successfully logged in to facebook. "
                         "You can close this window now.")
Exemple #18
0
def Facebook_getAccessTokenFromCode(self, code, redirect_uri):
  return facebook.get_access_token_from_code(code=code,
    redirect_uri=redirect_uri,
    app_id=self.portal_preferences.getPreferredVifibFacebookApplicationId(),
    app_secret=self.portal_preferences.getPreferredVifibFacebookApplicationSecret())
Exemple #19
0
    def identify(self, environ):
        """This method is called when a request is incoming.

        If credentials are found, the returned identity mapping will
        contain an arbitrary set of key/value pairs.

        Return None to indicate that the plugin found no appropriate
        credentials.

        An IIdentifier plugin is also permitted to ``pre-authenticate''
        an identity.  If the identifier plugin knows that the identity
        is ``good'' (e.g. in the case of ticket-based authentication
        where the user id is embedded into the ticket), it can insert a
        special key into the identity dictionary: repoze.who.userid.
        If this key is present in the identity dictionary, no
        authenticators will be asked to authenticate the identity.
        """
        if not self._has_already_logged_fb_version:
            environ[REPOZE_WHO_LOGGER].info(u'Using Facebook API v%s',
                                            FACEBOOK_API_VERSION_STR)
            self._has_already_logged_fb_version = True

        request = Request(environ)
        response = Response()

        # First test for logout as we then don't need the rest.
        if request.path in self.logout_handler_paths:
            return self._logout(environ, request, response)  # --> None

        # Then we check that we are actually on the URL which is
        # supposed to be the url to return to (login_handler_path in
        # configuration) this URL is used for both: the answer for the
        # login form and when the openid provider redirects the user
        # back.
        elif request.path not in self.login_handler_paths:
            return None

        try:
            request.scheme = request.headers['X-Forwarded-Proto']
        except KeyError:
            pass

        login_handler_url = self._get_full_login_handler_url(request)
        environ[REPOZE_WHO_LOGGER].debug(u'login_handler_url: %r',
                                         login_handler_url)
        default_target_url = self._deduct_default_target_url(request)

        if 'access_token' in request.params and 'uid' in request.params:
            fb_user = {
                'access_token': request.params['access_token'],
                'uid': request.params['uid'],
            }

            data_source = 'from params'

        elif 'code' in request.params:
            try:
                fb_user = facebook.get_access_token_from_code(
                    request.params['code'],
                    login_handler_url,
                    config['pyfacebook.appid'],
                    config['pyfacebook.secret'])
            except facebook.GraphAPIError as e:
                self._log_graph_api_exception(
                    'Exception in get_access_token_from_code()', e, environ)
                self._redirect(environ, target_url=default_target_url,
                               response=response)
                return None

            data_source = 'via Facebook "code"'

        else:
            try:
                fb_user = facebook.get_user_from_cookie(
                    request.cookies,
                    config['pyfacebook.appid'],
                    config['pyfacebook.secret'])
            except facebook.GraphAPIError as e:
                self._log_graph_api_exception(
                    'Exception in get_user_from_cookie()', e, environ)
                # Redirect to Facebook to get a code for a new access token.
                self._redirect_to_perms_dialog(environ, login_handler_url)
                return None

            data_source = 'from cookie'

        environ[REPOZE_WHO_LOGGER] \
            .info('Received fb_user = %r (%s)', fb_user, data_source)

        # Store a local instance of the user data so we don't need
        # a round-trip to Facebook on every request

        try:
            graph = facebook.GraphAPI(fb_user["access_token"],
                                      version=FACEBOOK_API_VERSION_STR)
            profile = graph.get_object('me')
            if 'id' not in profile:
                environ[REPOZE_WHO_LOGGER] \
                    .warn('Facebook Python-SDK received no uid.')
                return self._logout(environ, request, response)  # --> None

            if 'uid' in fb_user:
                assert profile['id'] == fb_user['uid']
            else:
                fb_user['uid'] = profile['id']

            permissions = graph.get_object('me/permissions')['data']
            environ[REPOZE_WHO_LOGGER].info(u'Granted Facebook permissions: %r',
                                            permissions)

            if FACEBOOK_API_VERSION >= (2, 0):
                granted = [
                    item['permission'] for item in permissions
                    if item['status'] == 'granted'
                ]
                missing_mandatory = self.mandatory_permissions - set(granted)
                missing_optional = self.optional_permissions - set(granted)

                if missing_optional:
                    environ[REPOZE_WHO_LOGGER]\
                        .info(u'Missing optional permissions: %r',
                              missing_optional)
                    environ[FACEBOOK_CONNECT_REPOZE_WHO_MISSING_OPTIONAL] = \
                        missing_optional

                if missing_mandatory:
                    environ[REPOZE_WHO_LOGGER]\
                        .info(u'Missing mandatory permissions: %r',
                              missing_mandatory)
                    environ[FACEBOOK_CONNECT_REPOZE_WHO_MISSING_MANDATORY] = \
                        missing_mandatory
                    response.status = BAD_REQUEST
                    self._set_handler(environ, response)
                    return None

            else:
                # Legacy, against FB API < v2.0:
                if 'email' not in permissions:
                    environ[REPOZE_WHO_LOGGER].warn(
                        'No permissions to access email address, '
                        'will redirect to permission dialog.')
                    self._redirect_to_perms_dialog(environ, login_handler_url,
                                                   perms=['email'])
                    return None

        except facebook.GraphAPIError as e:
            self._log_graph_api_exception('Exception in get_object()', e,
                                          environ)
            raise

        profile['access_token'] = fb_user['access_token']

        environ[REPOZE_WHO_LOGGER].info('graph.get_object("me") = %r', profile)

        if self.identified_hook is None:  # or (fb_user is None):
            environ[REPOZE_WHO_LOGGER] \
                .warn('identify(): No identified_hook was provided.')
            self._redirect(environ, target_url=default_target_url,
                           response=response)
            return None

        self._set_handler(environ, response)

        identity = {}

        self.identified_hook(profile['id'], profile, environ, identity,
                             response)

        return identity
 def get_access_token_from_code(self, code, redirect_uri=None):
     if redirect_uri is None:
         redirect_uri = self.redirect_uri
     return facebooklib.get_access_token_from_code(code, redirect_uri,
                                                   self._app_id,
                                                   self._app_secret)
 def get_access_token_from_code(self, code, redirect_uri=None):
     if redirect_uri is None:
         redirect_uri = self.redirect_uri
     return facebooklib.get_access_token_from_code(code, redirect_uri,
                                           self._app_id, self._app_secret)
    def identify(self, environ):
        """This method is called when a request is incoming.

        If credentials are found, the returned identity mapping will
        contain an arbitrary set of key/value pairs.

        Return None to indicate that the plugin found no appropriate
        credentials.

        An IIdentifier plugin is also permitted to ``preauthenticate''
        an identity.  If the identifier plugin knows that the identity
        is ``good'' (e.g. in the case of ticket-based authentication
        where the userid is embedded into the ticket), it can insert a
        special key into the identity dictionary: repoze.who.userid.
        If this key is present in the identity dictionary, no
        authenticators will be asked to authenticate the identity.
        """
        request = Request(environ)

        # First test for logout as we then don't need the rest.
        if request.path in self.logout_handler_paths:
            if request.path.endswith('.json'):
                self._logout_json(environ)
                return None

            self._logout_and_redirect(environ)
            return None                 # No identity was found.

        # Then we check that we are actually on the URL which is
        # supposed to be the url to return to (login_handler_path in
        # configuration) this URL is used for both: the answer for the
        # login form and when the openid provider redirects the user
        # back.
        elif request.path != self.login_handler_path:
            return None

        try:
            request.scheme = request.headers['X-Forwarded-Proto']
        except KeyError:
            pass

        redirect_to_self_url = request.application_url + \
            self.login_handler_path

        if 'access_token' in request.params and 'uid' in request.params:
            fb_user = {
                'access_token': request.params['access_token'],
                'uid': request.params['uid'],
            }

            data_source = 'from params'

        elif 'code' in request.params:
            try:
                fb_user = facebook.get_access_token_from_code(
                    request.params['code'],
                    redirect_to_self_url,
                    config['pyfacebook.appid'],
                    config['pyfacebook.secret'])
            except facebook.GraphAPIError as e:
                self._log_graph_api_exception(
                    'Exception in get_access_token_from_code()', e, environ)
                self._redirect_to(environ)
                return None

            data_source = 'via Facebook "code"'

        else:
            try:
                fb_user = facebook.get_user_from_cookie(
                    request.cookies,
                    config['pyfacebook.appid'],
                    config['pyfacebook.secret'])
            except facebook.GraphAPIError as e:
                self._log_graph_api_exception(
                    'Exception in get_user_from_cookie()', e, environ)
                # Redirect to Facebook to get a code for a new access token.
                self._redirect_to_perms_dialog(environ, redirect_to_self_url)
                return None

            data_source = 'from cookie'

        environ[REPOZE_WHO_LOGGER] \
            .info('Received fb_user = %r (%s)', fb_user, data_source)

        # Store a local instance of the user data so we don't need
        # a round-trip to Facebook on every request

        try:
            graph = facebook.GraphAPI(fb_user["access_token"])
            profile = graph.get_object("me")

            if not 'id' in profile:
                environ[REPOZE_WHO_LOGGER] \
                    .warn('Facebook Python-SDK received no uid.')
                self._logout_and_redirect(environ)
                return None
            if 'uid' in fb_user:
                assert profile['id'] == fb_user['uid']
            else:
                fb_user['uid'] = profile['id']

            permissions = graph.get_permissions()

            if not 'email' in permissions:
                environ[REPOZE_WHO_LOGGER].warn(
                    'No permissions to access email address, '
                    'will redirect to permission dialog.')
                self._redirect_to_perms_dialog(environ, redirect_to_self_url,
                                               perms=['email'])
                return None

        except facebook.GraphAPIError as e:
            self._log_graph_api_exception(
                'Exception in get_object()', e, environ)
            raise

        profile['access_token'] = fb_user['access_token']

        environ[REPOZE_WHO_LOGGER] \
            .warn('graph.get_object("me") = %r', profile)

        if self.identified_hook is None:  # or (fb_user is None):
            environ[REPOZE_WHO_LOGGER] \
                .warn('identify(): No identified_hook was provided.')
            self._redirect_to(environ, None)
            return None

        identity = dict()

        authenticated, redirect_to_url, cookies \
            = self.identified_hook(profile['id'], profile, environ, identity)

        self._redirect_to(environ, redirect_to_url, cookies)

        return identity