def confirm_login(request): """Renders a login form for a user that needs to login in order to authenticate an active OpenID authentication request. """ if 'form.submitted' in request.POST: if request.POST.get('csrf_token') != request.session.get_csrf_token(): raise Forbidden login = request.POST.get('login', '') password = request.POST.get('password', '') user = DBSession().query(User).filter_by(username=login).first() if user is not None and user.check_password(password): headers = remember(request, user.username) return HTTPFound( location=route_url('openid_confirm_login_success', request), headers=headers) else: request.session.flash(_(u'Failed to log in, please try again.')) options = { 'title': _(u'Log in to authenticate OpenID request'), 'login_name': request.params.get('login', ''), 'action_url': route_url('openid_confirm_login', request), #'reset_url': route_url('reset_password', request), 'csrf_token': request.session.get_csrf_token(), } return render_to_response('templates/openid_confirm_login.pt', options, request)
def front_page(request): return { 'title': _(u'Nuorisovaalit 2011 - Tunnistautuminen'), #'login_url': route_url('login', request), #'logout_url': route_url('logout', request), 'openid_endpoint': route_url('openid_endpoint', request), 'xrds_location': route_url('yadis_server', request), }
def create_message(self, user, reset): """Returns an email.message.Message object representing the password reset message. """ from_address = self.request.registry.settings['webidentity_from_address'].strip() date_format = self.request.registry.settings['webidentity_date_format'].strip() locale = get_localizer(self.request) subject = locale.translate( _(u'Password reset for ${identity}', mapping={'identity': identity_url(self.request, user.username)})) message = Message() message['From'] = Header(from_address, 'utf-8') message['To'] = Header(u'{0} <{1}>'.format(user.username, user.email), 'utf-8') message['Subject'] = Header(subject, 'utf-8') message.set_payload(locale.translate(_( u'password-reset-email', default=textwrap.dedent(u''' Hi ${username} A password retrieval process has been initiated for your OpenID identity ${identity} If the process was initiated by you you can continue the process of resetting your password by opening the following link in your browser ${reset_url} The link will will expire at ${expiration}. If you did not initiate this request you can just ignore this email. Your password has not been changed. ''').lstrip(), mapping=dict( username=user.username, identity=identity_url(self.request, user.username), expiration=reset.expires.strftime(date_format), reset_url=route_url('reset_password_token', self.request, token=reset.token))))) return message
def send_confirmation_message(self): """Sends an email confirmation message to the user.""" username = self.request.POST.get('username', '').strip() redirect_url = route_url('reset_password', self.request) if not username: self.request.session.flash(_(u'Please supply a username.')) else: user = self.session.query(User).filter(User.username == username).first() if user is None: self.request.session.flash(_(u'The given username does not match any account.')) else: # Create a password reset request that is valid for 24 hours reset = PasswordReset(user.id, datetime.now() + timedelta(hours=24)) self.session.add(reset) message = self.create_message(user, reset) from_address = self.request.registry.settings['webidentity_from_address'].strip() send_mail(from_address, [user.email], message) self.request.session.flash(_(u'Password retrieval instructions have been emailed to you.')) redirect_url = self.request.application_url return HTTPFound(location=redirect_url)
def login(request): """Renders a login form and logs in a user if given the correct credentials. """ session = DBSession() login_url = route_url('login', request) login = u'' if 'form.submitted' in request.POST: login = request.POST['login'] if request.session.get_csrf_token() != request.POST.get('csrf_token'): raise Forbidden(u'CSRF attempt detected.') else: # Allow the use of the full identity URL. username = extract_local_id(request, login, relaxed=True) if len(username) == 0: # Fallback to the the local id. username = login user = session.query(User).filter_by(username=username).first() password = request.POST['password'] if user is not None and user.check_password(password): headers = remember(request, user.username) request.session.flash(_(u'You have successfully logged in.')) return HTTPFound(location=request.application_url, headers=headers) request.session.flash(_(u'Login failed')) return { 'title': _(u'Login'), 'action_url': login_url, 'login': login, 'reset_url': route_url('reset_password', request), 'csrf_token': request.session.get_csrf_token(), }
def change_password(self): """Changes the password for a user.""" token = self.request.POST.get('token', '').strip() if token: password = self.request.POST.get('password', '') confirm_password = self.request.POST.get('confirm_password', '') if len(password.strip()) < 5: self.request.session.flash(_(u'Password must be at least five characters long')) return HTTPFound( location=route_url('reset_password_token', self.request, token=token)) elif password != confirm_password: self.request.session.flash(_(u'Given passwords do not match')) return HTTPFound( location=route_url('reset_password_token', self.request, token=token)) else: reset = self.session.query(PasswordReset)\ .filter(PasswordReset.token == token)\ .filter(PasswordReset.expires >= datetime.now())\ .first() if reset is None: raise NotFound() user = self.session.query(User).get(reset.user_id) if user is None: raise NotFound() # Update the user password user.password = password self.session.add(user) self.session.delete(reset) self.request.session.flash(_(u'Password changed.')) headers = remember(self.request, user.username) return HTTPFound(location=self.request.application_url, headers=headers) raise NotFound()
def password_change_form(self): """Renders the form for changing a password for a valid token.""" reset = self.session.query(PasswordReset)\ .filter(PasswordReset.token == self.request.matchdict['token'])\ .filter(PasswordReset.expires >= datetime.now())\ .first() if reset is None: # No matching password reset found raise NotFound() user = self.session.query(User).get(reset.user_id) if user is None: raise NotFound() return { 'action_url': route_url('reset_password_process', self.request), 'title': _(u'Change password'), 'token': reset.token, }
def webob_response(webresponse, request): """Returns an equivalent WebOb Response object for the given an openid.server.server.WebResponse object. """ if webresponse.code == 200 and webresponse.body.startswith('<form'): # The OpenID response has been encoded as an HTML form that POSTs to # the relying party. We need to wrap the form in an HTML document # and serve that to the browser. options = { 'title': _(u'OpenID authentication in progress'), 'openid_form_response': webresponse.body.decode('utf-8'), } response = render_to_response('templates/form_auto_submit.pt', options, request) else: # Create a raw response. response = Response(webresponse.body) response.status = webresponse.code response.headers.update(webresponse.headers) return response
def identity(request): """OpenID identity page for a user. The URL this page is served as is the OpenID identifier for the user and the contents contain the required information for service discovery. """ if request.matchdict.get('local_id', '').strip(): session = DBSession() account = session.query(User)\ .filter(User.username == request.matchdict['local_id'])\ .first() if account is None: raise NotFound() return { 'title': _(u'Identity page'), 'openid_endpoint': route_url('openid_endpoint', request), 'xrds_location': route_url('yadis_user', request, local_id=request.matchdict['local_id']), 'identity': identity_url(request, request.matchdict['local_id']), } else: raise NotFound()
def render_form(self): """Renders the password reset form.""" return { 'action_url': route_url('reset_password_initiate', self.request), 'title': _(u'Reset password'), }
def logout(request): """Logs out the currently authenticated user.""" headers = forget(request) request.session.flash(_(u'You have been logged out')) return HTTPFound(location=request.application_url, headers=headers)
def auth_decision(request, openid_request): """Renders the appropriate page that allows the user to make a decision about the OpenID authentication request. The possible scenarios are: 1. The user is logged in to the OP and RP wants OP to select the id 2. The user is logged in to the OP and her identity matches the claimed id. 3. The user is logged in to the OP and her identity does not match the claimed id. 4. The user is not logged in and RP wants OP to select the id. 5. The user is not logged in and RP sent a claimed id. In cases 1) and 2) the user can simply make the decision on allowing the authentication to proceed (and AX related decisions.) In cases 3), 4) and 5) the user needs to log in to the OP first. """ user = authenticated_user(request) expected_user = extract_local_id(request, openid_request.identity) session = DBSession() log = logging.getLogger('webidentity') # Persist the OpenID request so we can continue processing it after the # user has authenticated overriding any previous request. cidrequest = session.query(CheckIdRequest).get(request.environ['repoze.browserid']) if cidrequest is None: cidrequest = CheckIdRequest(request.environ['repoze.browserid'], openid_request) else: # Unconditionally overwrite any existing checkid request. cidrequest.request = openid_request cidrequest.issued = int(time.time()) session.add(cidrequest) # Clean up dangling requests for roughly 10% of the time. # We do not do this on every call to reduce the possibility of a database # deadlock as rows need to be locked. if random.randint(0, 100) < 10: threshold = int(time.time()) - 3600 session.query(CheckIdRequest).filter(CheckIdRequest.issued < threshold).delete() log.info('Cleaned up dangling OpenID authentication requests.') options = { 'title': _(u'Approve OpenID request?'), 'action_url': route_url('openid_confirm', request), 'trust_root': openid_request.trust_root, #'reset_url': route_url('reset_password', request), } if user is not None: ax_request = ax.FetchRequest.fromOpenIDRequest(openid_request) sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request) if ax_request is not None or sreg_request is not None: # Prepare the user attributes for an SReg/AX request. # Mapping of attributes the RP has requested from the user. requested_attributes = {} if sreg_request.wereFieldsRequested(): requested_attributes.update(dict( (SREG_TO_AX.get(field), field in sreg_request.required) for field in sreg_request.allRequestedFields())) # The AX request takes precedence over SReg if both are requested. if ax_request is not None: requested_attributes.update(dict( (type_uri, attrinfo.required) for type_uri, attrinfo in ax_request.requested_attributes.iteritems())) # Set of attributes that the RP has marked mandatory required_attributes = set( type_uri for type_uri, required in requested_attributes.iteritems() if required) for persona in user.personas: available_attributes = set(a.type_uri for a in persona.attributes) options.setdefault('personas', []).append({ 'id': persona.id, 'name': persona.name, 'attributes': [ dict(type_uri=a.type_uri, value=a.value) for a in persona.attributes if a.type_uri in requested_attributes], 'missing': required_attributes - available_attributes, }) if openid_request.idSelect(): # Case 1. # The Relying Party has requested us to select an identifier. options.update({ 'identity': identity_url(request, user.username), 'csrf_token': request.session.get_csrf_token(), }) request.add_response_callback(disable_caching) return render_to_response('templates/openid_confirm.pt', options, request) elif user.username == expected_user: # Case 2. # A logged-in user that matches the user in the claimed identifier. options.update({ 'identity': openid_request.identity, 'csrf_token': request.session.get_csrf_token(), }) request.add_response_callback(disable_caching) return render_to_response('templates/openid_confirm.pt', options, request) else: # Case 3 # TODO: Implement case 3 raise NotImplementedError else: # Cases 4 and 5. options.update({ 'action_url': route_url('openid_confirm_login', request), 'login_name': expected_user if not openid_request.idSelect() else None, 'csrf_token': request.session.get_csrf_token(), }) return render_to_response('templates/openid_confirm_login.pt', options, request)