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')
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')
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)
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)
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)
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)
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)
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)
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"]
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)
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)
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)
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
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
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)
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
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
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')
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')
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
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
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)
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
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)
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
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='*****@*****.**')
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 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)
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)
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
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)))
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)))
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
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
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 _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
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)
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)
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)
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
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)
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
def get_login_url(self, request, **kwargs): url = reverse('openid_login') if kwargs: url += '?' + urlencode(kwargs) return url
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")
def get_login_url(self, request, **kwargs): print self.id url = reverse(self.id + "_login") if kwargs: url = url + '?' + urlencode(kwargs) return url
def abs_uri(name): return request.build_absolute_uri(reverse(name))
def respond_user_inactive(self, request, user): return HttpResponseRedirect(reverse('account_inactive'))
def respond_email_verification_sent(self, request, user): return HttpResponseRedirect(reverse('account_email_verification_sent'))
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)
def get_login_url(self, request, **kwargs): url = reverse(self.id + "_login") if kwargs: url = url + '?' + urlencode(kwargs) return url