Exemple #1
0
 def dispatch(self, request):
     if 'error' in request.GET or not 'code' in request.GET:
         # TODO: Distinguish cancel from error
         return render_authentication_error(request)
     app = self.adapter.get_provider().get_app(self.request)
     client = self.get_client(request, app)
     try:
         r = praw.Reddit('OAuth Sketchdaily Schedule  by u/davidwinters ver 0.1.')
         r.set_oauth_app_info(client.consumer_key, client.consumer_secret, 'http://themes.sketchdaily.net/accounts/redditprovider/login/callback/')
         access_token = r.get_access_information(request.GET['code'])
         user = r.get_me()
         extra = r.get_my_moderation()
         # access_token = client.get_access_token(request.GET['code'])
         token = SocialToken(token=access_token)
         #token = self.adapter.parse_token(access_token)
         token.app = app
         login = self.adapter.complete_login(request,
                                             app,
                                             token,
                                             response=access_token, user=user, extra=extra)
         token.account = login.account
         login.token = token
         login.state = SocialLogin.unmarshall_state(request.REQUEST
                                                    .get('uniqueKey'))
         return complete_social_login(request, login)
     except OAuth2Error:
         return render_authentication_error(request)
Exemple #2
0
 def dispatch(self, request):
     if 'error' in request.GET or not 'code' in request.GET:
         # TODO: Distinguish cancel from error
         return render_authentication_error(request)
     app = self.adapter.get_provider().get_app(self.request)
     client = self.get_client(request, app)
     try:
         r = praw.Reddit(
             'OAuth Sketchdaily Schedule  by u/davidwinters ver 0.1.')
         r.set_oauth_app_info(
             client.consumer_key, client.consumer_secret,
             'http://themes.sketchdaily.net/accounts/redditprovider/login/callback/'
         )
         access_token = r.get_access_information(request.GET['code'])
         user = r.get_me()
         extra = r.get_my_moderation()
         # access_token = client.get_access_token(request.GET['code'])
         token = SocialToken(token=access_token)
         #token = self.adapter.parse_token(access_token)
         token.app = app
         login = self.adapter.complete_login(request,
                                             app,
                                             token,
                                             response=access_token,
                                             user=user,
                                             extra=extra)
         token.account = login.account
         login.token = token
         login.state = SocialLogin.unmarshall_state(
             request.REQUEST.get('uniqueKey'))
         return complete_social_login(request, login)
     except OAuth2Error:
         return render_authentication_error(request)
Exemple #3
0
    def post(self, request):
        serializer = OAuthTokenSerializer(data=request.data)

        non_field_error_key = getattr(
            settings, "NON_FIELD_ERRORS_KEY", "non_field_errors"
        )

        provider = self.provider(request)

        err_r = JsonResponse({non_field_error_key: {"error": "Access token invalid"}})
        if not serializer.is_valid():
            return err_r
        data = serializer.validated_data

        # Create the token
        # from allauth.socialaccount.providers.oauth2.views.OAuth2Adapter.parse_token
        token = SocialToken(token=data["access_token"])
        token.token_secret = data.get("refresh_token", "")
        token.app = provider.get_app(request)
        expires_in = data.get(self.expires_in_key, None)
        if expires_in:
            token.expires_at = timezone.now() + timedelta(seconds=int(expires_in))

        # Verify the access token works
        resp = requests.get(
            self.profile_url,
            params={"access_token": token.token, "alt": "json"},
        )
        if resp.status_code > 299:
            # We've got a problem
            return err_r
        extra_data = resp.json()
        login = provider.sociallogin_from_response(request, extra_data)
        login.lookup()
        if not login.is_existing:
            login.save(request)

        # Create SimpleJWT tokens for consumer authentication purposes
        simple_token = RefreshToken.for_user(login.user)

        def save_info_in_simple_token(_token):
            _token["provider_id"] = provider.id
            _token["provider_access_token"] = data["access_token"]
            _token["provider_refresh_token"] = token.token_secret
            return str(_token)

        return JsonResponse(
            {
                "access_token": save_info_in_simple_token(simple_token.access_token),
                "refresh_token": save_info_in_simple_token(simple_token),
            }
        )
    def validate(self, attrs):
        view = self.context.get('view')
        request = self._get_request()

        if not view:
            raise serializers.ValidationError(
                "View is not defined, pass it as a context variable")

        adapter_class = getattr(view, 'adapter_class', None)
        if not adapter_class:
            raise serializers.ValidationError("Define adapter_class in view")

        adapter = adapter_class(request)
        app = adapter.get_provider().get_app(request)

        access_token = attrs.get('access_token')
        token_secret = attrs.get('token_secret')

        request.session['oauth_api.twitter.com_access_token'] = {
            'oauth_token': access_token,
            'oauth_token_secret': token_secret,
        }
        token = SocialToken(token=access_token, token_secret=token_secret)
        token.app = app

        try:
            login = self.get_social_login(adapter, app, token, access_token)
            complete_social_login(request, login)
        except OAuthError as e:
            raise serializers.ValidationError(str(e))

        if not login.is_existing:
            # We have an account already signed up in a different flow
            # with the same email address: raise an exception.
            # This needs to be handled in the frontend. We can not just
            # link up the accounts due to security constraints
            if allauth_settings.UNIQUE_EMAIL:
                # Do we have an account already with this email address?
                account_exists = get_user_model().objects.filter(
                    email=login.user.email, ).exists()
                if account_exists:
                    raise serializers.ValidationError(
                        _("User is already registered with this e-mail address."
                          ))

            login.lookup()
            login.save(request, connect=True)
        attrs['user'] = login.account.user

        return attrs
    def validate(self, attrs):
        view = self.context.get('view')
        request = self._get_request()

        if not view:
            raise serializers.ValidationError(
                'View is not defined, pass it as a context variable'
            )

        adapter_class = getattr(view, 'adapter_class', None)
        if not adapter_class:
            raise serializers.ValidationError('Define adapter_class in view')

        adapter = adapter_class()
        app = adapter.get_provider().get_app(request)

        if('access_token' in attrs) and ('token_secret' in attrs):
            access_token = attrs.get('access_token')
            token_secret = attrs.get('token_secret')
        else:
            raise serializers.ValidationError('Incorrect input. access_token and token_secret are required.')

        request.session['oauth_api.twitter.com_access_token'] = {
            'oauth_token': access_token,
            'oauth_token_secret': token_secret,
        }
        token = SocialToken(token=access_token, token_secret=token_secret)
        token.app = app

        try:
            login = self.get_social_login(adapter, app, token, access_token)
            complete_social_login(request, login)
        except HTTPError:
            raise serializers.ValidationError('Incorrect value')

        if not login.is_existing:
            login.lookup()
            login.save(request, connect=True)
        attrs['user'] = login.account.user

        return attrs
    def validate(self, attrs):
        view = self.context.get('view')
        request = self._get_request()

        if not view:
            raise serializers.ValidationError(
                'View is not defined, pass it as a context variable')

        adapter_class = getattr(view, 'adapter_class', None)
        if not adapter_class:
            raise serializers.ValidationError('Define adapter_class in view')

        adapter = adapter_class()
        app = adapter.get_provider().get_app(request)

        if ('access_token' in attrs) and ('token_secret' in attrs):
            access_token = attrs.get('access_token')
            token_secret = attrs.get('token_secret')
        else:
            raise serializers.ValidationError(
                'Incorrect input. access_token and token_secret are required.')

        request.session['oauth_api.twitter.com_access_token'] = {
            'oauth_token': access_token,
            'oauth_token_secret': token_secret,
        }
        token = SocialToken(token=access_token, token_secret=token_secret)
        token.app = app

        try:
            login = self.get_social_login(adapter, app, token, access_token)
            complete_social_login(request, login)
        except OAuthError as e:
            raise serializers.ValidationError(str(e))

        if not login.is_existing:
            login.lookup()
            login.save(request, connect=True)
        attrs['user'] = login.account.user

        return attrs
Exemple #7
0
    def validate(self, attrs):
        """Validate social login user."""
        view = self.context.get('view')
        request = self._get_request()

        if not view:
            raise serializers.ValidationError(
                'View is not defined, pass it as a context variable')

        adapter_class = getattr(view, 'adapter_class', None)
        if not adapter_class:
            raise serializers.ValidationError('Define adapter_class in view')

        adapter = adapter_class()
        app = adapter.get_provider().get_app(request)

        if ('access_token' in attrs) and ('token_secret' in attrs):
            access_token = attrs.get('access_token')
            token_secret = attrs.get('token_secret')
        else:
            raise serializers.ValidationError(
                'Incorrect input. access_token and token_secret are required.')

        request.session['oauth_api.twitter.com_access_token'] = {
            'oauth_token': access_token,
            'oauth_token_secret': token_secret,
        }
        token = SocialToken(token=access_token, token_secret=token_secret)
        token.app = app

        if 'account_type' in attrs:
            account_type = attrs.get('account_type')
        else:
            account_type = 'talent'
        try:
            login, response = CustomSocialLoginSerializer.get_social_login(
                self, adapter, app, token, access_token, account_type)
            # Temp fix because twitter response email is not coming.
            if login.user.email == '':
                login.user.email = None
            complete_social_login(request, login, response)
        except HTTPError:
            raise serializers.ValidationError('Incorrect value')

        if not login.is_existing:
            login.lookup()
            login.save(request, connect=True)

        data = RegisterSerializer().validate_account_type(
            account_type=account_type)
        user_account_type = list(data.values())[0]

        try:
            temp_user = login.account.user.person
            typ, created = PersonType.objects.get_or_create(
                person_type=user_account_type)
        except User.DoesNotExist:
            temp_user = login.account.user.company
            typ, created = CompanyType.objects.get_or_create(
                company_type=user_account_type)
        temp_user.typ.add(typ)

        referral = create_referral(temp_user)
        temp_user.referral = referral
        # provide incentive to user who referred this user.

        request = self.context.get('request')
        if request and 'referral_code' in request.data:
            referrer_user = get_referrer_user(request, user=temp_user)

        attrs['user'] = login.account.user

        return attrs