def begin(request, openid_url): request.session['request_referer'] = urlparse.urljoin(request.META.get('HTTP_REFERER', ''), '/') consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: return on_failure(request, _('The OpenID was invalid')) s = SRegRequest() for sarg in OPENID_SREG: if sarg.lower().lstrip() == "policy_url": s.policy_url = OPENID_SREG[sarg] else: for v in OPENID_SREG[sarg].split(','): s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) auth_request.addExtension(s) axr = AXFetchRequest() for i in OPENID_AX: axr.add(AttrInfo(i['type_uri'], i['count'], i['required'], i['alias'])) auth_request.addExtension(axr) redirect_url = auth_request.redirectURL(get_trusted_root(request), request.build_absolute_uri(reverse("openid_complete"))) return HttpResponseRedirect(redirect_url)
def begin(self, request, data): try: openid_url = data['openid_url'].strip() except KeyError: messages.error(request, lang.FILL_OPENID_URL) return redirect('netauth-login') # allow user to type openid provider without http:// prefix if not openid_url.startswith("http"): openid_url = "http://%s" % openid_url return_url = request.build_absolute_uri(reverse('netauth-complete', args=[self.provider])) request.session['openid_return_to'] = return_url client = consumer.Consumer(request.session, None) try: openid_request = client.begin(openid_url) sreg_extra = [value for __, value in self.PROFILE_MAPPING.items()] sreg = SRegRequest(required=sreg_extra) openid_request.addExtension(sreg) ax_msg = FetchRequest() for __, detail in self.PROFILE_MAPPING.items(): ax_msg.add(AttrInfo(settings.AX_URIS[detail], required=True)) openid_request.addExtension(ax_msg) redirect_url = openid_request.redirectURL(realm='http://' + request.get_host(), return_to=return_url) return redirect(redirect_url) except discover.DiscoveryFailure: messages.error(request, _('Could not find OpenID server')) return redirect('netauth-login')
def post(self, request, *args, **kwargs): data = dict(list(request.GET.items()) + list(request.POST.items())) if self.provider.endpoint: data['openid'] = self.provider.endpoint form = LoginForm(data) 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)) auth_request.addExtension(ax) callback_url = reverse(self.callback_view) SocialLogin.stash_state(request) 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, self.provider.id, exception=e) return render(request, self.template_name, {'form': form})
def login(request): if 'openid' in request.GET or request.method == 'POST': form = LoginForm(request.REQUEST) if form.is_valid(): client = _openid_consumer(request) try: auth_request = client.begin(form.cleaned_data['openid']) if QUERY_EMAIL: sreg = SRegRequest() sreg.requestField(field_name=SRegField.EMAIL, required=True) auth_request.addExtension(sreg) ax = FetchRequest() ax.add(AttrInfo(AXAttribute.CONTACT_EMAIL, required=True)) auth_request.addExtension(ax) callback_url = reverse(callback) state = SocialLogin.marshall_state(request) callback_url = callback_url + '?' + urlencode(dict(state=state)) redirect_url = auth_request.redirectURL( request.build_absolute_uri('/'), request.build_absolute_uri(callback_url)) return HttpResponseRedirect(redirect_url) except DiscoveryFailure, e: if request.method == 'POST': form._errors["openid"] = form.error_class([e]) else: return render_authentication_error(request)
def begin(self, request, data): try: openid_url = data['openid_url'].strip() except KeyError: messages.error(request, lang.FILL_OPENID_URL) raise Redirect('publicauth-login') # allow user to type openid provider without http:// prefix if not openid_url.startswith("http"): openid_url = "http://%s" % openid_url return_url = request.build_absolute_uri( reverse('publicauth-complete', args=[self.provider])) request.session['openid_return_to'] = return_url client = consumer.Consumer(request.session, None) try: openid_request = client.begin(openid_url) sreg_extra = [i for i in self.PROFILE_MAPPING] sreg = SRegRequest(required=sreg_extra) openid_request.addExtension(sreg) ax_msg = FetchRequest() for detail in self.PROFILE_MAPPING: ax_msg.add(AttrInfo(settings.AX_URIS[detail], required=True)) openid_request.addExtension(ax_msg) redirect_url = openid_request.redirectURL(realm='http://' + request.get_host(), return_to=return_url) raise Redirect(redirect_url) except discover.DiscoveryFailure: messages.error(request, _('Could not find OpenID server')) raise Redirect('publicauth-login')
def test02(self): interface = SQLAlchemyAXInterface() interface.connectionString = \ SQLAlchemyAXInterfaceTestCase.DB_CONNECTION_STR interface.attributeNames = ('firstName', 'lastName', 'emailAddress') interface.sqlQuery = ("select firstname, lastname, emailAddress from " "users where username = '******'") axReq = FetchRequest() for typeURI in interface.attributeNames: axReq.add(AttrInfo(typeURI, required=True)) axResp = FetchResponse() authnCtx = { SQLAlchemyAXInterface.USERNAME_SESSION_KEYNAME: SQLAlchemyAXInterfaceTestCase.USERNAME } interface(axReq, axResp, None, authnCtx) axData = axResp.getExtensionArgs() self.assert_(len(axData.keys()) > 0) print(axData)
def login(request): if 'openid' in request.GET or request.method == 'POST': form = LoginForm(request.REQUEST) if form.is_valid(): client = _openid_consumer(request) try: auth_request = client.begin(form.cleaned_data['openid']) if QUERY_EMAIL: sreg = SRegRequest() sreg.requestField(field_name=SRegField.EMAIL, required=True) auth_request.addExtension(sreg) ax = FetchRequest() ax.add(AttrInfo(AXAttribute.CONTACT_EMAIL, required=True)) auth_request.addExtension(ax) callback_url = reverse(callback) SocialLogin.stash_state(request) 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) else: form = LoginForm() d = dict(form=form) return render_to_response('openid/login.html', d, context_instance=RequestContext(request))
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) provider = OpenIDProvider(request) realm = provider.get_settings().get( 'REALM', request.build_absolute_uri('/')) 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) # Fix for issues 1523 and 2072 (github django-allauth) if 'next' in form.cleaned_data and form.cleaned_data['next']: auth_request.return_to_args['next'] = \ form.cleaned_data['next'] redirect_url = auth_request.redirectURL( realm, 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 test_ax_and_sreg_required_fields_for_trusted_site(self): """The server should always return values for required fields to trusted sites, regardless of the state of the checkbox in the UI. Optional fields should not be returned if the user has unchecked them. Fields are required if at least one of the SReg and AX request lists them as such. """ self.rpconfig.allowed_user_attribs = ( 'fullname,email,language,account_verified') sreg_request = SRegRequest( required=['language', 'email'], optional=['fullname']) ax_request = FetchRequest() ax_request.add( AttrInfo(AX_URI_EMAIL, alias='email', required=True)) ax_request.add( AttrInfo(AX_URI_ACCOUNT_VERIFIED, alias='account_verified', required=True)) ax_request.add( AttrInfo(AX_URI_LANGUAGE, alias='language', required=False)) ax_request.add( AttrInfo(AX_URI_FULL_NAME, alias='fullname', required=False)) form = UserAttribsRequestForm( request=self._get_request_with_post_args(), sreg_request=sreg_request, ax_request=ax_request, rpconfig=self.rpconfig) self.assertIn('email', form.data_approved_for_request) self.assertIn('account_verified', form.data_approved_for_request) self.assertIn('language', form.data_approved_for_request) self.assertNotIn('fullname', form.data_approved_for_request)
def prepare_authentication_request(self, request, redirect_to): if not redirect_to.startswith('http://') or redirect_to.startswith( 'https://'): redirect_to = get_url_host(request) + redirect_to user_url = self.get_user_url(request) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): raise InvalidAuthentication('i-names are not supported') consumer = Consumer(request.session, OsqaOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: raise InvalidAuthentication( _('Sorry, but your input is not a valid OpenId')) sreg = getattr(self, 'sreg_attributes', False) if sreg: s = SRegRequest() for k, attr_dic in sreg.items(): if k == "policy_url": s.policy_url = attr_dic continue for attr_name in attr_dic.keys(): s.requestField(field_name=attr_name, required=(k == "required")) auth_request.addExtension(s) ax_schema = getattr(self, 'dataype2ax_schema', False) if ax_schema and request.session.get('force_email_request', True): axr = AXFetchRequest() for data_type, schema in ax_schema.items(): if isinstance(schema, tuple): axr.add(AttrInfo(schema[0], required=True, alias=schema[1])) else: axr.add(AttrInfo(schema, required=True, alias=data_type)) auth_request.addExtension(axr) trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') return auth_request.redirectURL(trust_root, redirect_to)
def prepare_authentication_request(self, request, redirect_to): if not redirect_to.startswith('http://') or redirect_to.startswith('https://'): redirect_to = get_url_host(request) + redirect_to user_url = self.get_user_url(request) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): raise InvalidAuthentication('i-names are not supported') consumer = Consumer(request.session, OsqaOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId')) sreg = getattr(self, 'sreg_attributes', False) if sreg: s = SRegRequest() for k, attr_dic in sreg.items(): if k == "policy_url": s.policy_url = attr_dic continue for attr_name in attr_dic.keys(): s.requestField(field_name=attr_name, required=(k == "required")) auth_request.addExtension(s) ax_schema = getattr(self, 'dataype2ax_schema', False) if ax_schema and request.session.get('force_email_request', True): axr = AXFetchRequest() for data_type, schema in ax_schema.items(): if isinstance(schema, tuple): axr.add(AttrInfo(schema[0], 1, True, schema[1])) else: axr.add(AttrInfo(schema, 1, True, data_type)) auth_request.addExtension(axr) trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) return auth_request.redirectURL(trust_root, redirect_to)
def test_ax_optional_fields_for_untrusted_site(self): """The server should return values for optional fields to untrusted sites only when the user checks the checkbox in the UI. """ post_args = {'fullname': 'fullname'} ax_request = FetchRequest() for (attr, alias) in [ (AX_URI_FULL_NAME, 'fullname'), (AX_URI_EMAIL, 'email')]: ax_request.add(AttrInfo(attr, alias=alias, required=False)) form = UserAttribsRequestForm( request=self._get_request_with_post_args(post_args), sreg_request=None, ax_request=ax_request, rpconfig=None) self.assertTrue('fullname' in form.data_approved_for_request) self.assertFalse('email' in form.data_approved_for_request)
def test_ax_required_fields_for_trusted_site(self): """The server should always return values for required fields to trusted sites, regardless of the state of the checkbox in the UI. Optional fields should not be returned if the user has unchecked them. """ self.rpconfig.allowed_user_attribs = 'fullname,email' ax_request = FetchRequest() ax_request.add( AttrInfo(AX_URI_FULL_NAME, alias='fullname', required=True)) ax_request.add( AttrInfo(AX_URI_EMAIL, alias='email', required=False)) form = UserAttribsRequestForm( request=self._get_request_with_post_args(), sreg_request=None, ax_request=ax_request, rpconfig=self.rpconfig) self.assertIn('fullname', form.data_approved_for_request) self.assertNotIn('email', form.data_approved_for_request)
def prepare_authentication_request(self, request, redirect_to): if not redirect_to.startswith('http://') or redirect_to.startswith( 'https://'): redirect_to = get_url_host(request) + redirect_to user_url = self.get_user_url(request) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): raise InvalidAuthentication('i-names are not supported') consumer = Consumer(request.session, OsqaOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: raise InvalidAuthentication( _('Sorry, but your input is not a valid OpenId')) #sreg = getattr(settings, 'OPENID_SREG', False) #if sreg: # s = SRegRequest() # for sarg in sreg: # if sarg.lower().lstrip() == "policy_url": # s.policy_url = sreg[sarg] # else: # for v in sreg[sarg].split(','): # s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) # auth_request.addExtension(s) #auth_request.addExtension(SRegRequest(required=['email'])) if request.session.get('force_email_request', True): axr = AXFetchRequest() for data_type, schema in self.dataype2ax_schema.items(): if isinstance(schema, tuple): axr.add(AttrInfo(schema[0], 1, True, schema[1])) else: axr.add(AttrInfo(schema, 1, True, data_type)) auth_request.addExtension(axr) trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') return auth_request.redirectURL(trust_root, redirect_to)
def prepare_authentication_request(self, request, redirect_to): if not redirect_to.startswith('http://') or redirect_to.startswith('https://'): redirect_to = get_url_host(request) + redirect_to user_url = self.get_user_url(request) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): raise InvalidAuthentication('i-names are not supported') consumer = Consumer(request.session, OsqaOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId')) #sreg = getattr(settings, 'OPENID_SREG', False) #if sreg: # s = SRegRequest() # for sarg in sreg: # if sarg.lower().lstrip() == "policy_url": # s.policy_url = sreg[sarg] # else: # for v in sreg[sarg].split(','): # s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) # auth_request.addExtension(s) #auth_request.addExtension(SRegRequest(required=['email'])) if request.session.get('force_email_request', True): axr = AXFetchRequest() for data_type, schema in self.dataype2ax_schema.items(): if isinstance(schema, tuple): axr.add(AttrInfo(schema[0], 1, True, schema[1])) else: axr.add(AttrInfo(schema, 1, True, data_type)) auth_request.addExtension(axr) trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) return auth_request.redirectURL(trust_root, redirect_to)
def test_ax_checkbox_status_for_trusted_site(self): """Checkboxes are always checked if the site is trusted""" self.rpconfig.allowed_user_attribs = 'fullname,email' ax_request = FetchRequest() ax_request.add( AttrInfo(AX_URI_FULL_NAME, alias='fullname', required=True)) ax_request.add( AttrInfo(AX_URI_EMAIL, alias='email', required=False)) form = UserAttribsRequestForm( request=self._get_request_with_post_args(), sreg_request=None, ax_request=ax_request, rpconfig=self.rpconfig) # True because fullname required self.assertTrue(form.check_test('fullname')(True)) # True because trusted site and no previous disapproval self.assertTrue(form.check_test('email')(True)) # Throw in an unrequested field for good measure self.assertFalse(form.check_test('language')(True))
def test_no_approved_fields_without_post_request(self): """The server should not generate a list of approved fields when the request is not a POST request. """ sreg_request = SRegRequest(required=['fullname', 'email']) ax_request = FetchRequest() for (attr, alias) in [ (AX_URI_FULL_NAME, 'fullname'), (AX_URI_EMAIL, 'email')]: ax_request.add(AttrInfo(attr, alias=alias, required=True)) request = self._get_request_with_post_args() request.META['REQUEST_METHOD'] = 'GET' form = UserAttribsRequestForm(request=request, sreg_request=sreg_request, ax_request=ax_request, rpconfig=self.rpconfig) self.assertEqual(len(form.data_approved_for_request), 0)
def test_ax_fields_for_trusted_auto_authorize_site(self): """The server should always return values for requested fields to trusted sites configured to auto-authorize. """ self.rpconfig.allowed_user_attribs = 'fullname,email' self.rpconfig.auto_authorize = True ax_request = FetchRequest() # One required attribute ax_request.add( AttrInfo(AX_URI_FULL_NAME, alias='fullname', required=True)) # One optional attribute ax_request.add( AttrInfo(AX_URI_EMAIL, alias='email', required=False)) form = UserAttribsRequestForm( request=self._get_request_with_post_args(), sreg_request=None, ax_request=ax_request, rpconfig=self.rpconfig) # Both attributes should be returned self.assertIn('fullname', form.data_approved_for_request) self.assertIn('email', form.data_approved_for_request)
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)) 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 perform_openid_auth(self, form): if not form.is_valid(): return form request = self.request client = self.get_client() provider = self.provider(request) realm = self.get_realm(provider) 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) SocialLogin.stash_state(request) # Fix for issues 1523 and 2072 (github django-allauth) if "next" in form.cleaned_data and form.cleaned_data["next"]: auth_request.return_to_args['next'] = \ form.cleaned_data['next'] redirect_url = auth_request.redirectURL( realm, request.build_absolute_uri(self.get_callback_url())) return HttpResponseRedirect(redirect_url)
def Respond(self, oidresponse): """Send an OpenID response. Args: oidresponse: OpenIDResponse The response to send, usually created by OpenIDRequest.answer(). """ logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode) if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']: # user = users.get_current_user() user = self.get_current_user() if user: from openid.extensions.sreg import SRegRequest,SRegResponse sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request) logging.info("sreg_req:%s",sreg_req.allRequestedFields()) if sreg_req.wereFieldsRequested(): user_data = {'nickname':user.nickname, 'email':user.email} sreg_resp = SRegResponse.extractResponse(sreg_req, user_data) sreg_resp.toMessage(oidresponse.fields) # add nickname, using the Simple Registration Extension: # http://www.openidenabled.com/openid/simple-registration-extension/ #oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'nickname', user.nickname) #oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'email', user.email) #oidresponse.fields.setArg('http://openid.net/srv/ax/1.0', 'nickname', user.nickname) #oidresponse.fields.setArg('http://openid.net/srv/ax/1.0', 'email', user.email) from openid.extensions.ax import FetchRequest, FetchResponse res ={'nickname':user.nickname,'email':user.email,'attr0':user.email,'attr1':user.nickname} ax_req = FetchRequest.fromOpenIDRequest(oidresponse.request) logging.info("ax_req:%s",ax_req.getRequiredAttrs()) ax_res = FetchResponse() for x in ax_req.iterAttrs(): ax_res.addValue(x.type_uri,res[x.alias] ) ax_res.toMessage(oidresponse.fields) pass logging.info('Using response: %s' % oidresponse) encoded_response = oidserver.encodeResponse(oidresponse) # update() would be nice, but wsgiref.headers.Headers doesn't implement it for header, value in encoded_response.headers.items(): self.response.headers[header] = str(value) if encoded_response.code in (301, 302): self.redirect(self.response.headers['location']) else: self.response.set_status(encoded_response.code) if encoded_response.body: logging.debug('Sending response body: %s' % encoded_response.body) self.response.out.write(encoded_response.body) else: self.response.out.write('')
def perform_openid_auth(self, form): if not form.is_valid(): return form request = self.request provider = self.provider(request) endpoint = form.cleaned_data["openid"] client = self.get_client(provider, endpoint) realm = self.get_realm(provider) auth_request = client.begin(endpoint) 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) SocialLogin.stash_state(request) # Fix for issues 1523 and 2072 (github django-allauth) if "next" in form.cleaned_data and form.cleaned_data["next"]: auth_request.return_to_args["next"] = form.cleaned_data["next"] redirect_url = auth_request.redirectURL( realm, request.build_absolute_uri(self.get_callback_url())) return HttpResponseRedirect(redirect_url)
def test_ax_checkbox_status_for_untrusted_site_with_approved_data(self): """If the user has previously approved sending data to an untrusted site the same checkbox settings should be returned on the next request. """ approved_data = { 'requested': ['fullname', 'email'], 'approved': ['email', 'language']} ax_request = FetchRequest() ax_request.add( AttrInfo(AX_URI_FULL_NAME, alias='fullname', required=True)) ax_request.add( AttrInfo(AX_URI_EMAIL, alias='email', required=False)) form = UserAttribsRequestForm( request=self._get_request_with_post_args(), sreg_request=None, ax_request=ax_request, rpconfig=None, approved_data=approved_data) # False because untrusted site and previously disapproved self.assertFalse(form.check_test('fullname')(True)) # True because previously approved self.assertTrue(form.check_test('email')(True)) # Throw in an unrequested, previously-approved field for good measure self.assertFalse(form.check_test('language')(True))
def test_ax_checkbox_status_for_trusted_site_with_approved_data(self): """If the user has previously approved sending data to a trusted site the same checkbox settings should be returned on the next request unless those conflict with the required fields. """ self.rpconfig.allowed_user_attribs = 'fullname,email,language' approved_data = { 'requested': ['fullname', 'email', 'language'], 'approved': ['email', 'language']} ax_request = FetchRequest() ax_request.add( AttrInfo(AX_URI_FULL_NAME, alias='fullname', required=True)) ax_request.add( AttrInfo(AX_URI_EMAIL, alias='email', required=False)) form1 = UserAttribsRequestForm( request=self._get_request_with_post_args(), sreg_request=None, ax_request=ax_request, rpconfig=self.rpconfig, approved_data=approved_data) # True because fullname required self.assertTrue(form1.check_test('fullname')(True)) # True because email previously approved self.assertTrue(form1.check_test('email')(True)) # Throw in an unrequested, previously-approved field for good measure self.assertFalse(form1.check_test('language')(True)) approved_data['approved'] = [] form2 = UserAttribsRequestForm( request=self._get_request_with_post_args(), sreg_request=None, ax_request=ax_request, rpconfig=self.rpconfig, approved_data=approved_data) # True because fullname required self.assertTrue(form1.check_test('fullname')(True)) # False because email previously disapproved self.assertFalse(form2.check_test('email')(True)) # Throw in an unrequested field for good measure self.assertFalse(form2.check_test('language')(True))
def test01InvalidQueryUsernameKey(self): interface = SQLAlchemyAXInterface() interface.connectionString = \ SQLAlchemyAXInterfaceTestCase.DB_CONNECTION_STR interface.sqlQuery = ("select firstname from users where username = "******"'${invalidUsernameKey}'") axReq = FetchRequest() axResp = FetchResponse() authnCtx = { SQLAlchemyAXInterface.USERNAME_SESSION_KEYNAME: SQLAlchemyAXInterfaceTestCase.USERNAME } try: interface(axReq, axResp, None, authnCtx) except AXInterfaceConfigError: pass else: self.fail("Expected AXInterfaceConfigError exception")
def openid_auth_site(request): try: oreq = request.session['openid_request'] except KeyError: return render(request, 'openid-auth-site.html', { 'error': 'No OpenID request associated. The request may have \ expired.', }, status=400) sreg = SRegRequest.fromOpenIDRequest(oreq) ax = FetchRequest.fromOpenIDRequest(oreq) sreg_fields = set(sreg.allRequestedFields()) if ax: for uri in ax.requested_attributes: k = openid_ax_attribute_mapping.get(uri) if k: sreg_fields.add(k) ldap_user = LDAPUser.objects.get(username=request.user.username) if sreg_fields: sreg_data = { 'nickname': ldap_user.username, 'email': ldap_user.email, 'fullname': ldap_user.full_name, 'dob': ldap_user.birthday, } for k in list(sreg_data): if not sreg_data[k]: del sreg_data[k] else: sreg_data = {} sreg_fields = sreg_data.keys() # Read preferences from the db. try: saved_pref = OpenID_Attributes.objects.get( uid=ldap_user.uid, trust_root=oreq.trust_root, ) except OpenID_Attributes.DoesNotExist: saved_pref = None auto_auth = False else: auto_auth = saved_pref.always_auth if auto_auth or request.POST: if auto_auth: # TODO: can we do this nicer? form_inp = model_to_dict(saved_pref) else: form_inp = request.POST form = SiteAuthForm(form_inp, instance=saved_pref) # can it be invalid somehow? assert(form.is_valid()) attrs = form.save(commit=False) # nullify fields that were not requested for fn in form.cleaned_data: if fn in ('always_auth',): pass elif hasattr(attrs, fn) and fn not in sreg_fields: setattr(attrs, fn, None) if auto_auth or 'accept' in request.POST: # prepare sreg response for fn, send in form.cleaned_data.items(): if fn not in sreg_data: pass elif not send: del sreg_data[fn] elif isinstance(sreg_data[fn], list): form_key = 'which_%s' % fn val = form.cleaned_data[form_key] if val not in sreg_data[fn]: raise NotImplementedError( 'Changing choices not implemented yet') sreg_data[fn] = val if not auto_auth: setattr(attrs, form_key, val) if not auto_auth: # save prefs in the db # (if auto_auth, then nothing changed) attrs.uid = ldap_user.uid attrs.trust_root = oreq.trust_root attrs.save() oresp = oreq.answer(True, identity=request.build_absolute_uri( reverse(user_page, args=(request.user.username,)))) sreg_resp = SRegResponse.extractResponse(sreg, sreg_data) oresp.addExtension(sreg_resp) if ax: ax_resp = FetchResponse(ax) for uri in ax.requested_attributes: k = openid_ax_attribute_mapping.get(uri) if k and k in sreg_data: ax_resp.addValue(uri, sreg_data[k]) oresp.addExtension(ax_resp) elif 'reject' in request.POST: oresp = oreq.answer(False) else: return render(request, 'openid-auth-site.html', { 'error': 'Invalid request submitted.', }, status=400) if request.session.get('auto_logout', False): # _logout clears request.session _logout(request) else: del request.session['openid_request'] return render_openid_response(request, oresp) form = SiteAuthForm(instance=saved_pref) sreg_form = {} # Fill in lists for choices for f in sreg_fields: if f not in sreg_data: pass elif isinstance(sreg_data[f], list): form.fields['which_%s' % f].widget.choices = [ (x, x) for x in sreg_data[f] ] sreg_form[f] = form['which_%s' % f] else: sreg_form[f] = format_html("<input type='text'" + " readonly='readonly'" + " value='{0}' />", sreg_data[f]) try: # TODO: cache it if oreq.returnToVerified(): tr_valid = 'Return-To valid and trusted' else: tr_valid = 'Return-To untrusted' except openid.yadis.discover.DiscoveryFailure: tr_valid = 'Unable to verify trust (Yadis unsupported)' except openid.fetchers.HTTPFetchingError: tr_valid = 'Unable to verify trust (HTTP error)' return render(request, 'openid-auth-site.html', { 'openid_request': oreq, 'return_to_valid': tr_valid, 'form': form, 'sreg': sreg_fields, 'sreg_form': sreg_form, 'policy_url': sreg.policy_url, })
def begin(request, redirect_to=None, on_failure=None, user_url=None, template_name="openid_consumer/signin.html"): on_failure = on_failure or default_on_failure trust_root = getattr(settings, "OPENID_TRUST_ROOT", get_url_host(request) + "/") # foo derbis. redirect_to = redirect_to or getattr( settings, "OPENID_REDIRECT_TO", # If not explicitly set, assume current URL with complete/ appended get_full_url(request).split("?")[0] + "complete/", ) # In case they were lazy... if not (redirect_to.startswith("http://") or redirect_to.startswith("https://")): redirect_to = get_url_host(request) + redirect_to if request.GET.get("next") and is_valid_next_url(request.GET["next"]): if "?" in redirect_to: join = "&" else: join = "?" redirect_to += join + urllib.urlencode({"next": request.GET["next"]}) if not user_url: user_url = request.REQUEST.get("openid_url", None) if not user_url: request_path = request.path if request.GET.get("next"): request_path += "?" + urllib.urlencode({"next": request.GET["next"]}) return render(template_name, {"action": request_path}, RequestContext(request)) if xri.identifierScheme(user_url) == "XRI" and getattr(settings, "OPENID_DISALLOW_INAMES", False): return on_failure(request, _("i-names are not supported")) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: return on_failure(request, _("The OpenID was invalid")) sreg = getattr(settings, "OPENID_SREG", False) if sreg: s = SRegRequest() for sarg in sreg: if sarg.lower().lstrip() == "policy_url": s.policy_url = sreg[sarg] else: for v in sreg[sarg].split(","): s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) auth_request.addExtension(s) pape = getattr(settings, "OPENID_PAPE", False) if pape: if openid.__version__ <= "2.0.0" and openid.__version__ >= "2.1.0": raise (ImportError, "For pape extension you need python-openid 2.1.0 or newer") p = PapeRequest() for parg in pape: if parg.lower().strip() == "policy_list": for v in pape[parg].split(","): p.addPolicyURI(v) elif parg.lower().strip() == "max_auth_age": p.max_auth_age = pape[parg] auth_request.addExtension(p) OPENID_AX_PROVIDER_MAP = getattr(settings, "OPENID_AX_PROVIDER_MAP", {}) openid_provider = "Google" if "google" in request.session.get("openid_provider", "") else "Default" ax = OPENID_AX_PROVIDER_MAP.get(openid_provider) if ax: axr = AXFetchRequest() for attr_name, attr_url in ax.items(): # axr.add(AttrInfo(i['type_uri'], # i['count'], i['required'], # i['alias'])) # setting all as required attrs axr.add(AttrInfo(attr_url, required=True)) auth_request.addExtension(axr) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def openid_auth_site(request): try: oreq = request.session['openid_request'] except KeyError: return render(request, 'openid-auth-site.html', { 'error': 'No OpenID request associated. The request may have \ expired.', }, status=400) sreg = SRegRequest.fromOpenIDRequest(oreq) ax = FetchRequest.fromOpenIDRequest(oreq) sreg_fields = set(sreg.allRequestedFields()) if ax: for uri in ax.requested_attributes: k = openid_ax_attribute_mapping.get(uri) if k: sreg_fields.add(k) ldap_user = LDAPUser.objects.get(username=request.user.username) if sreg_fields: sreg_data = { 'nickname': ldap_user.username, 'email': ldap_user.email, 'fullname': ldap_user.full_name, 'dob': ldap_user.birthday, } for k in list(sreg_data): if not sreg_data[k]: del sreg_data[k] else: sreg_data = {} sreg_fields = sreg_data.keys() # Read preferences from the db. try: saved_pref = OpenID_Attributes.objects.get( uid=ldap_user.uid, trust_root=oreq.trust_root, ) except OpenID_Attributes.DoesNotExist: saved_pref = None auto_auth = False else: auto_auth = saved_pref.always_auth if auto_auth or request.POST: if auto_auth: # TODO: can we do this nicer? form_inp = model_to_dict(saved_pref) else: form_inp = request.POST form = SiteAuthForm(form_inp, instance=saved_pref) # can it be invalid somehow? assert (form.is_valid()) attrs = form.save(commit=False) # nullify fields that were not requested for fn in form.cleaned_data: if fn in ('always_auth', ): pass elif hasattr(attrs, fn) and fn not in sreg_fields: setattr(attrs, fn, None) if auto_auth or 'accept' in request.POST: # prepare sreg response for fn, send in form.cleaned_data.items(): if fn not in sreg_data: pass elif not send: del sreg_data[fn] elif isinstance(sreg_data[fn], list): form_key = 'which_%s' % fn val = form.cleaned_data[form_key] if val not in sreg_data[fn]: raise NotImplementedError( 'Changing choices not implemented yet') sreg_data[fn] = val if not auto_auth: setattr(attrs, form_key, val) if not auto_auth: # save prefs in the db # (if auto_auth, then nothing changed) attrs.uid = ldap_user.uid attrs.trust_root = oreq.trust_root attrs.save() oresp = oreq.answer(True, identity=request.build_absolute_uri( reverse(user_page, args=(request.user.username, )))) sreg_resp = SRegResponse.extractResponse(sreg, sreg_data) oresp.addExtension(sreg_resp) if ax: ax_resp = FetchResponse(ax) for uri in ax.requested_attributes: k = openid_ax_attribute_mapping.get(uri) if k and k in sreg_data: ax_resp.addValue(uri, sreg_data[k]) oresp.addExtension(ax_resp) elif 'reject' in request.POST: oresp = oreq.answer(False) else: return render(request, 'openid-auth-site.html', { 'error': 'Invalid request submitted.', }, status=400) if request.session.get('auto_logout', False): # _logout clears request.session _logout(request) else: del request.session['openid_request'] return render_openid_response(request, oresp) form = SiteAuthForm(instance=saved_pref) sreg_form = {} # Fill in lists for choices for f in sreg_fields: if f not in sreg_data: pass elif isinstance(sreg_data[f], list): form.fields['which_%s' % f].widget.choices = [ (x, x) for x in sreg_data[f] ] sreg_form[f] = form['which_%s' % f] else: sreg_form[f] = format_html( "<input type='text'" + " readonly='readonly'" + " value='{0}' />", sreg_data[f]) try: # TODO: cache it if oreq.returnToVerified(): tr_valid = 'Return-To valid and trusted' else: tr_valid = 'Return-To untrusted' except openid.yadis.discover.DiscoveryFailure: tr_valid = 'Unable to verify trust (Yadis unsupported)' except openid.fetchers.HTTPFetchingError: tr_valid = 'Unable to verify trust (HTTP error)' return render( request, 'openid-auth-site.html', { 'openid_request': oreq, 'return_to_valid': tr_valid, 'form': form, 'sreg': sreg_fields, 'sreg_form': sreg_form, 'policy_url': sreg.policy_url, })
def begin(request, confirmed=True, redirect_to=None, on_failure=None, user_url=None, template_name='openid_consumer/signin.html'): on_failure = on_failure or default_on_failure trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') # foo derbis. redirect_to = redirect_to or getattr( settings, 'OPENID_REDIRECT_TO', # If not explicitly set, assume current URL with complete/ appended get_full_url(request).split('?')[0] + 'complete/') # In case they were lazy... if not redirect_to.startswith('http://') or redirect_to.startswith( 'https://'): redirect_to = get_url_host(request) + redirect_to if request.GET.get('next') and is_valid_next_url(request.GET['next']): if '?' in redirect_to: join = '&' else: join = '?' redirect_to += join + urlencode({'next': request.GET['next']}) if not user_url: user_url = request.REQUEST.get('openid_url', None) if not user_url: request_path = request.path if request.GET.get('next'): request_path += '?' + urlencode({'next': request.GET['next']}) return render(template_name, { 'action': request_path, }, RequestContext(request)) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): return on_failure(request, _('i-names are not supported')) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: return on_failure(request, _('The OpenID was invalid')) sreg = getattr(settings, 'OPENID_SREG', False) if sreg: s = SRegRequest() for sarg in sreg: if sarg.lower().lstrip() == "policy_url": s.policy_url = sreg[sarg] else: for v in sreg[sarg].split(','): s.requestField( field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) auth_request.addExtension(s) pape = getattr(settings, 'OPENID_PAPE', False) if pape: if openid.__version__ <= '2.0.0' and openid.__version__ >= '2.1.0': raise ImportError, 'For pape extension you need python-openid 2.1.0 or newer' p = PapeRequest() for parg in pape: if parg.lower().strip() == 'policy_list': for v in pape[parg].split(','): p.addPolicyURI(v) elif parg.lower().strip() == 'max_auth_age': p.max_auth_age = pape[parg] auth_request.addExtension(p) ax = getattr(settings, 'OPENID_AX', []) if ax: axr = AXFetchRequest() for i in ax: axr.add( AttrInfo(i['type_uri'], i['count'], i['required'], i['alias'])) auth_request.addExtension(axr) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def begin(request, redirect_to=None, on_failure=None, user_url=None, template_name='openid_consumer/signin.html'): on_failure = on_failure or default_on_failure trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) # foo derbis. redirect_to = redirect_to or getattr( settings, 'OPENID_REDIRECT_TO', # If not explicitly set, assume current URL with complete/ appended get_full_url(request).split('?')[0] + 'complete/' ) # In case they were lazy... if not redirect_to.startswith('http://') or redirect_to.startswith('https://'): redirect_to = get_url_host(request) + redirect_to if request.GET.get('next') and is_valid_next_url(request.GET['next']): if '?' in redirect_to: join = '&' else: join = '?' redirect_to += join + urllib.urlencode({ 'next': request.GET['next'] }) if not user_url: user_url = request.REQUEST.get('openid_url', None) if not user_url: request_path = request.path if request.GET.get('next'): request_path += '?' + urllib.urlencode({ 'next': request.GET['next'] }) return render(template_name, { 'action': request_path, }, RequestContext(request)) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): return on_failure(request, _('i-names are not supported')) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: return on_failure(request, _('The OpenID was invalid')) sreg = getattr(settings, 'OPENID_SREG', False) if sreg: s = SRegRequest() for sarg in sreg: if sarg.lower().lstrip() == "policy_url": s.policy_url = sreg[sarg] else: for v in sreg[sarg].split(','): s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) auth_request.addExtension(s) pape = getattr(settings, 'OPENID_PAPE', False) if pape: if openid.__version__ <= '2.0.0' and openid.__version__ >= '2.1.0': raise ImportError, 'For pape extension you need python-openid 2.1.0 or newer' p = PapeRequest() for parg in pape: if parg.lower().strip() == 'policy_list': for v in pape[parg].split(','): p.addPolicyURI(v) elif parg.lower().strip() == 'max_auth_age': p.max_auth_age = pape[parg] auth_request.addExtension(p) ax = getattr(settings, 'OPENID_AX', []) if ax: axr = AXFetchRequest() for i in ax: axr.add(AttrInfo(i['type_uri'], i['count'], i['required'], i['alias'])) auth_request.addExtension(axr) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)