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 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 from_openid_response(openid_response): issued = int(time.time()) openid = OpenID(openid_response.identity_url, issued, openid_response.signed_fields) if getattr(settings, 'OPENID_SREG', False): openid.sreg = SRegResponse.fromSuccessResponse(openid_response) if getattr(settings, 'OPENID_AX', False): openid.ax = AXFetchResponse.fromSuccessResponse(openid_response) return openid
def _get_email_from_response(response): email = None sreg = SRegResponse.fromSuccessResponse(response) if sreg: email = valid_email_or_none(sreg.get(SRegField.EMAIL)) if not email: ax = FetchResponse.fromSuccessResponse(response) if ax: try: values = ax.get(AXAttribute.CONTACT_EMAIL) if values: email = valid_email_or_none(values[0]) except KeyError: pass return email
def get_email_from_response(response): email = None sreg = SRegResponse.fromSuccessResponse(response) if sreg: email = valid_email_or_none(sreg.get(SRegField.EMAIL)) if not email: ax = FetchResponse.fromSuccessResponse(response) if ax: try: values = ax.get(AXAttribute.CONTACT_EMAIL) if values: email = valid_email_or_none(values[0]) except KeyError: pass return email
def process_authentication_request(self, request): consumer = Consumer(request.session, OsqaOpenIDStore()) query_dict = dict([(k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()]) #for i in query_dict.items(): #print "%s : %s" % i url = get_url_host(request) + request.path openid_response = consumer.complete(query_dict, url) if openid_response.status == SUCCESS: if request.session.get('force_email_request', True): try: ax = AXFetchResponse.fromSuccessResponse(openid_response) axargs = ax.getExtensionArgs() ax_schema2data_type = dict([ (s, t) for t, s in self.dataype2ax_schema.items() ]) available_types = dict([(ax_schema2data_type[s], re.sub('^type\.', '', n)) for n, s in axargs.items() if s in ax_schema2data_type]) available_data = dict([(t, axargs["value.%s.1" % s]) for t, s in available_types.items() ]) request.session['auth_consumer_data'] = { 'email': available_data.get('email', None), } except Exception, e: pass #import sys, traceback #traceback.print_exc(file=sys.stdout) return request.GET['openid.identity']
def process_authentication_request(self, request): consumer = Consumer(request.session, OsqaOpenIDStore()) query_dict = dict([ (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items() ]) #for i in query_dict.items(): #print "%s : %s" % i url = get_url_host(request) + request.path openid_response = consumer.complete(query_dict, url) if openid_response.status == SUCCESS: if request.session.get('force_email_request', True): try: ax = AXFetchResponse.fromSuccessResponse(openid_response) axargs = ax.getExtensionArgs() ax_schema2data_type = dict([(s, t) for t, s in self.dataype2ax_schema.items()]) available_types = dict([ (ax_schema2data_type[s], re.sub('^type\.', '', n)) for n, s in axargs.items() if s in ax_schema2data_type ]) available_data = dict([ (t, axargs["value.%s.1" % s]) for t, s in available_types.items() ]) request.session['auth_consumer_data'] = { 'email': available_data.get('email', None), } except Exception, e: pass #import sys, traceback #traceback.print_exc(file=sys.stdout) return request.GET['openid.identity']
def process_authentication_request(self, request): consumer = Consumer(request.session, OsqaOpenIDStore()) query_dict = dict([(k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()]) #for i in query_dict.items(): # print "%s : %s" % i url = get_url_host(request) + request.path openid_response = consumer.complete(query_dict, url) if openid_response.status == SUCCESS: if request.session.get('force_email_request', True): try: ax = AXFetchResponse.fromSuccessResponse(openid_response) email = ax.getExtensionArgs()['value.ext0.1'] request.session['auth_email_request'] = email except Exception, e: pass return request.GET['openid.identity']
def get_value_from_response(response, sreg_names=None, ax_names=None): value = None if sreg_names: sreg = SRegResponse.fromSuccessResponse(response) if sreg: for name in sreg_names: value = sreg.get(name) if value: break if not value and ax_names: ax = FetchResponse.fromSuccessResponse(response) if ax: for name in ax_names: try: values = ax.get(name) if values: value = values[0] except KeyError: pass if value: break return value
def process_authentication_request(self, request): consumer = Consumer(request.session, OsqaOpenIDStore()) query_dict = dict([ (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items() ]) #for i in query_dict.items(): # print "%s : %s" % i url = get_url_host(request) + request.path openid_response = consumer.complete(query_dict, url) if openid_response.status == SUCCESS: if request.session.get('force_email_request', True): try: ax = AXFetchResponse.fromSuccessResponse(openid_response) email = ax.getExtensionArgs()['value.ext0.1'] request.session['auth_email_request'] = email except Exception, e: pass return request.GET['openid.identity']
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 get_extra_data(self, resp): return FetchResponse.fromSuccessResponse(resp)
def process_authentication_request(self, request): consumer = Consumer(request.session, OsqaOpenIDStore()) query_dict = dict([ (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items() ]) #for i in query_dict.items(): #print "%s : %s" % i url = get_url_host(request) + request.path openid_response = consumer.complete(query_dict, url) if openid_response.status == SUCCESS: consumer_data = {} sreg_attrs = getattr(self, 'sreg_attributes', False) if sreg_attrs: sreg_response = SRegResponse.fromSuccessResponse(openid_response) if sreg_response: all_attrs = {} [all_attrs.update(d) for k,d in sreg_attrs.items() if k != "policy_url"] for attr_name, local_name in all_attrs.items(): if attr_name in sreg_response: consumer_data[local_name] = sreg_response[attr_name] ax_schema = getattr(self, 'dataype2ax_schema', False) if ax_schema: ax = AXFetchResponse.fromSuccessResponse(openid_response) if ax: axargs = ax.getExtensionArgs() ax_schema2data_type = dict([(s, t) for t, s in ax_schema.items()]) available_types = dict([ (ax_schema2data_type[s], re.sub('^type\.', '', n)) for n, s in axargs.items() if s in ax_schema2data_type ]) for t, s in available_types.items(): if not t in consumer_data: if axargs.get("value.%s.1" % s, None): consumer_data[t] = axargs["value.%s.1" % s] request.session['auth_consumer_data'] = consumer_data return request.GET['openid.identity'] elif openid_response.status == CANCEL: raise InvalidAuthentication(_('The OpenId authentication request was canceled')) elif openid_response.status == FAILURE: raise InvalidAuthentication(_('The OpenId authentication failed: ') + openid_response.message) elif openid_response.status == SETUP_NEEDED: raise InvalidAuthentication(_('Setup needed')) else: raise InvalidAuthentication(_('The OpenId authentication failed with an unknown status: ') + openid_response.status)
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 process_authentication_request(self, request): consumer = Consumer(request.session, OsqaOpenIDStore()) query_dict = dict([(smart_unicode(k), smart_unicode(v)) for k, v in request.GET.items()]) #for i in query_dict.items(): #print "%s : %s" % i url = get_url_host(request) + request.path openid_response = consumer.complete(query_dict, url) if openid_response.status == SUCCESS: consumer_data = {} sreg_attrs = getattr(self, 'sreg_attributes', False) if sreg_attrs: sreg_response = SRegResponse.fromSuccessResponse( openid_response) if sreg_response: all_attrs = {} [ all_attrs.update(d) for k, d in sreg_attrs.items() if k != "policy_url" ] for attr_name, local_name in all_attrs.items(): if attr_name in sreg_response: consumer_data[local_name] = sreg_response[ attr_name] ax_schema = getattr(self, 'dataype2ax_schema', False) if ax_schema: ax = AXFetchResponse.fromSuccessResponse( openid_response, False) if ax: axargs = ax.getExtensionArgs() ax_schema2data_type = dict([(s, t) for t, s in ax_schema.items()]) available_types = dict([(ax_schema2data_type[s], re.sub('^type\.', '', n)) for n, s in axargs.items() if s in ax_schema2data_type]) for t, s in available_types.items(): if not t in consumer_data: if axargs.get("value.%s.1" % s, None): consumer_data[t] = axargs["value.%s.1" % s] request.session['auth_consumer_data'] = consumer_data return request.GET['openid.identity'] elif openid_response.status == CANCEL: raise InvalidAuthentication( _('The OpenId authentication request was canceled')) elif openid_response.status == FAILURE: raise InvalidAuthentication( _('The OpenId authentication failed: ') + openid_response.message) elif openid_response.status == SETUP_NEEDED: raise InvalidAuthentication(_('Setup needed')) else: raise InvalidAuthentication( _('The OpenId authentication failed with an unknown status: ') + openid_response.status)