def renderIndexPage(request, **template_args): template_args['consumer_url'] = util.getViewURL(request, startOpenID) template_args['pape_policies'] = POLICY_PAIRS response = TemplateView(request, 'consumer/index.html', template_args) response[YADIS_HEADER_NAME] = util.getViewURL(request, rpXRDS) return response
def renderIndexPage(request, **template_args): template_args["consumer_url"] = util.getViewURL(request, startOpenID) template_args["pape_policies"] = POLICY_PAIRS response = direct_to_template(request, "consumer/index.html", template_args) response[YADIS_HEADER_NAME] = util.getViewURL(request, rpXRDS) return response
def renderIndexPage(request, **template_args): template_args['consumer_url'] = util.getViewURL(request, startOpenID) template_args['pape_policies'] = POLICY_PAIRS response = TemplateView(request, 'consumer/index.html', template_args) response[YADIS_HEADER_NAME] = util.getViewURL(request, rpXRDS) return response
def index(request): consumer_url = util.getViewURL( request, 'djopenid.consumer.views.startOpenID') server_url = util.getViewURL(request, 'djopenid.server.views.server') return TemplateView(request, 'index.html', {'consumer_url': consumer_url, 'server_url': server_url})
def server(request): """ Respond to requests for the server's primary web page. """ return render_to_response('server/index.html', { 'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds), }, context_instance=RequestContext(request))
def server(request): """ Respond to requests for the server's primary web page. """ return render( request, "server/index.html", {"user_url": getViewURL(request, idPage), "server_xrds_url": getViewURL(request, idpXrds)}, )
def index(request): consumer_url = util.getViewURL(request, 'djopenid.consumer.views.startOpenID') server_url = util.getViewURL(request, 'djopenid.server.views.server') return direct_to_template(request, 'index.html', { 'consumer_url': consumer_url, 'server_url': server_url })
def server(request): """ Respond to requests for the server's primary web page. """ return render_to_response( 'server/index.html', { 'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds), }, context_instance=RequestContext(request))
def server(request): """ Respond to requests for the server's primary web page. """ return direct_to_template( request, 'server/index.html', {'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds), })
def idPage(request): """ Serve the identity page for OpenID URLs. """ return render_to_response( 'server/idPage.html', {'server_url': getViewURL(request, endpoint)}, context_instance=RequestContext(request))
def idpXrds(request): """ Respond to requests for the IDP's XRDS document, which is used in IDP-driven identifier selection. """ return util.renderXRDS( request, [OPENID_IDP_2_0_TYPE], [getViewURL(request, endpoint)])
def idpXrds(request): """ Respond to requests for the IDP's XRDS document, which is used in IDP-driven identifier selection. """ return util.renderXRDS(request, [OPENID_IDP_2_0_TYPE], [getViewURL(request, endpoint)])
def showDecidePage(request, openid_request): """ Render a page to the user so a trust decision can be made. @type openid_request: openid.server.server.CheckIDRequest """ trust_root = openid_request.trust_root return_to = openid_request.return_to try: # Stringify because template's ifequal can only compare to strings. trust_root_valid = verifyReturnTo(trust_root, return_to) \ and "Valid" or "Invalid" except DiscoveryFailure as err: trust_root_valid = "DISCOVERY_FAILED" except HTTPFetchingError as err: trust_root_valid = "Unreachable" pape_request = pape.Request.fromOpenIDRequest(openid_request) return direct_to_template( request, 'server/trust.html', {'trust_root': trust_root, 'trust_handler_url':getViewURL(request, processTrustResult), 'trust_root_valid': trust_root_valid, 'pape_request': pape_request, })
def idPage(request): """ Serve the identity page for OpenID URLs. """ return render_to_response('server/idPage.html', {'server_url': getViewURL(request, endpoint)}, context_instance=RequestContext(request))
def showDecidePage(request, openid_request): """ Render a page to the user so a trust decision can be made. @type openid_request: openid.server.server.CheckIDRequest """ trust_root = openid_request.trust_root return_to = openid_request.return_to try: # Stringify because template's ifequal can only compare to strings. trust_root_valid = verifyReturnTo(trust_root, return_to) \ and "Valid" or "Invalid" except DiscoveryFailure as err: trust_root_valid = "DISCOVERY_FAILED" except HTTPFetchingError as err: trust_root_valid = "Unreachable" pape_request = pape.Request.fromOpenIDRequest(openid_request) return render_to_response( 'server/trust.html', { 'trust_root': trust_root, 'trust_handler_url': getViewURL(request, processTrustResult), 'trust_root_valid': trust_root_valid, 'pape_request': pape_request, }, context_instance=RequestContext(request))
def endpoint(request): """ Respond to low-level OpenID protocol messages. """ ret_json = request.META.get('HTTP_ACCEPT', False) and \ not (request.META['HTTP_ACCEPT'].find('html') > -1) query = util.normalDict(request.GET or request.POST) if query.get('data', ''): #TODO no use query.get('remember', '') username = query.get('user') password = query.get('passwd') user = _sign_in(request, username, password) if not user or not user.is_active: next_url = query.get('next') or request.META.get('HTTP_REFERER', '') if not ret_json: return direct_to_template(request, 'server/login.html', {'ret': 'error<a href=' + next_url + '>back</a>', 'data': query['data'], 'url': getViewURL(request, endpoint), 'next': next_url}) else: response_data = {'prompt': 'openid login', \ 'action': getViewURL(request, endpoint), \ 'method': 'POST', \ 'fields': [ {'type': 'text', 'name': 'user', 'label': 'Username: '******'type': 'password', 'name': 'passwd', 'label': 'Password: '******'type': 'hidden', 'name': 'data', 'value': query['data']}, ] } return http.HttpResponse(json.dumps(response_data), mimetype="application/json") query = pickle.loads(base64.decodestring(query['data'])) s = getServer(request) # First, decode the incoming request into something the OpenID # library can use. try: openid_request = s.decodeRequest(query) except ProtocolError, why: # This means the incoming request was invalid. return direct_to_template( request, 'server/endpoint.html', {'error': str(why)})
def idPage(request): """ Serve the identity page for OpenID URLs. """ return direct_to_template( request, 'server/idPage.html', {'server_url': getViewURL(request, endpoint)})
def rpXRDS(request): """ Return a relying party verification XRDS document """ return util.renderXRDS( request, [RP_RETURN_TO_URL_TYPE], [util.getViewURL(request, finishOpenID)])
def sign_in(request): from djopenid.server import views as s_views if request.method == 'GET': next_url = request.GET.get('next', '') if request.user.is_authenticated(): return http.HttpResponseRedirect(getViewURL(request, s_views.server)) return direct_to_template(request, 'server/login.html', {'ret': '', 'next': next_url, 'url': '/auth/'}) else: user, passwd = request.POST.get('user', None), request.POST.get('passwd', None) next_url = request.POST.get('next', None) remember = request.POST.get('remember', '') user = _sign_in(request, user, passwd) if not user: return direct_to_template(request, 'server/login.html', {'ret': 'error', 'next': next_url, 'url': '/auth/'}) if not next_url: return http.HttpResponseRedirect(getViewURL(request, s_views.server)) return http.HttpResponseRedirect(next_url)
def rpXRDS(request): """ Return a relying party verification XRDS document """ return util.renderXRDS( request, [RP_RETURN_TO_URL_TYPE], [util.getViewURL(request, finishOpenID)])
def trustPage(request): """ Display the trust page template, which allows the user to decide whether to approve the OpenID verification. """ return direct_to_template( request, 'server/trust.html', {'trust_handler_url':getViewURL(request, processTrustResult)})
def trustPage(request): """ Display the trust page template, which allows the user to decide whether to approve the OpenID verification. """ return render_to_response( 'server/trust.html', {'trust_handler_url': getViewURL(request, processTrustResult)}, context_instance=RequestContext(request))
def trustPage(request): """ Display the trust page template, which allows the user to decide whether to approve the OpenID verification. """ return render_to_response( 'server/trust.html', {'trust_handler_url': getViewURL(request, processTrustResult)}, context_instance=RequestContext(request))
def setUp(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://127.0.0.1/%s' % (self.id(),), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request)
def processTrustResult(request): """ Handle the result of a trust decision and respond to the RP accordingly. """ # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest(request) # The identifier that this server can vouch for response_identity = getViewURL(request, idPage, args=[request.user.username]) # If the decision was to allow the verification, respond # accordingly. allowed = 'allow' in request.POST or 'once' in request.POST # Generate a response with the appropriate answer. openid_response = openid_request.answer(allowed, identity=response_identity) # Send Simple Registration data in the response, if appropriate. if allowed: if ('allow' in request.POST) and \ not AuthSites.objects.filter( uid = request.user.id, site = openid_request.trust_root): auth_site = AuthSites.objects.create( uid = request.user.id, site = openid_request.trust_root, permission = 1) auth_site.save() sreg_data = {'username': request.user.username, 'mail': request.user.email, 'uid': str(request.user.id)} sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request) sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data) openid_response.addExtension(sreg_resp) pape_response = pape.Response() pape_response.setAuthLevel(pape.LEVELS_NIST, 0) openid_response.addExtension(pape_response) return displayResponse(request, openid_response)
def setUp(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = "http://127.0.0.1:8080/endpoint" message = Message.fromPostArgs( { "openid.mode": "checkid_setup", "openid.identity": id_url, "openid.return_to": "http://127.0.0.1/%s" % (self.id(),), "openid.sreg.required": "postcode", } ) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request)
def processTrustResult(request): """ Handle the result of a trust decision and respond to the RP accordingly. """ # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest(request) # The identifier that this server can vouch for response_identity = getViewURL(request, idPage) # If the decision was to allow the verification, respond # accordingly. allowed = 'allow' in request.POST # Generate a response with the appropriate answer. openid_response = openid_request.answer(allowed, identity=response_identity) # Send Simple Registration data in the response, if appropriate. if allowed: sreg_data = { 'fullname': 'Example User', 'nickname': 'example', 'dob': '1970-01-01', 'email': '*****@*****.**', 'gender': 'F', 'postcode': '12345', 'country': 'ES', 'language': 'eu', 'timezone': 'America/New_York', } sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request) sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data) openid_response.addExtension(sreg_resp) pape_response = pape.Response() pape_response.setAuthLevel(pape.LEVELS_NIST, 0) openid_response.addExtension(pape_response) return displayResponse(request, openid_response)
def processTrustResult(request): """ Handle the result of a trust decision and respond to the RP accordingly. """ # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest(request) # The identifier that this server can vouch for response_identity = getViewURL(request, idPage) # If the decision was to allow the verification, respond # accordingly. allowed = 'allow' in request.POST # Generate a response with the appropriate answer. openid_response = openid_request.answer(allowed, identity=response_identity) # Send Simple Registration data in the response, if appropriate. if allowed: sreg_data = { 'fullname': 'Example User', 'nickname': 'example', 'dob': '1970-01-01', 'email': '*****@*****.**', 'gender': 'F', 'postcode': '12345', 'country': 'ES', 'language': 'eu', 'timezone': 'America/New_York', } sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request) sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data) openid_response.addExtension(sreg_resp) pape_response = pape.Response() pape_response.setAuthLevel(pape.LEVELS_NIST, 0) openid_response.addExtension(pape_response) return displayResponse(request, openid_response)
def test_unreachableRealm(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://unreachable.invalid/%s' % (self.id(),), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request) response = views.showDecidePage(self.request, self.openid_request) self.assertContains(response, 'trust_root_valid is Unreachable')
def processTrustResult(request): """ Handle the result of a trust decision and respond to the RP accordingly. """ # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest(request) # The identifier that this server can vouch for response_identity = getViewURL(request, idPage) # If the decision was to allow the verification, respond # accordingly. allowed = "allow" in request.POST # Generate a response with the appropriate answer. openid_response = openid_request.answer(allowed, identity=response_identity) # Send Simple Registration data in the response, if appropriate. if allowed: sreg_data = { "fullname": "Example User", "nickname": "example", "dob": "1970-01-01", "email": "*****@*****.**", "gender": "F", "postcode": "12345", "country": "ES", "language": "eu", "timezone": "America/New_York", } sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request) sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data) openid_response.addExtension(sreg_resp) pape_response = pape.Response() pape_response.setAuthLevel(pape.LEVELS_NIST, 0) openid_response.addExtension(pape_response) return displayResponse(request, openid_response)
def test_unreachableRealm(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = "http://127.0.0.1:8080/endpoint" message = Message.fromPostArgs( { "openid.mode": "checkid_setup", "openid.identity": id_url, "openid.return_to": "http://unreachable.invalid/%s" % (self.id(),), "openid.sreg.required": "postcode", } ) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request) response = views.showDecidePage(self.request, self.openid_request) self.failUnless("trust_root_valid is Unreachable" in response.content, response)
def handleCheckIDRequest(request, openid_request): """ Handle checkid_* requests. Get input from the user to find out whether she trusts the RP involved. Possibly, get intput about what Simple Registration information, if any, to send in the response. """ # If the request was an IDP-driven identifier selection request # (i.e., the IDP URL was entered at the RP), then return the # default identity URL for this server. In a full-featured # provider, there could be interaction with the user to determine # what URL should be sent. if not openid_request.idSelect(): id_url = getViewURL(request, idPage) # Confirm that this server can actually vouch for that # identifier if id_url != openid_request.identity: # Return an error response error_response = ProtocolError( openid_request.message, "This server cannot verify the URL %r" % (openid_request.identity,)) return displayResponse(request, error_response) if openid_request.immediate: # Always respond with 'cancel' to immediate mode requests # because we don't track information about a logged-in user. # If we did, then the answer would depend on whether that user # had trusted the request's trust root and whether the user is # even logged in. openid_response = openid_request.answer(False) return displayResponse(request, openid_response) else: # Store the incoming request object in the session so we can # get to it later. setRequest(request, openid_request) return showDecidePage(request, openid_request)
def handleCheckIDRequest(request, openid_request): """ Handle checkid_* requests. Get input from the user to find out whether she trusts the RP involved. Possibly, get intput about what Simple Registration information, if any, to send in the response. """ # If the request was an IDP-driven identifier selection request # (i.e., the IDP URL was entered at the RP), then return the # default identity URL for this server. In a full-featured # provider, there could be interaction with the user to determine # what URL should be sent. if not openid_request.idSelect(): id_url = getViewURL(request, idPage) # Confirm that this server can actually vouch for that # identifier if id_url != openid_request.identity: # Return an error response error_response = ProtocolError( openid_request.message, "This server cannot verify the URL %r" % (openid_request.identity, )) return displayResponse(request, error_response) if openid_request.immediate: # Always respond with 'cancel' to immediate mode requests # because we don't track information about a logged-in user. # If we did, then the answer would depend on whether that user # had trusted the request's trust root and whether the user is # even logged in. openid_response = openid_request.answer(False) return displayResponse(request, openid_response) else: # Store the incoming request object in the session so we can # get to it later. setRequest(request, openid_request) return showDecidePage(request, openid_request)
def finishOpenID(request): """ Finish the OpenID authentication process. Invoke the OpenID library with the response from the OpenID server and render a page detailing the result. """ result = {} # Because the object containing the query parameters is a # MultiValueDict and the OpenID library doesn't allow that, we'll # convert it to a normal dict. # OpenID 2 can send arguments as either POST body or GET query # parameters. request_args = util.normalDict(request.GET) if request.method == "POST": request_args.update(util.normalDict(request.POST)) if request_args: c = getConsumer(request) # Get a response object indicating the result of the OpenID # protocol. return_to = util.getViewURL(request, finishOpenID) response = c.complete(request_args, return_to) # Get a Simple Registration response object if response # information was included in the OpenID response. sreg_response = {} ax_items = {} if response.status == consumer.SUCCESS: sreg_response = sreg.SRegResponse.fromSuccessResponse(response) ax_response = ax.FetchResponse.fromSuccessResponse(response) if ax_response: ax_items = { "fullname": ax_response.get("http://schema.openid.net/namePerson"), "web": ax_response.get("http://schema.openid.net/contact/web/default"), } # Get a PAPE response object if response information was # included in the OpenID response. pape_response = None if response.status == consumer.SUCCESS: pape_response = pape.Response.fromSuccessResponse(response) if not pape_response.auth_policies: pape_response = None # Map different consumer status codes to template contexts. results = { consumer.CANCEL: {"message": "OpenID authentication cancelled."}, consumer.FAILURE: {"error": "OpenID authentication failed."}, consumer.SUCCESS: { "url": response.getDisplayIdentifier(), "sreg": sreg_response and sreg_response.items(), "ax": ax_items.items(), "pape": pape_response, }, } result = results[response.status] if isinstance(response, consumer.FailureResponse): # In a real application, this information should be # written to a log for debugging/tracking OpenID # authentication failures. In general, the messages are # not user-friendly, but intended for developers. result["failure_reason"] = response.message return renderIndexPage(request, **result)
try: # Stringify because template's ifequal can only compare to strings. trust_root_valid = verifyReturnTo(trust_root, return_to) \ and "Valid" or "Invalid" except DiscoveryFailure, err: trust_root_valid = "DISCOVERY_FAILED" except HTTPFetchingError, err: trust_root_valid = "Unreachable" pape_request = pape.Request.fromOpenIDRequest(openid_request) return direct_to_template( request, 'server/trust.html', {'trust_root': trust_root, 'trust_handler_url':getViewURL(request, processTrustResult), 'trust_root_valid': trust_root_valid, 'pape_request': pape_request, }) def processTrustResult(request): """ Handle the result of a trust decision and respond to the RP accordingly. """ # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest(request) # The identifier that this server can vouch for response_identity = getViewURL(request, idPage)
def getServer(request): """ Get a Server object to perform OpenID authentication. """ return Server(getOpenIDStore(), getViewURL(request, endpoint))
def idPage(request): """ Serve the identity page for OpenID URLs. """ return render(request, "server/idPage.html", {"server_url": getViewURL(request, endpoint)})
def getServer(request): """ Get a Server object to perform OpenID authentication. """ return Server(getOpenIDStore(), getViewURL(request, endpoint))
def startOpenID(request): """ Start the OpenID authentication process. Renders an authentication form and accepts its POST. * Renders an error message if OpenID cannot be initiated * Requests some Simple Registration data using the OpenID library's Simple Registration machinery * Generates the appropriate trust root and return URL values for this application (tweak where appropriate) * Generates the appropriate redirect based on the OpenID protocol version. """ if request.POST: # Start OpenID authentication. openid_url = request.POST["openid_identifier"] c = getConsumer(request) error = None try: auth_request = c.begin(openid_url) except DiscoveryFailure, e: # Some other protocol-level failure occurred. error = "OpenID discovery error: %s" % (str(e),) if error: # Render the page with an error. return renderIndexPage(request, error=error) # Add Simple Registration request information. Some fields # are optional, some are required. It's possible that the # server doesn't support sreg or won't return any of the # fields. sreg_request = sreg.SRegRequest(optional=["email", "nickname"], required=["dob"]) auth_request.addExtension(sreg_request) # Add Attribute Exchange request information. ax_request = ax.FetchRequest() # XXX - uses myOpenID-compatible schema values, which are # not those listed at axschema.org. ax_request.add(ax.AttrInfo("http://schema.openid.net/namePerson", required=True)) ax_request.add( ax.AttrInfo("http://schema.openid.net/contact/web/default", required=False, count=ax.UNLIMITED_VALUES) ) auth_request.addExtension(ax_request) # Add PAPE request information. We'll ask for # phishing-resistant auth and display any policies we get in # the response. requested_policies = [] policy_prefix = "policy_" for k, v in request.POST.iteritems(): if k.startswith(policy_prefix): policy_attr = k[len(policy_prefix) :] if policy_attr in PAPE_POLICIES: requested_policies.append(getattr(pape, policy_attr)) if requested_policies: pape_request = pape.Request(requested_policies) auth_request.addExtension(pape_request) # Compute the trust root and return URL values to build the # redirect information. trust_root = util.getViewURL(request, startOpenID) return_to = util.getViewURL(request, finishOpenID) # Send the browser to the server either by sending a redirect # URL or by generating a POST form. if auth_request.shouldSendRedirect(): url = auth_request.redirectURL(trust_root, return_to) return HttpResponseRedirect(url) else: # Beware: this renders a template whose content is a form # and some javascript to submit it upon page load. Non-JS # users will have to click the form submit button to # initiate OpenID authentication. form_id = "openid_message" form_html = auth_request.formMarkup(trust_root, return_to, False, {"id": form_id}) return direct_to_template(request, "consumer/request_form.html", {"html": form_html})
def finishOpenID(request): """ Finish the OpenID authentication process. Invoke the OpenID library with the response from the OpenID server and render a page detailing the result. """ result = {} # Because the object containing the query parameters is a # MultiValueDict and the OpenID library doesn't allow that, we'll # convert it to a normal dict. # OpenID 2 can send arguments as either POST body or GET query # parameters. request_args = util.normalDict(request.GET) if request.method == 'POST': request_args.update(util.normalDict(request.POST)) if request_args: c = getConsumer(request) # Get a response object indicating the result of the OpenID # protocol. return_to = util.getViewURL(request, finishOpenID) response = c.complete(request_args, return_to) # Get a Simple Registration response object if response # information was included in the OpenID response. sreg_response = {} ax_items = {} if response.status == consumer.SUCCESS: sreg_response = sreg.SRegResponse.fromSuccessResponse(response) ax_response = ax.FetchResponse.fromSuccessResponse(response) if ax_response: ax_items = { 'fullname': ax_response.get('http://schema.openid.net/namePerson'), 'web': ax_response.get( 'http://schema.openid.net/contact/web/default'), } # Get a PAPE response object if response information was # included in the OpenID response. pape_response = None if response.status == consumer.SUCCESS: pape_response = pape.Response.fromSuccessResponse(response) if not pape_response.auth_policies: pape_response = None # Map different consumer status codes to template contexts. results = { consumer.CANCEL: { 'message': 'OpenID authentication cancelled.' }, consumer.FAILURE: { 'error': 'OpenID authentication failed.' }, consumer.SUCCESS: { 'url': response.getDisplayIdentifier(), 'sreg': sreg_response and list(sreg_response.items()), 'ax': list(ax_items.items()), 'pape': pape_response } } result = results[response.status] if isinstance(response, consumer.FailureResponse): # In a real application, this information should be # written to a log for debugging/tracking OpenID # authentication failures. In general, the messages are # not user-friendly, but intended for developers. result['failure_reason'] = response.message return renderIndexPage(request, **result)
def handleCheckIDRequest(request, openid_request): """ Handle checkid_* requests. Get input from the user to find out whether she trusts the RP involved. Possibly, get intput about what Simple Registration information, if any, to send in the response. """ # If the request was an IDP-driven identifier selection request # (i.e., the IDP URL was entered at the RP), then return the # default identity URL for this server. In a full-featured # provider, there could be interaction with the user to determine # what URL should be sent. for k in dir(openid_request): if k.startswith('_'): continue if not request.user.is_authenticated(): ret_json = request.META.get('HTTP_ACCEPT', False) and \ not (request.META['HTTP_ACCEPT'].find('html') > -1) query = util.normalDict(request.GET or request.POST) if not ret_json: return direct_to_template(request, 'server/login.html', {'ret': '', 'data': base64.encodestring(pickle.dumps(query)).strip('\n'), 'url': getViewURL(request, endpoint), 'next': request.GET.get('next', request.META.get('HTTP_REFERER', '')) }) else: response_data = {'prompt': 'openid login', \ 'action': getViewURL(request, endpoint), \ 'method': 'POST', \ 'fields': [ {'type': 'text', 'name': 'user', 'label': 'Username: '******'type': 'password', 'name': 'passwd', 'label': 'Password: '******'type': 'hidden', 'name': 'data', 'value': base64.encodestring(pickle.dumps(query)).strip('\n')}, ] } return http.HttpResponse(json.dumps(response_data), mimetype="application/json") if not openid_request.idSelect(): id_url = getViewURL(request, idPage, args=[request.user.username]) # Confirm that this server can actually vouch for that # identifier if id_url != openid_request.identity: # Return an error response error_response = ProtocolError( openid_request.message, "This server cannot verify the URL %r" % (openid_request.identity,)) return displayResponse(request, error_response) if openid_request.immediate: # Always respond with 'cancel' to immediate mode requests # because we don't track information about a logged-in user. # If we did, then the answer would depend on whether that user # had trusted the request's trust root and whether the user is # even logged in. openid_response = openid_request.answer(False) return displayResponse(request, openid_response) else: # Store the incoming request object in the session so we can # get to it later. setRequest(request, openid_request) return showDecidePage(request, openid_request)
def startOpenID(request): """ Start the OpenID authentication process. Renders an authentication form and accepts its POST. * Renders an error message if OpenID cannot be initiated * Requests some Simple Registration data using the OpenID library's Simple Registration machinery * Generates the appropriate trust root and return URL values for this application (tweak where appropriate) * Generates the appropriate redirect based on the OpenID protocol version. """ if request.POST: # Start OpenID authentication. openid_url = request.POST['openid_identifier'] c = getConsumer(request) error = None try: auth_request = c.begin(openid_url) except DiscoveryFailure as e: # Some other protocol-level failure occurred. error = "OpenID discovery error: %s" % (str(e), ) if error: # Render the page with an error. return renderIndexPage(request, error=error) # Add Simple Registration request information. Some fields # are optional, some are required. It's possible that the # server doesn't support sreg or won't return any of the # fields. sreg_request = sreg.SRegRequest( optional=['email', 'nickname'], required=['dob']) auth_request.addExtension(sreg_request) # Add Attribute Exchange request information. ax_request = ax.FetchRequest() # XXX - uses myOpenID-compatible schema values, which are # not those listed at axschema.org. ax_request.add( ax.AttrInfo('http://schema.openid.net/namePerson', required=True)) ax_request.add( ax.AttrInfo( 'http://schema.openid.net/contact/web/default', required=False, count=ax.UNLIMITED_VALUES)) auth_request.addExtension(ax_request) # Add PAPE request information. We'll ask for # phishing-resistant auth and display any policies we get in # the response. requested_policies = [] policy_prefix = 'policy_' for k, v in list(request.POST.items()): if k.startswith(policy_prefix): policy_attr = k[len(policy_prefix):] if policy_attr in PAPE_POLICIES: requested_policies.append(getattr(pape, policy_attr)) if requested_policies: pape_request = pape.Request(requested_policies) auth_request.addExtension(pape_request) # Compute the trust root and return URL values to build the # redirect information. trust_root = util.getViewURL(request, startOpenID) return_to = util.getViewURL(request, finishOpenID) # Send the browser to the server either by sending a redirect # URL or by generating a POST form. if auth_request.shouldSendRedirect(): url = auth_request.redirectURL(trust_root, return_to) return HttpResponseRedirect(url) else: # Beware: this renders a template whose content is a form # and some javascript to submit it upon page load. Non-JS # users will have to click the form submit button to # initiate OpenID authentication. form_id = 'openid_message' form_html = auth_request.formMarkup(trust_root, return_to, False, {'id': form_id}) return TemplateView(request, 'consumer/request_form.html', {'html': form_html}) return renderIndexPage(request)
def finishOpenID(request): """ Finish the OpenID authentication process. Invoke the OpenID library with the response from the OpenID server and render a page detailing the result. """ result = {} # Because the object containing the query parameters is a # MultiValueDict and the OpenID library doesn't allow that, we'll # convert it to a normal dict. # OpenID 2 can send arguments as either POST body or GET query # parameters. request_args = util.normalDict(request.GET) if request.method == 'POST': request_args.update(util.normalDict(request.POST)) if request_args: c = getConsumer(request) # Get a response object indicating the result of the OpenID # protocol. return_to = util.getViewURL(request, finishOpenID) response = c.complete(request_args, return_to) # Get a Simple Registration response object if response # information was included in the OpenID response. sreg_response = {} if response.status == consumer.SUCCESS: sreg_response = sreg.SRegResponse.fromSuccessResponse(response) # Get a PAPE response object if response information was # included in the OpenID response. pape_response = None if response.status == consumer.SUCCESS: pape_response = pape.Response.fromSuccessResponse(response) # Map different consumer status codes to template contexts. results = { consumer.CANCEL: {'message': 'OpenID authentication cancelled.'}, consumer.FAILURE: {'error': 'OpenID authentication failed.'}, consumer.SUCCESS: {'url': response.getDisplayIdentifier(), 'sreg': sreg_response.items(), 'pape': pape_response}, } result = results[response.status] if isinstance(response, consumer.FailureResponse): # In a real application, this information should be # written to a log for debugging/tracking OpenID # authentication failures. In general, the messages are # not user-friendly, but intended for developers. result['failure_reason'] = response.message return renderIndexPage(request, **result)