Ejemplo n.º 1
0
def get_application_access_token(application_id,
                                 application_secret_key,
                                 api_version=None):
    """
    Get an OAuth access token for the given application.

    :param application_id: An integer describing a Facebook application's ID.
    :param application_secret_key: A string describing a Facebook application's secret key.
    """
    graph = GraphAPI(version=api_version)

    response = graph.get(path='oauth/access_token',
                         client_id=application_id,
                         client_secret=application_secret_key,
                         grant_type='client_credentials')

    try:
        data = parse_qs(response)

        try:
            return data['access_token'][0]
        except KeyError:
            raise GraphAPI.FacebookError('No access token given')
    except AttributeError:  # api_version >= 2.3 returns a dict
        return response['access_token'], None
Ejemplo n.º 2
0
def get_extended_access_token(access_token, application_id, application_secret_key):
    """
    Get an extended OAuth access token.

    :param access_token: A string describing an OAuth access token.
    :param application_id: An integer describing the Facebook application's ID.
    :param application_secret_key: A string describing the Facebook application's secret key.

    Returns a tuple with a string describing the extended access token and a datetime instance
    describing when it expires.
    """
    graph = GraphAPI()

    response = graph.get(
        path='oauth/access_token',
        client_id=application_id,
        client_secret=application_secret_key,
        grant_type='fb_exchange_token',
        fb_exchange_token=access_token
    )

    components = parse_qs(response)

    token = components['access_token'][0]
    expires_at = datetime.now() + timedelta(seconds=int(components['expires'][0]))

    return token, expires_at
Ejemplo n.º 3
0
def get_application_access_token(application_id, application_secret_key, api_version=None):
    """
    Get an OAuth access token for the given application.

    :param application_id: An integer describing a Facebook application's ID.
    :param application_secret_key: A string describing a Facebook application's secret key.
    """
    graph = GraphAPI(version=api_version)

    response = graph.get(
        path='oauth/access_token',
        client_id=application_id,
        client_secret=application_secret_key,
        grant_type='client_credentials'
    )

    try:
        data = parse_qs(response)

        try:
            return data['access_token'][0]
        except KeyError:
            raise GraphAPI.FacebookError('No access token given')
    except AttributeError:  # api_version >= 2.3 returns a dict
        return response['access_token'], None
Ejemplo n.º 4
0
def get_extended_access_token(access_token, application_id, application_secret_key, api_version=None):
    """
    Get an extended OAuth access token.

    :param access_token: A string describing an OAuth access token.
    :param application_id: An integer describing the Facebook application's ID.
    :param application_secret_key: A string describing the Facebook application's secret key.

    Returns a tuple with a string describing the extended access token and a datetime instance
    describing when it expires.
    """
    graph = GraphAPI(version=api_version)

    response = graph.get(
        path='oauth/access_token',
        client_id=application_id,
        client_secret=application_secret_key,
        grant_type='fb_exchange_token',
        fb_exchange_token=access_token
    )

    try:
        components = parse_qs(response)
    except AttributeError:  # api_version >= 2.3 returns a dict
        return response['access_token'], None

    token = components['access_token'][0]

    try:
        expires_at = datetime.now() + timedelta(seconds=int(components['expires'][0]))
    except KeyError:  # there is no expiration
        expires_at = None

    return token, expires_at
Ejemplo n.º 5
0
def get_extended_access_token(access_token,
                              application_id,
                              application_secret_key,
                              api_version=None):
    """
    Get an extended OAuth access token.

    :param access_token: A string describing an OAuth access token.
    :param application_id: An integer describing the Facebook application's ID.
    :param application_secret_key: A string describing the Facebook application's secret key.

    Returns a tuple with a string describing the extended access token and a datetime instance
    describing when it expires.
    """
    graph = GraphAPI(version=api_version)

    response = graph.get(path='oauth/access_token',
                         client_id=application_id,
                         client_secret=application_secret_key,
                         grant_type='fb_exchange_token',
                         fb_exchange_token=access_token)

    try:
        #api_version < 2.3 try to parse as it returns string formatted like url query
        components = parse_qs(response)
    except AttributeError:
        # api_version >= 2.3 returns a dict
        # Make tidier exception structure to handle expiry time on api_version >=2.3
        token = response['access_token']
        expiry_countdown = response.get(
            'expires_in', 3600)  # https://github.com/jgorset/facepy/pull/172
    else:
        token = components['access_token'][0]
        try:
            expiry_countdown = int(components['expires'][0])
        except KeyError:  # there is no expiration
            expiry_countdown = None

    if expiry_countdown is not None:
        expires_at = datetime.now() + timedelta(seconds=expiry_countdown)
    else:
        expires_at = None

    return token, expires_at
Ejemplo n.º 6
0
def get_extended_access_token(access_token,
                              application_id,
                              application_secret_key,
                              api_version=None):
    """
    Get an extended OAuth access token.

    :param access_token: A string describing an OAuth access token.
    :param application_id: An integer describing the Facebook application's ID.
    :param application_secret_key: A string describing the Facebook application's secret key.

    Returns a tuple with a string describing the extended access token and a datetime instance
    describing when it expires.
    """
    graph = GraphAPI(version=api_version)

    response = graph.get(path='oauth/access_token',
                         client_id=application_id,
                         client_secret=application_secret_key,
                         grant_type='fb_exchange_token',
                         fb_exchange_token=access_token)

    try:
        components = parse_qs(response)
    except AttributeError:  # api_version >= 2.3 returns a dict
        return response['access_token'], None

    token = components['access_token'][0]

    try:
        expires_at = datetime.now() + timedelta(
            seconds=int(components['expires'][0]))
    except KeyError:  # there is no expiration
        expires_at = None

    return token, expires_at
Ejemplo n.º 7
0
    def process_request(self, request):
        # user already authed
        if request.user.is_authenticated() or (hasattr(request, 'facebook') and request.facebook):
            return

        # User is not authed. Lets init some variables to play with
        request.facebook = Facebook()
        oauth_token = False


        # User may redirect after they granted us to access their facebook.
        # Now we are going to do some business with facebook.
        if 'code' in request.GET:
            try:
                graph = GraphAPI()
                # Don't disturb!!! doing business with Mr. Zuckerberg
                response = graph.get(
                    'oauth/access_token',
                    client_id=FACEBOOK_APPLICATION_ID,
                    redirect_uri=FACEBOOK_AUTHORIZATION_REDIRECT_URL,
                    client_secret=FACEBOOK_APPLICATION_SECRET_KEY,
                    code=request.GET['code']
                )
                parsed_response = parse_qs(response)

                # We got a virgin OAuth Token from Facebook. Now we gonna put it into our DB.
                oauth_token, new_oauth_token = FacebookOAuthToken.objects.get_or_create(
                    token=parsed_response['access_token'][0],
                    issued_at=now(),
                    expires_at=now() + timedelta(seconds=int(parsed_response['expires'][0]))
                )

            except GraphAPI.OAuthError as error:
                pass

        # the user may already bring a token for us in past. Lets check our cookie for that
        elif 'facebook_oauth_token' in request.COOKIES:
            try:
                # we got the cookie. But wait!!! We should have it in our DB too. let's cross check
                oauth_token = FacebookOAuthToken.objects.get(token=request.COOKIES['facebook_oauth_token'])
            except FacebookOAuthToken.DoesNotExist:
                request.facebook = False
                return

        # NO code from Facebook or NO Access Token stored in cookie.
        # how the heck I gonna identify you?
        if not oauth_token or oauth_token.expired:
            request.facebook = False
            return


        # GREAT!!! You must have a valid access token...
        try:
            facebook_profile = oauth_token.facebookprofile
            if not facebook_profile.authorized:
                request.facebook = False
            facebook_profile.last_seen_at = now()
            facebook_profile.save()
        except FacebookProfile.DoesNotExist:
            # No Facebook Profile found against the current oauth token
            graph = GraphAPI(oauth_token.token)
            profile = graph.get('me')

            # Two Possibilities:
            # 1. User already have their Facebook profile with us and we need to integrate this new token
            # 2. User didn't connect it yet. But they want to connect now.
            try:
                # case 1:
                facebook_profile = FacebookProfile.objects.get(facebook_id=profile.get('id'))
                if not facebook_profile.authorized:
                    if new_oauth_token:
                        facebook_profile.authorized = True
                        facebook_profile.last_seen_at = now()
                    else:
                        request.facebook = False
                        return
            except FacebookProfile.DoesNotExist:
                # case 2:
                email = profile.get('email')
                # lets check whether we have already an account for this email or not
                try:
                    user = User.objects.get(email=email)
                except User.DoesNotExist:
                    username = email.split('@')[0]
                    user = User.objects.create(
                                username=username,
                                email=email,
                                password=password_generator(),
                                first_name=profile.get('first_name'),
                                last_name=profile.get('last_name'),
                            )
                facebook_profile = FacebookProfile.objects.create(
                    user = user,
                    facebook_id = profile.get('id'),
                    email = email,
                    oauth_token = oauth_token
                )

            facebook_profile.synchronize(profile)

            # Delete previous access token if there is any and its not same as current
            prev_oauth_token = None
            if facebook_profile.oauth_token != oauth_token:
                prev_oauth_token = facebook_profile.oauth_token
                facebook_profile.oauth_token = oauth_token

            facebook_profile.save()
            if prev_oauth_token:
                prev_oauth_token.delete()

        if facebook_profile.oauth_token.extended:
            try:
                facebook_profile.oauth_token.extend()
            except:
                pass

        request.facebook.facebookprofile = facebook_profile
        request.facebook.oauth_token = oauth_token
        user = authenticate(username=facebook_profile.user.username, password=oauth_token)
        login(request, user)