示例#1
0
 def test_login(self):
     resp = self.client.post(reverse(views.login),
                             dict(openid='http://me.yahoo.com'))
     assert 'login.yahooapis' in resp['location']
     with patch('allauth.socialaccount.providers'
                '.openid.views._openid_consumer') as consumer_mock:
         client = Mock()
         complete = Mock()
         consumer_mock.return_value = client
         client.complete = complete
         complete_response = Mock()
         complete.return_value = complete_response
         complete_response.status = consumer.SUCCESS
         complete_response.identity_url = 'http://dummy/john/'
         with patch('allauth.socialaccount.providers'
                    '.openid.utils.SRegResponse') as sr_mock:
             with patch('allauth.socialaccount.providers'
                        '.openid.utils.FetchResponse') as fr_mock:
                 sreg_mock = Mock()
                 ax_mock = Mock()
                 sr_mock.fromSuccessResponse = sreg_mock
                 fr_mock.fromSuccessResponse = ax_mock
                 sreg_mock.return_value = {}
                 ax_mock.return_value = {AXAttribute.PERSON_FIRST_NAME:
                                         ['raymond']}
                 resp = self.client.post(reverse('openid_callback'))
                 self.assertRedirects(
                     resp, "/accounts/profile/",
                     fetch_redirect_response=False
                 )
                 get_user_model().objects.get(first_name='raymond')
示例#2
0
 def test_login(self):
     resp = self.client.post(reverse(views.login),
                             dict(openid='http://me.yahoo.com'))
     assert 'login.yahooapis' in resp['location']
     with patch('allauth.socialaccount.providers'
                '.openid.views._openid_consumer') as consumer_mock:
         client = Mock()
         complete = Mock()
         consumer_mock.return_value = client
         client.complete = complete
         complete_response = Mock()
         complete.return_value = complete_response
         complete_response.status = consumer.SUCCESS
         complete_response.identity_url = 'http://dummy/john/'
         with patch('allauth.socialaccount.providers'
                    '.openid.utils.SRegResponse') as sr_mock:
             with patch('allauth.socialaccount.providers'
                        '.openid.utils.FetchResponse') as fr_mock:
                 sreg_mock = Mock()
                 ax_mock = Mock()
                 sr_mock.fromSuccessResponse = sreg_mock
                 fr_mock.fromSuccessResponse = ax_mock
                 sreg_mock.return_value = {}
                 ax_mock.return_value = {
                     AXAttribute.PERSON_FIRST_NAME: ['raymond']
                 }
                 resp = self.client.post(reverse('openid_callback'))
                 self.assertRedirects(resp,
                                      "/accounts/profile/",
                                      fetch_redirect_response=False)
                 get_user_model().objects.get(first_name='raymond')
示例#3
0
 def test_login_by_token(self):
     resp = self.client.get(reverse('account_login'))
     with patch('allauth.socialaccount.providers.facebook.views'
                '.requests') as requests_mock:
         mocks = [self.get_mocked_response().json()]
         requests_mock.get.return_value.json \
             = lambda: mocks.pop()
         resp = self.client.post(reverse('facebook_login_by_token'),
                                 data={'access_token': 'dummy'})
         self.assertRedirects(resp, 'http://testserver/accounts/profile/',
                              fetch_redirect_response=False)
示例#4
0
 def test_login_by_token_reauthenticate(self):
     resp = self.client.get(reverse('account_login'))
     nonce = json.loads(
         resp.context['fb_data'])['loginOptions']['auth_nonce']
     with patch('allauth.socialaccount.providers.facebook.views'
                '.requests') as requests_mock:
         mocks = [self.get_mocked_response().json(),
                  {'auth_nonce': nonce}]
         requests_mock.get.return_value.json \
             = lambda: mocks.pop()
         resp = self.client.post(reverse('facebook_login_by_token'),
                                 data={'access_token': 'dummy'})
         self.assertRedirects(resp, 'http://testserver/accounts/profile/',
                              fetch_redirect_response=False)
示例#5
0
 def test_login_by_token_reauthenticate(self):
     resp = self.client.get(reverse('account_login'))
     nonce = json.loads(
         resp.context['fb_data'])['loginOptions']['auth_nonce']
     with patch('allauth.socialaccount.providers.facebook.views'
                '.requests') as requests_mock:
         mocks = [self.get_mocked_response().json(), {'auth_nonce': nonce}]
         requests_mock.get.return_value.json \
             = lambda: mocks.pop()
         resp = self.client.post(reverse('facebook_login_by_token'),
                                 data={'access_token': 'dummy'})
         self.assertRedirects(resp,
                              '/accounts/profile/',
                              fetch_redirect_response=False)
示例#6
0
 def test_login_redirect(self):
     response = self.client.get(reverse(views.login))
     redirect_url = reverse(views.callback)
     full_redirect_url = "http://testserver" + redirect_url
     secret = self.app.secret + full_redirect_url
     redirect_url_hash = md5(secret.encode("utf-8")).hexdigest()
     params = {
         'app': self.app.client_id,
         'hash': redirect_url_hash,
         'redirect': full_redirect_url,
     }
     self.assertRedirects(response, '%s?%s' %
                          (views.AUTHORIZE_URL, urlencode(params)),
                          fetch_redirect_response=False)
示例#7
0
 def test_login_redirect(self):
     response = self.client.get(reverse(views.login))
     redirect_url = 'http://testserver' + reverse(views.callback)
     redirect_url_hash = md5(
         (self.app.secret + redirect_url).encode('utf-8')).hexdigest()
     params = {
         'app': self.app.client_id,
         'hash': redirect_url_hash,
         'redirect': redirect_url,
     }
     self.assertRedirects(response,
                          '%s?%s' %
                          (views.AUTHORIZE_URL, urlencode(params)),
                          fetch_redirect_response=False)
示例#8
0
 def test_login_redirect(self):
     response = self.client.get(reverse(views.login),
                                follow=False, **{'HTTP_HOST': 'localhost'})
     redirect_url = 'http://localhost' + reverse(views.callback)
     redirect_url_hash = md5(
         (self.app.secret + redirect_url).encode('utf-8')).hexdigest()
     params = {
         'app': self.app.client_id,
         'hash': redirect_url_hash,
         'redirect': redirect_url,
     }
     self.assertRedirects(response, '%s?%s' %
                          (views.AUTHORIZE_URL, urlencode(params)),
                          fetch_redirect_response=False)
示例#9
0
    def save(self, request, **kwargs):
        current_site = get_current_site(request)
        email = self.cleaned_data["email"]
        token_generator = kwargs.get("token_generator",
                                     default_token_generator)

        for user in self.users:

            temp_key = token_generator.make_token(user)

            # save it to the password reset model
            # password_reset = PasswordReset(user=user, temp_key=temp_key)
            # password_reset.save()

            # send the password reset email
            path = reverse("account_reset_password_from_key",
                           kwargs=dict(uidb36=user_pk_to_url_str(user),
                                       key=temp_key))
            url = build_absolute_uri(request, path)

            context = {
                "current_site": current_site,
                "user": user,
                "password_reset_url": url,
                "request": request
            }

            if app_settings.AUTHENTICATION_METHOD \
                    != AuthenticationMethod.EMAIL:
                context['username'] = user_username(user)
            get_adapter(request).send_mail('account/email/password_reset_key',
                                           email, context)
        return self.cleaned_data["email"]
示例#10
0
 def dispatch(self, request):
     """
     View to handle final steps of OAuth based authentication where the user
     gets redirected back to from the service provider
     """
     login_done_url = reverse(self.adapter.provider_id + "_callback")
     client = self._get_client(request, login_done_url)
     if not client.is_valid():
         if "denied" in request.GET:
             error = AuthError.CANCELLED
         else:
             error = AuthError.UNKNOWN
         extra_context = dict(oauth_client=client)
         return render_authentication_error(
             request, self.adapter.provider_id, error=error, extra_context=extra_context
         )
     app = self.adapter.get_provider().get_app(request)
     try:
         access_token = client.get_access_token()
         token = SocialToken(
             app=app,
             token=access_token["oauth_token"],
             # .get() -- e.g. Evernote does not feature a secret
             token_secret=access_token.get("oauth_token_secret", ""),
         )
         login = self.adapter.complete_login(request, app, token, response=access_token)
         login.token = token
         login.state = SocialLogin.unstash_state(request)
         return complete_social_login(request, login)
     except OAuthError as e:
         return render_authentication_error(request, self.adapter.provider_id, exception=e)
示例#11
0
    def test_google_compelete_login_401(self):
        from allauth.socialaccount.providers.google.views import \
            GoogleOAuth2Adapter

        class LessMockedResponse(MockedResponse):
            def raise_for_status(self):
                if self.status_code != 200:
                    raise HTTPError(None)
        request = RequestFactory().get(
            reverse(self.provider.id + '_login'),
            dict(process='login'))

        adapter = GoogleOAuth2Adapter(request)
        app = adapter.get_provider().get_app(request)
        token = SocialToken(token='some_token')
        response_with_401 = LessMockedResponse(
            401, """
            {"error": {
              "errors": [{
                "domain": "global",
                "reason": "authError",
                "message": "Invalid Credentials",
                "locationType": "header",
                "location": "Authorization" } ],
              "code": 401,
              "message": "Invalid Credentials" }
            }""")
        with patch(
                'allauth.socialaccount.providers.google.views'
                '.requests') as patched_requests:
            patched_requests.get.return_value = response_with_401
            with self.assertRaises(HTTPError):
                adapter.complete_login(request, app, token)
示例#12
0
    def test_webmonitor_compelete_login_401(self):
        from allauth.socialaccount.providers.webmonitor.views import \
            WebmonitorOAuth2Adapter

        class LessMockedResponse(MockedResponse):
            def raise_for_status(self):
                if self.status_code != 200:
                    raise HTTPError(None)

        request = RequestFactory().get(reverse(self.provider.id + '_login'),
                                       dict(process='login'))

        adapter = WebmonitorOAuth2Adapter(request)
        app = adapter.get_provider().get_app(request)
        token = SocialToken(token='some_token')
        response_with_401 = LessMockedResponse(
            401, """
            {"error": {
              "errors": [{
                "domain": "global",
                "reason": "authError",
                "message": "Invalid Credentials",
                "locationType": "header",
                "location": "Authorization" } ],
              "code": 401,
              "message": "Invalid Credentials" }
            }""")
        with patch('allauth.socialaccount.providers.webmonitor.views'
                   '.requests') as patched_requests:
            patched_requests.get.return_value = response_with_401
            with self.assertRaises(HTTPError):
                adapter.complete_login(request, app, token)
示例#13
0
 def get_auth_params(self, request, action):
     params = super(UntappdProvider, self).get_auth_params(request, action)
     # Untappd uses redirect_url instead of redirect_uri
     params['redirect_url'] = request.build_absolute_uri(
         reverse(self.id + '_callback')
     )
     return params
示例#14
0
文件: tests.py 项目: syurk738/labpin
 def login(self, resp_mock, process='login', with_refresh_token=True):
     resp = self.client.get(reverse(self.provider.id + '_login'), {
         'process': process,
         'shop': 'test'
     })
     self.assertEqual(resp.status_code, 200)  # No re-direct, JS must do it
     actual_content = resp.content.decode('utf8')
     self.assertTrue(
         'script' in actual_content,
         'Content missing script tag. [Actual: {}]'.format(actual_content))
     self.assertTrue(
         resp.xframe_options_exempt,
         'Redirect JS must be allowed to run in Shopify iframe')
     self.assertTrue(
         '<!DOCTYPE html><html><head>' in actual_content
         and '</head><body></body></html>' in actual_content,
         'Expected standard HTML skeleton. [Actual: {}]'.format(
             actual_content))
     p = urlparse(
         actual_content.split(";</script>")[0].split('location.href = "')
         [1])
     q = parse_qs(p.query)
     resp = self._complete_shopify_login(q, resp, resp_mock,
                                         with_refresh_token)
     return resp
示例#15
0
 def test_discovery_failure(self):
     """
     This used to generate a server 500:
     DiscoveryFailure: No usable OpenID services found
     for http://www.google.com/
     """
     resp = self.client.post(reverse('openid_login'),
                             dict(openid='http://www.google.com'))
     self.assertTrue('openid' in resp.context['form'].errors)
示例#16
0
 def login(self, resp_mock, process='login', with_refresh_token=True):
     resp = self.client.get(reverse(self.provider.id + '_login'),
                            {'process': process, 'shop': 'test'})
     self.assertEqual(resp.status_code, 302)
     p = urlparse(resp['location'])
     q = parse_qs(p.query)
     resp = self._complete_shopify_login(q, resp, resp_mock,
                                         with_refresh_token)
     return resp
示例#17
0
 def get_email_confirmation_url(self, request, emailconfirmation):
     """Constructs the email confirmation (activation) url.
     Note that if you have architected your system such that email
     confirmations are sent outside of the request context `request`
     can be `None` here.
     """
     url = reverse("account_confirm_email", args=[emailconfirmation.key])
     ret = build_absolute_uri(request, url)
     return ret
示例#18
0
 def login(self, resp_mock, process='login', with_refresh_token=True):
     resp = self.client.get(reverse(self.provider.id + '_login'),
                            {'process': process, 'shop': 'test'})
     self.assertEqual(resp.status_code, 302)
     p = urlparse(resp['location'])
     q = parse_qs(p.query)
     resp = self._complete_shopify_login(q, resp, resp_mock,
                                         with_refresh_token)
     return resp
示例#19
0
 def test_discovery_failure(self):
     """
     This used to generate a server 500:
     DiscoveryFailure: No usable OpenID services found
     for http://www.google.com/
     """
     resp = self.client.post(reverse('openid_login'),
                             dict(openid='http://www.google.com'))
     self.assertTrue('openid' in resp.context['form'].errors)
示例#20
0
 def test_login_with_extra_attributes(self):
     with patch('allauth.socialaccount.providers.openid.views.QUERY_EMAIL',
                True):
         resp = self.client.post(reverse(views.login),
                                 dict(openid='http://me.yahoo.com'))
     assert 'login.yahooapis' in resp['location']
     with patch('allauth.socialaccount.providers'
                '.openid.views._openid_consumer') as consumer_mock:
         client = Mock()
         complete = Mock()
         endpoint = Mock()
         consumer_mock.return_value = client
         client.complete = complete
         complete_response = Mock()
         complete.return_value = complete_response
         complete_response.endpoint = endpoint
         complete_response.endpoint.server_url = 'http://me.yahoo.com'
         complete_response.status = consumer.SUCCESS
         complete_response.identity_url = 'http://dummy/john/'
         with patch('allauth.socialaccount.providers'
                    '.openid.utils.SRegResponse') as sr_mock:
             with patch('allauth.socialaccount.providers'
                        '.openid.utils.FetchResponse') as fr_mock:
                 sreg_mock = Mock()
                 ax_mock = Mock()
                 sr_mock.fromSuccessResponse = sreg_mock
                 fr_mock.fromSuccessResponse = ax_mock
                 sreg_mock.return_value = {}
                 ax_mock.return_value = {
                     AXAttribute.CONTACT_EMAIL: ['*****@*****.**'],
                     AXAttribute.PERSON_FIRST_NAME: ['raymond'],
                     'http://axschema.org/contact/phone/default':
                     ['123456789']
                 }
                 resp = self.client.post(reverse('openid_callback'))
                 self.assertRedirects(resp,
                                      "/accounts/profile/",
                                      fetch_redirect_response=False)
                 socialaccount = \
                     SocialAccount.objects.get(user__first_name='raymond')
                 self.assertEqual(socialaccount.extra_data.get('phone'),
                                  '123456789')
示例#21
0
 def test_login_with_extra_attributes(self):
     with patch('allauth.socialaccount.providers.openid.views.QUERY_EMAIL',
                True):
         resp = self.client.post(reverse(views.login),
                                 dict(openid='http://me.yahoo.com'))
     assert 'login.yahooapis' in resp['location']
     with patch('allauth.socialaccount.providers'
                '.openid.views._openid_consumer') as consumer_mock:
         client = Mock()
         complete = Mock()
         endpoint = Mock()
         consumer_mock.return_value = client
         client.complete = complete
         complete_response = Mock()
         complete.return_value = complete_response
         complete_response.endpoint = endpoint
         complete_response.endpoint.server_url = 'http://me.yahoo.com'
         complete_response.status = consumer.SUCCESS
         complete_response.identity_url = 'http://dummy/john/'
         with patch('allauth.socialaccount.providers'
                    '.openid.utils.SRegResponse') as sr_mock:
             with patch('allauth.socialaccount.providers'
                        '.openid.utils.FetchResponse') as fr_mock:
                 sreg_mock = Mock()
                 ax_mock = Mock()
                 sr_mock.fromSuccessResponse = sreg_mock
                 fr_mock.fromSuccessResponse = ax_mock
                 sreg_mock.return_value = {}
                 ax_mock.return_value = {
                     AXAttribute.CONTACT_EMAIL: ['*****@*****.**'],
                     AXAttribute.PERSON_FIRST_NAME: ['raymond'],
                     'http://axschema.org/contact/phone/default':
                         ['123456789']}
                 resp = self.client.post(reverse('openid_callback'))
                 self.assertRedirects(
                     resp, "/accounts/profile/",
                     fetch_redirect_response=False
                 )
                 socialaccount = \
                     SocialAccount.objects.get(user__first_name='raymond')
                 self.assertEqual(
                     socialaccount.extra_data.get('phone'), '123456789')
示例#22
0
def resolve_url(to):
    """
    Subset of django.shortcuts.resolve_url (that one is 1.5+)
    """
    try:
        return reverse(to)
    except NoReverseMatch:
        # If this doesn't "feel" like a URL, re-raise.
        if '/' not in to and '.' not in to:
            raise
    # Finally, fall back and assume it's a URL
    return to
示例#23
0
def resolve_url(to):
    """
    Subset of django.shortcuts.resolve_url (that one is 1.5+)
    """
    try:
        return reverse(to)
    except NoReverseMatch:
        # If this doesn't "feel" like a URL, re-raise.
        if "/" not in to and "." not in to:
            raise
    # Finally, fall back and assume it's a URL
    return to
示例#24
0
 def dispatch(self, request):
     callback_url = reverse(self.adapter.provider_id + "_callback")
     SocialLogin.stash_state(request)
     action = request.GET.get("action", AuthAction.AUTHENTICATE)
     provider = self.adapter.get_provider()
     auth_url = provider.get_auth_url(request, action) or self.adapter.authorize_url
     auth_params = provider.get_auth_params(request, action)
     client = self._get_client(request, callback_url)
     try:
         return client.get_redirect(auth_url, auth_params)
     except OAuthError as e:
         return render_authentication_error(request, self.adapter.provider_id, exception=e)
示例#25
0
 def login(self, resp_mock, process='login', with_refresh_token=True):
     resp = self.client.get(reverse(self.provider.id + '_login'), {
         'process': process,
         'shop': 'test'
     })
     p = urlparse(resp['location'])
     q = parse_qs(p.query)
     complete_url = reverse(self.provider.id + '_callback')
     self.assertGreater(q['redirect_uri'][0].find(complete_url), 0)
     response_json = self \
         .get_login_response_json(with_refresh_token=with_refresh_token)
     with mocked_response(
             MockedResponse(200, response_json,
                            {'content-type': 'application/json'}),
             resp_mock):
         resp = self.client.get(complete_url, {
             'code': 'test',
             'state': q['state'][0],
             'shop': 'test',
         })
     return resp
示例#26
0
def login(request):
    if 'openid' in request.GET or request.method == 'POST':
        form = LoginForm(
            dict(list(request.GET.items()) + list(request.POST.items()))
        )
        if form.is_valid():
            client = _openid_consumer(request)
            try:
                auth_request = client.begin(form.cleaned_data['openid'])
                if QUERY_EMAIL:
                    sreg = SRegRequest()
                    for name in SRegFields:
                        sreg.requestField(field_name=name,
                                          required=True)
                    auth_request.addExtension(sreg)
                    ax = FetchRequest()
                    for name in AXAttributes:
                        ax.add(AttrInfo(name,
                                        required=True))
                    provider = OpenIDProvider(request)
                    server_settings = \
                        provider.get_server_settings(request.GET.get('openid'))
                    extra_attributes = \
                        server_settings.get('extra_attributes', [])
                    for _, name, required in extra_attributes:
                        ax.add(AttrInfo(name,
                                        required=required))
                    auth_request.addExtension(ax)
                callback_url = reverse(callback)
                SocialLogin.stash_state(request)
                # https://github.com/pennersr/django-allauth/issues/1523
                auth_request.return_to_args['next'] = \
                    form.cleaned_data.get('next', '/')
                redirect_url = auth_request.redirectURL(
                    request.build_absolute_uri('/'),
                    request.build_absolute_uri(callback_url))
                return HttpResponseRedirect(redirect_url)
            # UnicodeDecodeError:
            # see https://github.com/necaris/python3-openid/issues/1
            except (UnicodeDecodeError, DiscoveryFailure) as e:
                if request.method == 'POST':
                    form._errors["openid"] = form.error_class([e])
                else:
                    return render_authentication_error(
                        request,
                        OpenIDProvider.id,
                        exception=e)
    else:
        form = LoginForm(initial={'next': request.GET.get('next'),
                                  'process': request.GET.get('process')})
    d = dict(form=form)
    return render(request, "openid/login.html", d)
示例#27
0
 def login(self, resp_mock, process='login', with_refresh_token=True):
     resp = self.client.get(reverse(self.provider.id + '_login'),
                            {'process': process, 'shop': 'test'})
     p = urlparse(resp['location'])
     q = parse_qs(p.query)
     complete_url = reverse(self.provider.id+'_callback')
     self.assertGreater(q['redirect_uri'][0]
                        .find(complete_url), 0)
     response_json = self \
         .get_login_response_json(with_refresh_token=with_refresh_token)
     with mocked_response(
             MockedResponse(
                 200,
                 response_json,
                 {'content-type': 'application/json'}),
             resp_mock):
         resp = self.client.get(complete_url,
                                {'code': 'test',
                                 'state': q['state'][0],
                                 'shop': 'test',
                                 })
     return resp
示例#28
0
    def test_login(self):
        with patch('allauth.socialaccount.providers.persona.views'
                   '.requests') as requests_mock:
            requests_mock.post.return_value.json.return_value = {
                'status': 'okay',
                'email': '*****@*****.**'
            }

            resp = self.client.post(reverse('persona_login'),
                                    dict(assertion='dummy'))
            self.assertRedirects(resp, '/accounts/profile/',
                                 fetch_redirect_response=False)
            get_user_model().objects.get(email='*****@*****.**')
示例#29
0
    def test_login(self):
        with patch('allauth.socialaccount.providers.persona.views'
                   '.requests') as requests_mock:
            requests_mock.post.return_value.json.return_value = {
                'status': 'okay',
                'email': '*****@*****.**'
            }

            resp = self.client.post(reverse('persona_login'),
                                    dict(assertion='dummy'))
            self.assertRedirects(resp, '/accounts/profile/',
                                 fetch_redirect_response=False)
            get_user_model().objects.get(email='*****@*****.**')
示例#30
0
def login(request):
    app = providers.registry.by_id(
        DraugiemProvider.id, request).get_app(request)
    redirect_url = request.build_absolute_uri(reverse(callback))
    redirect_url_hash = md5((
        app.secret + redirect_url).encode('utf-8')).hexdigest()
    params = {
        'app': app.client_id,
        'hash': redirect_url_hash,
        'redirect': redirect_url,
    }
    SocialLogin.stash_state(request)
    return HttpResponseRedirect('%s?%s' % (AUTHORIZE_URL, urlencode(params)))
示例#31
0
def login(request):
    app = providers.registry.by_id(DraugiemProvider.id,
                                   request).get_app(request)
    redirect_url = request.build_absolute_uri(reverse(callback))
    redirect_url_hash = md5(
        (app.secret + redirect_url).encode('utf-8')).hexdigest()
    params = {
        'app': app.client_id,
        'hash': redirect_url_hash,
        'redirect': redirect_url,
    }
    SocialLogin.stash_state(request)
    return HttpResponseRedirect('%s?%s' % (AUTHORIZE_URL, urlencode(params)))
 def get_client(self, request, app):
     callback_url = reverse(self.adapter.provider_id + "_callback")
     protocol = (self.adapter.redirect_uri_protocol
                 or app_settings.DEFAULT_HTTP_PROTOCOL)
     callback_url = build_absolute_uri(request,
                                       callback_url,
                                       protocol=protocol)
     provider = self.adapter.get_provider()
     scope = provider.get_scope(request)
     client = WeixinOAuth2Client(self.request, app.client_id, app.secret,
                                 self.adapter.access_token_method,
                                 self.adapter.access_token_url,
                                 callback_url, scope)
     return client
def login(request):
    if 'openid' in request.GET or request.method == 'POST':
        form = LoginForm(
            dict(list(request.GET.items()) + list(request.POST.items())))
        if form.is_valid():
            client = _openid_consumer(request)
            try:
                auth_request = client.begin(form.cleaned_data['openid'])
                if QUERY_EMAIL:
                    sreg = SRegRequest()
                    for name in SRegFields:
                        sreg.requestField(field_name=name, required=True)
                    auth_request.addExtension(sreg)
                    ax = FetchRequest()
                    for name in AXAttributes:
                        ax.add(AttrInfo(name, required=True))
                    provider = OpenIDProvider(request)
                    server_settings = \
                        provider.get_server_settings(request.GET.get('openid'))
                    extra_attributes = \
                        server_settings.get('extra_attributes', [])
                    for _, name, required in extra_attributes:
                        ax.add(AttrInfo(name, required=required))
                    auth_request.addExtension(ax)
                callback_url = reverse(callback)
                SocialLogin.stash_state(request)
                # https://github.com/pennersr/django-allauth/issues/1523
                auth_request.return_to_args['next'] = \
                    form.cleaned_data.get('next', '/')
                redirect_url = auth_request.redirectURL(
                    request.build_absolute_uri('/'),
                    request.build_absolute_uri(callback_url))
                return HttpResponseRedirect(redirect_url)
            # UnicodeDecodeError:
            # see https://github.com/necaris/python3-openid/issues/1
            except (UnicodeDecodeError, DiscoveryFailure) as e:
                if request.method == 'POST':
                    form._errors["openid"] = form.error_class([e])
                else:
                    return render_authentication_error(request,
                                                       OpenIDProvider.id,
                                                       exception=e)
    else:
        form = LoginForm(initial={
            'next': request.GET.get('next'),
            'process': request.GET.get('process')
        })
    d = dict(form=form)
    return render(request, "openid/login.html", d)
示例#34
0
 def dispatch(self, request):
     callback_url = reverse(self.adapter.provider_id + "_callback")
     SocialLogin.stash_state(request)
     action = request.GET.get('action', AuthAction.AUTHENTICATE)
     provider = self.adapter.get_provider()
     auth_url = provider.get_auth_url(request,
                                      action) or self.adapter.authorize_url
     auth_params = provider.get_auth_params(request, action)
     client = self._get_client(request, callback_url)
     try:
         return client.get_redirect(auth_url, auth_params)
     except OAuthError as e:
         return render_authentication_error(request,
                                            self.adapter.provider_id,
                                            exception=e)
示例#35
0
文件: tests.py 项目: syurk738/labpin
 def _complete_shopify_login(self, q, resp, resp_mock, with_refresh_token):
     complete_url = reverse(self.provider.id + '_callback')
     self.assertGreater(q['redirect_uri'][0].find(complete_url), 0)
     response_json = self \
         .get_login_response_json(with_refresh_token=with_refresh_token)
     with mocked_response(
             MockedResponse(200, response_json,
                            {'content-type': 'application/json'}),
             resp_mock):
         resp = self.client.get(complete_url, {
             'code': 'test',
             'state': q['state'][0],
             'shop': 'test',
         })
     return resp
示例#36
0
def login(request):
    app = providers.registry.by_id(
        DraugiemProvider.id, request).get_app(request)
    request_scheme = request.META['wsgi.url_scheme']
    request_host = request.META['HTTP_HOST']
    request_path = reverse(callback)
    redirect_url = '%s://%s%s' % (request_scheme, request_host, request_path)
    redirect_url_hash = md5((
        app.secret + redirect_url).encode('utf-8')).hexdigest()
    params = {
        'app': app.client_id,
        'hash': redirect_url_hash,
        'redirect': redirect_url,
    }
    SocialLogin.stash_state(request)
    return HttpResponseRedirect('%s?%s' % (AUTHORIZE_URL, urlencode(params)))
示例#37
0
def login(request):
    app = providers.registry.by_id(DraugiemProvider.id,
                                   request).get_app(request)
    request_scheme = request.META['wsgi.url_scheme']
    request_host = request.META['HTTP_HOST']
    request_path = reverse(callback)
    redirect_url = '%s://%s%s' % (request_scheme, request_host, request_path)
    redirect_url_hash = md5(
        (app.secret + redirect_url).encode('utf-8')).hexdigest()
    params = {
        'app': app.client_id,
        'hash': redirect_url_hash,
        'redirect': redirect_url,
    }
    SocialLogin.stash_state(request)
    return HttpResponseRedirect('%s?%s' % (AUTHORIZE_URL, urlencode(params)))
示例#38
0
 def get_connect_redirect_url(self, request, socialaccount):
     """
     Returns the default URL to redirect to after successfully
     connecting a social account.
     """
     print('yes')
     assert is_authenticated(request.user)
     if 'success_url' in request.session:
         print(request.session['success_url'])
         success_url = request.session['success_url']
         del request.session['success_url']
     elif 'next' in request.path:
         success_url = request.GET['next']
     else:
         success_url = reverse('socialaccount_connections')
     return success_url
示例#39
0
 def get_client(self, request, app):
     callback_url = reverse(self.adapter.provider_id + "_callback")
     callback_url = build_absolute_uri(
         request, callback_url,
         protocol=self.adapter.redirect_uri_protocol)
     provider = self.adapter.get_provider()
     scope = provider.get_scope(request)
     client = OAuth2Client(self.request, app.client_id, app.secret,
                           self.adapter.access_token_method,
                           self.adapter.access_token_url,
                           callback_url,
                           scope,
                           scope_delimiter=self.adapter.scope_delimiter,
                           headers=self.adapter.headers,
                           basic_auth=self.adapter.basic_auth)
     return client
示例#40
0
 def get_client(self, request, app):
     callback_url = reverse(self.adapter.provider_id + "_callback")
     protocol = (
         self.adapter.redirect_uri_protocol or
         app_settings.DEFAULT_HTTP_PROTOCOL)
     callback_url = build_absolute_uri(
         request, callback_url,
         protocol=protocol)
     provider = self.adapter.get_provider()
     scope = provider.get_scope(request)
     client = WeixinOAuth2Client(
         self.request, app.client_id, app.secret,
         self.adapter.access_token_method,
         self.adapter.access_token_url,
         callback_url,
         scope)
     return client
示例#41
0
 def _complete_shopify_login(self, q, resp, resp_mock, with_refresh_token):
     complete_url = reverse(self.provider.id + '_callback')
     self.assertGreater(q['redirect_uri'][0]
                        .find(complete_url), 0)
     response_json = self \
         .get_login_response_json(with_refresh_token=with_refresh_token)
     with mocked_response(
             MockedResponse(
                 200,
                 response_json,
                 {'content-type': 'application/json'}),
             resp_mock):
         resp = self.client.get(complete_url,
                                {'code': 'test',
                                 'state': q['state'][0],
                                 'shop': 'test',
                                 })
     return resp
示例#42
0
    def test_callback(self):
        with patch(
                'allauth.socialaccount.providers.draugiem.views'
                '.draugiem_complete_login') as draugiem_complete_login:
            self.mock_socialaccount_state()

            response_json = self.get_draugiem_login_response()

            token = SocialToken(app=self.app, token=response_json['apikey'])
            login = self.get_socialaccount(response_json, token)

            draugiem_complete_login.return_value = login

            response = self.client.get(
                reverse(views.callback),
                {'dr_auth_status': 'ok',
                 'dr_auth_code': '42'})
            self.assertRedirects(response, '/accounts/profile/',
                                 fetch_redirect_response=False)
示例#43
0
    def test_callback(self):
        with patch('allauth.socialaccount.providers.draugiem.views'
                   '.draugiem_complete_login') as draugiem_complete_login:
            self.mock_socialaccount_state()

            response_json = self.get_draugiem_login_response()

            token = SocialToken(app=self.app, token=response_json['apikey'])
            login = self.get_socialaccount(response_json, token)

            draugiem_complete_login.return_value = login

            response = self.client.get(reverse(views.callback), {
                'dr_auth_status': 'ok',
                'dr_auth_code': '42'
            })
            self.assertRedirects(response,
                                 '/accounts/profile/',
                                 fetch_redirect_response=False)
示例#44
0
 def dispatch(self, request):
     """
     View to handle final steps of OAuth based authentication where the user
     gets redirected back to from the service provider
     """
     login_done_url = reverse(self.adapter.provider_id + "_callback")
     client = self._get_client(request, login_done_url)
     if not client.is_valid():
         if 'denied' in request.GET:
             error = AuthError.CANCELLED
         else:
             error = AuthError.UNKNOWN
         extra_context = dict(oauth_client=client)
         return render_authentication_error(
             request,
             self.adapter.provider_id,
             error=error,
             extra_context=extra_context)
     app = self.adapter.get_provider().get_app(request)
     try:
         access_token = client.get_access_token()
         token = SocialToken(
             app=app,
             token=access_token['oauth_token'],
             # .get() -- e.g. Evernote does not feature a secret
             token_secret=access_token.get('oauth_token_secret', ''))
         login = self.adapter.complete_login(request,
                                             app,
                                             token,
                                             response=access_token)
         login.token = token
         login.state = SocialLogin.unstash_state(request)
         return complete_social_login(request, login)
     except OAuthError as e:
         return render_authentication_error(
             request,
             self.adapter.provider_id,
             exception=e)
示例#45
0
 def login(self, resp_mock, process='login', with_refresh_token=True):
     resp = self.client.get(reverse(self.provider.id + '_login'),
                            {'process': process, 'shop': 'test'})
     self.assertEqual(resp.status_code, 200)  # No re-direct, JS must do it
     actual_content = resp.content.decode('utf8')
     self.assertTrue('script' in actual_content,
                     'Content missing script tag. [Actual: {}]'.format(
                         actual_content))
     self.assertTrue(resp.xframe_options_exempt,
                     'Redirect JS must be allowed to run in Shopify iframe')
     self.assertTrue(
         '<!DOCTYPE html><html><head>' in actual_content and
         '</head><body></body></html>' in actual_content,
         'Expected standard HTML skeleton. [Actual: {}]'.format(
             actual_content
         )
     )
     p = urlparse(actual_content.split(";</script>")[0].split(
         'location.href = "')[1])
     q = parse_qs(p.query)
     resp = self._complete_shopify_login(q, resp, resp_mock,
                                         with_refresh_token)
     return resp
示例#46
0
 def test_media_js(self):
     provider = providers.registry.by_id(FacebookProvider.id)
     request = RequestFactory().get(reverse('account_login'))
     request.session = {}
     script = provider.media_js(request)
     self.assertTrue('"appId": "app123id"' in script)
示例#47
0
 def get_auth_params(self, request, action):
     params = super(UntappdProvider, self).get_auth_params(request, action)
     # Untappd uses redirect_url instead of redirect_uri
     params['redirect_url'] = request.build_absolute_uri(
         reverse(self.id + '_callback'))
     return params
示例#48
0
 def get_login_url(self, request, **kwargs):
     url = reverse('openid_login')
     if kwargs:
         url += '?' + urlencode(kwargs)
     return url
示例#49
0
 def test_callback_invalid_auth_status(self):
     response = self.client.get(reverse(views.callback),
                                {'dr_auth_status': 'fail'})
     self.assertTemplateUsed(response,
                             "socialaccount/authentication_error.html")
示例#50
0
 def get_login_url(self, request, **kwargs):
     print self.id
     url = reverse(self.id + "_login")
     if kwargs:
         url = url + '?' + urlencode(kwargs)
     return url
示例#51
0
 def abs_uri(name):
     return request.build_absolute_uri(reverse(name))
示例#52
0
 def abs_uri(name):
     return request.build_absolute_uri(reverse(name))
示例#53
0
 def respond_user_inactive(self, request, user):
     return HttpResponseRedirect(reverse('account_inactive'))
示例#54
0
 def respond_email_verification_sent(self, request, user):
     return HttpResponseRedirect(reverse('account_email_verification_sent'))
示例#55
0
 def get_callback_url(self, request, app):
     callback_url = reverse(self.provider_id + "_callback")
     protocol = self.redirect_uri_protocol
     return build_absolute_uri(request, callback_url, protocol)
示例#56
0
 def get_login_url(self, request, **kwargs):
     url = reverse(self.id + "_login")
     if kwargs:
         url = url + '?' + urlencode(kwargs)
     return url
示例#57
0
 def test_callback_invalid_auth_status(self):
     response = self.client.get(reverse(views.callback),
                                {'dr_auth_status': 'fail'})
     self.assertTemplateUsed(response,
                             "socialaccount/authentication_error.html")