Пример #1
0
def send_notification(user, message):
    if user.provider == 'vkontakte':
        vkapi = vkontakte.API(api_id=VK_APP_ID,
                              api_secret=VK_APP_SECRET)
        vkapi.get('secure.sendNotification', client_secret=VK_APP_SECRET, uid=user.social_id, message=message)
    else:
        token = get_application_access_token(FACEBOOK_APPLICATION_ID, FACEBOOK_APPLICATION_SECRET_KEY)
        graph = GraphAPI(token)
        graph.post('/{social_id}/notifications?access_token={token}&template={message}'.format(social_id=user.social_id,
                                                                                               token=token,
                                                                                               message=quote_plus(message.encode('utf-8'))))
    def test_registration(self):
        """
        Verify that authorizing the application will register a new user.
        """

        self.client.post(path=reverse("home"), data={"signed_request": TEST_SIGNED_REQUEST})

        user = SocialUser.objects.get(id=1)
        graph = GraphAPI(user.oauth_token.token)

        assert user.first_name == graph.get("me")["first_name"]
        assert user.last_name == graph.get("me")["last_name"]
Пример #3
0
    def extend(self):
        """Extend the OAuth token."""
        graph = GraphAPI()

        response = graph.get(
            'oauth/access_token',
            client_id=FACEBOOK_APPLICATION_ID,
            client_secret=FACEBOOK_APPLICATION_SECRET_KEY,
            grant_type='fb_exchange_token',
            fb_exchange_token=self.token)

        components = parse_qs(response)

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

        self.save()
    def process_request(self, request):
        """Process the signed request."""
        if djangocanvas.settings.ENABLED_PATHS and djangocanvas.settings.DISABLED_PATHS:
            raise ImproperlyConfigured(
                'You may configure either FANDJANGO_ENABLED_PATHS '
                'or FANDJANGO_DISABLED_PATHS, but not both.'
            )

        if djangocanvas.settings.DISABLED_PATHS and is_disabled_path(request.path):
            return

        if djangocanvas.settings.ENABLED_PATHS and not is_enabled_path(request.path):
            return

        # An error occured during authorization...
        if 'error' in request.GET:
            logger.warning(u'Facebook authorization error')
            error = request.GET['error']

            # The user refused to authorize the application...
            if error == 'access_denied':
                logger.warning(u'Facebook user access denied')
                return authorization_denied_view(request)

        # Signed request found in either GET, POST or COOKIES...
        if 'signed_request' in request.REQUEST or 'signed_request' in request.COOKIES:
            request.facebook = Facebook()

            # If the request method is POST and its body only contains the signed request,
            # chances are it's a request from the Facebook platform and we'll override
            # the request method to HTTP GET to rectify their misinterpretation
            # of the HTTP standard.
            #
            # References:
            # "POST for Canvas" migration at http://developers.facebook.com/docs/canvas/post/
            # "Incorrect use of the HTTP protocol" discussion at http://forum.developers.facebook.net/viewtopic.php?id=93554
            if request.method == 'POST' and 'signed_request' in request.POST:
                request.POST = QueryDict('')
                request.method = 'GET'

            try:
                request.facebook.signed_request = SignedRequest(
                    signed_request=request.REQUEST.get('signed_request') or request.COOKIES.get('signed_request'),
                    application_secret_key=djangocanvas.settings.FACEBOOK_APPLICATION_SECRET_KEY)

            except SignedRequest.Error as ex:
                logger.warning(u'Facebook signed request error: {0}'.format(str(ex)))
                request.facebook = False

            # Valid signed request and user has authorized the application
            if request.facebook and request.facebook.signed_request.user.has_authorized_application:
                # Redirect to Facebook Authorization if the OAuth token has expired
                if request.facebook.signed_request.user.oauth_token.has_expired:
                    return authorize_application(
                        request=request,
                        redirect_uri=get_post_authorization_redirect_url(request))

                # Initialize a User object and its corresponding OAuth token
                social_id = request.facebook.signed_request.user.id
                try:
                    social_user = SocialUser.objects.get(social_id=social_id)
                except SocialUser.DoesNotExist:
                    logger.info(u'Creating a new user (facebook id = {0})'.format(social_id))
                    oauth_token = OAuthToken.objects.create(
                        token=request.facebook.signed_request.user.oauth_token.token,
                        issued_at=request.facebook.signed_request.user.oauth_token.issued_at,
                        expires_at=request.facebook.signed_request.user.oauth_token.expires_at)

                    social_user = SocialUser.objects.create(
                        social_id=request.facebook.signed_request.user.id,
                        provider='facebook',
                        oauth_token=oauth_token)

                    graph = GraphAPI(social_user.oauth_token.token)
                    profile = graph.get('me')

                    social_user.first_name = profile.get('first_name')
                    social_user.last_name = profile.get('last_name')

                    social_user.save()

                    request.social_data = graph
                    self._set_user_is_new(request)

                # Update the user's details and OAuth token
                else:
                    if 'signed_request' in request.REQUEST:
                        social_user.authorized = True

                        if request.facebook.signed_request.user.oauth_token:
                            social_user.oauth_token.token = request.facebook.signed_request.user.oauth_token.token
                            social_user.oauth_token.issued_at = request.facebook.signed_request.user.oauth_token.issued_at
                            social_user.oauth_token.expires_at = request.facebook.signed_request.user.oauth_token.expires_at
                            social_user.oauth_token.save()

                    social_user.save()

                if not social_user.oauth_token.extended:
                    # Attempt to extend the OAuth token, but ignore exceptions raised by
                    # bug #102727766518358 in the Facebook Platform.
                    #
                    # http://developers.facebook.com/bugs/102727766518358/
                    try:
                        social_user.oauth_token.extend()
                    except:
                        pass

                social_login(request, social_user)

            else:
                return authorize_application(
                    request=request,
                    redirect_uri=get_post_authorization_redirect_url(request))

        # ... no signed request found.
        else:
            request.facebook = False