def _register(self, username, email, password): user = User(username=username, email=email, password=password) self.request.db.add(user) # Create a new activation for the user activation = Activation() self.request.db.add(activation) user.activation = activation # Flush the session to ensure that the user can be created and the # activation is successfully wired up self.request.db.flush() # Send the activation email message = activation_email(self.request, user) mailer = get_mailer(self.request) mailer.send(message) self.request.session.flash( jinja2.Markup( _( "Thank you for creating an account! " "We've sent you an email with an activation link, " "before you can sign in <strong>please check your email and open " "the link to activate your account</strong>." ) ), "success", ) self.request.registry.notify(RegistrationEvent(self.request, user))
def _register(self, username, email, password): user = User(username=username, email=email, password=password) self.request.db.add(user) # Create a new activation for the user activation = Activation() self.request.db.add(activation) user.activation = activation # Flush the session to ensure that the user can be created and the # activation is successfully wired up self.request.db.flush() # Send the activation email message = activation_email(self.request, user) mailer = get_mailer(self.request) mailer.send(message) self.request.session.flash( jinja2.Markup( _('Thank you for creating an account! ' "We've sent you an email with an activation link, " 'before you can sign in <strong>please check your email and open ' 'the link to activate your account</strong>.')), 'success') self.request.registry.notify(RegistrationEvent(self.request, user))
def validator(self, node, value): super(LoginSchema, self).validator(node, value) username = value.get('username') password = value.get('password') user = User.get_by_username(username) if user is None: user = User.get_by_email(username) if user is None: err = colander.Invalid(node) err['username'] = _('User does not exist.') raise err if not User.validate_user(user, password): err = colander.Invalid(node) err['password'] = _('Incorrect password. Please try again.') raise err if not user.is_activated: reason = _('Your account is not active. Please check your e-mail.') raise colander.Invalid(node, reason) value['user'] = user
def delete(self): """Remove a user from the admins.""" if len(User.admins()) > 1: try: username = self.request.params["remove"] except KeyError: raise httpexceptions.HTTPNotFound user = User.get_by_username(username) user.admin = False return httpexceptions.HTTPSeeOther(location=self.request.route_url("admin_users_index"))
def edit_profile(self): """Handle POST payload from profile update form.""" if self.request.method != 'POST': return httpexceptions.HTTPMethodNotAllowed() # Nothing to do here for non logged-in users if self.request.authenticated_userid is None: return httpexceptions.HTTPUnauthorized() err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err user = User.get_by_userid(self.request.domain, self.request.authenticated_userid) response = {'model': {'email': user.email}} # We allow updating subscriptions without validating a password subscriptions = appstruct.get('subscriptions') if subscriptions: data = json.loads(subscriptions) err = _update_subscription_data(self.request, data) if err is not None: return err return response # Any updates to fields below this point require password validation. # # `pwd` is the current password # `password` (used below) is optional, and is the new password # if not User.validate_user(user, appstruct.get('pwd')): return {'errors': {'pwd': _('Invalid password')}, 'code': 401} email = appstruct.get('email') if email: email_user = User.get_by_email(email) if email_user: if email_user.id != user.id: return { 'errors': { 'pwd': _('That email is already used') }, } response['model']['email'] = user.email = email password = appstruct.get('password') if password: user.password = password return response
def edit_profile(self): """Handle POST payload from profile update form.""" if self.request.method != 'POST': return httpexceptions.HTTPMethodNotAllowed() # Nothing to do here for non logged-in users if self.request.authenticated_userid is None: return httpexceptions.HTTPUnauthorized() err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err user = User.get_by_userid( self.request.domain, self.request.authenticated_userid) response = {'model': {'email': user.email}} # We allow updating subscriptions without validating a password subscriptions = appstruct.get('subscriptions') if subscriptions: data = json.loads(subscriptions) err = _update_subscription_data(self.request, data) if err is not None: return err return response # Any updates to fields below this point require password validation. # # `pwd` is the current password # `password` (used below) is optional, and is the new password # if not User.validate_user(user, appstruct.get('pwd')): return {'errors': {'pwd': _('Invalid password')}, 'code': 401} email = appstruct.get('email') if email: email_user = User.get_by_email(email) if email_user: if email_user.id != user.id: return { 'errors': {'pwd': _('That email is already used')}, } response['model']['email'] = user.email = email password = appstruct.get('password') if password: user.password = password return response
def edit_profile(self): """Handle POST payload from profile update form.""" if self.request.method != "POST": return httpexceptions.HTTPMethodNotAllowed() # Nothing to do here for non logged-in users if self.request.authenticated_userid is None: return httpexceptions.HTTPUnauthorized() err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err user = User.get_by_id(self.request, self.request.authenticated_userid) response = {"model": {"email": user.email}} # We allow updating subscriptions without validating a password subscriptions = appstruct.get("subscriptions") if subscriptions: data = json.loads(subscriptions) err = _update_subscription_data(self.request, data) if err is not None: return err return response # Any updates to fields below this point require password validation. # # `pwd` is the current password # `password` (used below) is optional, and is the new password # if not User.validate_user(user, appstruct.get("pwd")): return {"errors": {"pwd": _("Invalid password")}, "code": 401} email = appstruct.get("email") if email: email_user = User.get_by_email(email) if email_user: if email_user.id != user.id: return {"errors": {"pwd": _("That email is already used")}} response["model"]["email"] = user.email = email password = appstruct.get("password") if password: user.password = password return response
def activate(self): """ Handle a request for a user activation link. Checks if the activation code passed is valid, and (as a safety check) that it is an activation for the passed user id. If all is well, activate the user and redirect them to the stream. """ code = self.request.matchdict.get("code") id_ = self.request.matchdict.get("id") if code is None or id_ is None: return httpexceptions.HTTPNotFound() try: id_ = int(id_) except ValueError: return httpexceptions.HTTPNotFound() activation = Activation.get_by_code(code) if activation is None: return httpexceptions.HTTPNotFound() user = User.get_by_activation(activation) if user is None or user.id != id_: return httpexceptions.HTTPNotFound() # Activate the user (by deleting the activation) self.request.db.delete(activation) self.request.session.flash(_("Your e-mail address has been verified. " "Thank you!"), "success") self.request.registry.notify(ActivationEvent(self.request, user)) return httpexceptions.HTTPFound(location=self.request.route_url("index"))
def unique_username(node, value): '''Colander validator that ensures the username does not exist.''' user = User.get_by_username(value) if user: msg = _("Sorry, an account with this username already exists. " "Please enter another one.") raise colander.Invalid(node, msg)
def unique_email(node, value): '''Colander validator that ensures no user with this email exists.''' user = User.get_by_email(value) if user: msg = _("Sorry, an account with this email address already exists. " "Try logging in instead.") raise colander.Invalid(node, msg)
def email_exists(node, value): '''Colander validator that ensures a user with this email exists.''' user = User.get_by_email(value) if not user: msg = _('We have no user with the email address "{}". Try correcting ' 'this address or try another.').format(value) raise colander.Invalid(node, msg)
def _validate_request(request): """ Check that the passed request is appropriate for proceeding with account claim. Asserts that: - the 'claim' feature is toggled on - no-one is logged in - the claim token is provided and authentic - the user referred to in the token exists - the user referred to in the token has not already claimed their account and raises for redirect or 404 otherwise. """ if not request.feature('claim'): raise exc.HTTPNotFound() # If signed in, redirect to stream if request.authenticated_userid is not None: _perform_logged_in_redirect(request) payload = _validate_token(request) if payload is None: raise exc.HTTPNotFound() user = User.get_by_userid(request.domain, payload['userid']) if user is None: log.warn('got claim token with invalid userid=%r', payload['userid']) raise exc.HTTPNotFound() # User already has a password? Claimed already. if user.password: _perform_already_claimed_redirect(request) return user
def email_exists(node, value): '''Colander validator that ensures a user with this email exists.''' user = User.get_by_email(value) if not user: msg = _('We have no user with the email address "{}". Try correcting ' 'this address or try another.') raise colander.Invalid(node, msg)
def disable_user(self): """Disable the user by setting a random password.""" err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err username = appstruct['username'] pwd = appstruct['pwd'] # Password check user = User.get_user(username, pwd) if user: # TODO: maybe have an explicit disabled flag in the status user.password = User.generate_random_password() self.request.session.flash(_('Account disabled.'), 'success') return {} else: return dict(errors={'pwd': _('Invalid password')}, code=401)
def disable_user(self): """Disable the user by setting a random password.""" if self.request.authenticated_userid is None: return httpexceptions.HTTPUnauthorized() err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err user = User.get_by_userid( self.request.domain, self.request.authenticated_userid) if User.validate_user(user, appstruct['pwd']): # Password check. # TODO: maybe have an explicit disabled flag in the status user.password = User.generate_random_password() self.request.session.flash(_('Account disabled.'), 'success') return {} else: return dict(errors={'pwd': _('Invalid password')}, code=401)
def disable_user(self): """Disable the user by setting a random password.""" if self.request.authenticated_userid is None: return httpexceptions.HTTPUnauthorized() err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err user = User.get_by_userid(self.request.domain, self.request.authenticated_userid) if User.validate_user(user, appstruct['pwd']): # Password check. # TODO: maybe have an explicit disabled flag in the status user.password = User.generate_random_password() self.request.session.flash(_('Account disabled.'), 'success') return {} else: return dict(errors={'pwd': _('Invalid password')}, code=401)
def register(self): """ Handle submission of the new user registration form. Validates the form data, creates a new activation for the user, sends the activation mail, and then redirects the user to the index. """ err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err # Create the new user from selected form fields props = {k: appstruct[k] for k in ["username", "email", "password"]} user = User(**props) self.request.db.add(user) # Create a new activation for the user activation = Activation() self.request.db.add(activation) user.activation = activation # Flush the session to ensure that the user can be created and the # activation is successfully wired up self.request.db.flush() # Send the activation email message = activation_email(self.request, user) mailer = get_mailer(self.request) mailer.send(message) self.request.session.flash( _( "Thank you for registering! Please check " "your e-mail now. You can continue by " "clicking the activation link we have " "sent you." ), "success", ) self.request.registry.notify(RegistrationEvent(self.request, user)) return httpexceptions.HTTPFound(location=self.request.route_url("index"))
def register(self): """ Handle submission of the new user registration form. Validates the form data, creates a new activation for the user, sends the activation mail, and then redirects the user to the index. """ err, appstruct = validate_form(self.form, self.request.POST.items()) if err is not None: return err # Create the new user from selected form fields props = {k: appstruct[k] for k in ['username', 'email', 'password']} user = User(**props) self.request.db.add(user) # Create a new activation for the user activation = Activation() self.request.db.add(activation) user.activation = activation # Flush the session to ensure that the user can be created and the # activation is successfully wired up self.request.db.flush() # Send the activation email message = activation_email(self.request, user) mailer = get_mailer(self.request) mailer.send(message) self.request.session.flash( _("Thank you for registering! Please check " "your e-mail now. You can continue by " "clicking the activation link we have " "sent you."), 'success') self.request.registry.notify(RegistrationEvent(self.request, user)) return httpexceptions.HTTPFound( location=self.request.route_url('index'))
def profile(self): """ Return a serialisation of the user's profile. For use by the frontend. Includes current email and subscriptions data. """ request = self.request userid = request.authenticated_userid model = {} if userid: model["email"] = User.get_by_id(request, userid).email if request.feature("notification"): model["subscriptions"] = Subscriptions.get_subscriptions_for_uri(userid) return {"model": model}
def forgot_password(self): """ Handle submission of the forgot password form. Validates that the email is one we know about, and then generates a new activation for the associated user, and dispatches a "reset your password" email which contains a token and/or link to the reset password form. """ schema = schemas.ForgotPasswordSchema().bind(request=self.request) form = deform.Form(schema) # Nothing to do here for logged-in users if self.request.authenticated_userid is not None: return httpexceptions.HTTPFound( location=self.forgot_password_redirect) err, appstruct = validate_form(form, self.request.POST.items()) if err is not None: return err # If the validation passes, we assume the user exists. # # TODO: fix this latent race condition by returning a user object in # the appstruct. user = User.get_by_email(appstruct['email']) # Create a new activation for this user. Any previous activation will # get overwritten. activation = Activation() self.request.db.add(activation) user.activation = activation # Write the new activation to the database in order to set up the # foreign key field and generate the code. self.request.db.flush() # Send the reset password email code = user.activation.code link = reset_password_link(self.request, code) message = reset_password_email(user, code, link) mailer = get_mailer(self.request) mailer.send(message) self.request.session.flash( _("Please check your email to finish " "resetting your password."), "success") return httpexceptions.HTTPFound(location=self.reset_password_redirect)
def forgot_password(self): """ Handle submission of the forgot password form. Validates that the email is one we know about, and then generates a new activation for the associated user, and dispatches a "reset your password" email which contains a token and/or link to the reset password form. """ schema = schemas.ForgotPasswordSchema().bind(request=self.request) form = deform.Form(schema) # Nothing to do here for logged-in users if self.request.authenticated_userid is not None: return httpexceptions.HTTPFound( location=self.forgot_password_redirect) err, appstruct = validate_form(form, self.request.POST.items()) if err is not None: return err # If the validation passes, we assume the user exists. # # TODO: fix this latent race condition by returning a user object in # the appstruct. user = User.get_by_email(appstruct['email']) # Create a new activation for this user. Any previous activation will # get overwritten. activation = Activation() self.request.db.add(activation) user.activation = activation # Write the new activation to the database in order to set up the # foreign key field and generate the code. self.request.db.flush() # Send the reset password email code = user.activation.code link = reset_password_link(self.request, code) message = reset_password_email(user, code, link) mailer = get_mailer(self.request) mailer.send(message) self.request.session.flash(_("Please check your email to finish " "resetting your password."), "success") return httpexceptions.HTTPFound(location=self.reset_password_redirect)
def profile(self): """ Return a serialisation of the user's profile. For use by the frontend. Includes current email and subscriptions data. """ request = self.request userid = request.authenticated_userid model = {} if userid: model["email"] = User.get_by_userid(request.domain, userid).email if request.feature('notification'): model['subscriptions'] = Subscriptions.get_subscriptions_for_uri( userid) return {'model': model}
def get_when_not_logged_in(self): """ Handle a request for a user activation link. Checks if the activation code passed is valid, and (as a safety check) that it is an activation for the passed user id. If all is well, activate the user and redirect them to the stream. """ code = self.request.matchdict.get('code') id_ = self.request.matchdict.get('id') try: id_ = int(id_) except ValueError: raise httpexceptions.HTTPNotFound() activation = Activation.get_by_code(code) if activation is None: self.request.session.flash( jinja2.Markup( _("We didn't recognize that activation link. " "Perhaps you've already activated your account? " 'If so, try <a href="{url}">signing in</a> using the username ' 'and password that you provided.').format( url=self.request.route_url('login'))), 'error') return httpexceptions.HTTPFound( location=self.request.route_url('index')) user = User.get_by_activation(activation) if user is None or user.id != id_: raise httpexceptions.HTTPNotFound() user.activate() self.request.session.flash( jinja2.Markup( _('Your account has been activated! ' 'You can now <a href="{url}">sign in</a> using the password you ' 'provided.').format(url=self.request.route_url('login'))), 'success') self.request.registry.notify(ActivationEvent(self.request, user)) return httpexceptions.HTTPFound( location=self.request.route_url('index'))
def get_when_not_logged_in(self): """ Handle a request for a user activation link. Checks if the activation code passed is valid, and (as a safety check) that it is an activation for the passed user id. If all is well, activate the user and redirect them to the stream. """ code = self.request.matchdict.get('code') id_ = self.request.matchdict.get('id') try: id_ = int(id_) except ValueError: raise httpexceptions.HTTPNotFound() activation = Activation.get_by_code(self.request.db, code) if activation is None: self.request.session.flash(jinja2.Markup(_( "We didn't recognize that activation link. " "Perhaps you've already activated your account? " 'If so, try <a href="{url}">logging in</a> using the username ' 'and password that you provided.').format( url=self.request.route_url('login'))), 'error') return httpexceptions.HTTPFound( location=self.request.route_url('index')) user = User.get_by_activation(self.request.db, activation) if user is None or user.id != id_: raise httpexceptions.HTTPNotFound() user.activate() self.request.session.flash(jinja2.Markup(_( 'Your account has been activated! ' 'You can now <a href="{url}">log in</a> using the password you ' 'provided.').format(url=self.request.route_url('login'))), 'success') self.request.registry.notify(ActivationEvent(self.request, user)) return httpexceptions.HTTPFound( location=self.request.route_url('index'))
def activate(self): """ Handle a request for a user activation link. Checks if the activation code passed is valid, and (as a safety check) that it is an activation for the passed user id. If all is well, activate the user and redirect them to the stream. """ code = self.request.matchdict.get("code") id_ = self.request.matchdict.get("id") if code is None or id_ is None: return httpexceptions.HTTPNotFound() try: id_ = int(id_) except ValueError: return httpexceptions.HTTPNotFound() activation = Activation.get_by_code(code) if activation is None: return httpexceptions.HTTPNotFound() user = User.get_by_activation(activation) if user is None or user.id != id_: return httpexceptions.HTTPNotFound() # Activate the user (by deleting the activation) self.request.db.delete(activation) self.request.session.flash( jinja2.Markup( _( "Your account has been activated! " 'You can now <a href="{url}">login</a> using the password you ' "provided." ).format(url=self.request.route_url("login")) ), "success", ) self.request.registry.notify(ActivationEvent(self.request, user)) return httpexceptions.HTTPFound(location=self.request.route_url("index"))
def activate(self): """ Handle a request for a user activation link. Checks if the activation code passed is valid, and (as a safety check) that it is an activation for the passed user id. If all is well, activate the user and redirect them to the stream. """ code = self.request.matchdict.get('code') id_ = self.request.matchdict.get('id') if code is None or id_ is None: return httpexceptions.HTTPNotFound() try: id_ = int(id_) except ValueError: return httpexceptions.HTTPNotFound() activation = Activation.get_by_code(code) if activation is None: return httpexceptions.HTTPNotFound() user = User.get_by_activation(activation) if user is None or user.id != id_: return httpexceptions.HTTPNotFound() # Activate the user (by deleting the activation) self.request.db.delete(activation) self.request.session.flash( jinja2.Markup( _('Your account has been activated! ' 'You can now <a href="{url}">login</a> using the password you ' 'provided.').format(url=self.request.route_url('login'))), 'success') self.request.registry.notify(ActivationEvent(self.request, user)) return httpexceptions.HTTPFound( location=self.request.route_url('index'))
def reset_password(self): """ Handle submission of the reset password form. This function checks that the activation code (i.e. reset token) provided by the form is valid, retrieves the user associated with the activation code, and resets their password. """ schema = schemas.ResetPasswordSchema().bind(request=self.request) form = deform.Form(schema) code = self.request.matchdict.get('code') if code is None: return httpexceptions.HTTPNotFound() activation = Activation.get_by_code(self.request, code) if activation is None: return httpexceptions.HTTPNotFound() user = User.get_by_activation(self.request, activation) if user is None: return httpexceptions.HTTPNotFound() if self.request.method != 'POST': return httpexceptions.HTTPMethodNotAllowed() err, appstruct = validate_form(form, self.request.POST.items()) if err is not None: return err user.password = appstruct['password'] db = get_session(self.request) db.delete(activation) self.request.session.flash(_('Your password has been reset!'), 'success') self.request.registry.notify(PasswordResetEvent(self.request, user)) return httpexceptions.HTTPFound(location=self.reset_password_redirect)
def reset_password(self): """ Handle submission of the reset password form. This function checks that the activation code (i.e. reset token) provided by the form is valid, retrieves the user associated with the activation code, and resets their password. """ schema = schemas.ResetPasswordSchema().bind(request=self.request) form = deform.Form(schema) code = self.request.matchdict.get('code') if code is None: return httpexceptions.HTTPNotFound() activation = Activation.get_by_code(code) if activation is None: return httpexceptions.HTTPNotFound() user = User.get_by_activation(activation) if user is None: return httpexceptions.HTTPNotFound() if self.request.method != 'POST': return httpexceptions.HTTPMethodNotAllowed() err, appstruct = validate_form(form, self.request.POST.items()) if err is not None: return err user.password = appstruct['password'] self.request.db.delete(activation) self.request.session.flash(_('Your password has been reset!'), 'success') self.request.registry.notify(PasswordResetEvent(self.request, user)) return httpexceptions.HTTPFound(location=self.reset_password_redirect)
def activate(self): """ Handle a request for a user activation link. Checks if the activation code passed is valid, and (as a safety check) that it is an activation for the passed user id. If all is well, activate the user and redirect them to the stream. """ code = self.request.matchdict.get('code') id_ = self.request.matchdict.get('id') if code is None or id_ is None: return httpexceptions.HTTPNotFound() try: id_ = int(id_) except ValueError: return httpexceptions.HTTPNotFound() activation = Activation.get_by_code(code) if activation is None: return httpexceptions.HTTPNotFound() user = User.get_by_activation(activation) if user is None or user.id != id_: return httpexceptions.HTTPNotFound() # Activate the user (by deleting the activation) self.request.db.delete(activation) self.request.session.flash( _("Your e-mail address has been verified. " "Thank you!"), 'success') self.request.registry.notify(ActivationEvent(self.request, user)) return httpexceptions.HTTPFound( location=self.request.route_url('index'))
def _validate_request(request): """ Check that the passed request is appropriate for proceeding with account claim. Asserts that: - no-one is logged in - the claim token is provided and authentic - the user referred to in the token exists - the user referred to in the token has not already claimed their account and raises for redirect or 404 otherwise. """ # If signed in, redirect to stream if request.authenticated_userid is not None: _perform_logged_in_redirect(request) payload = _validate_token(request) if payload is None: raise exc.HTTPNotFound() try: username = util.user.split_user(payload['userid'])['username'] except ValueError: log.warn('got claim token with invalid userid=%r', payload['userid']) raise exc.HTTPNotFound() user = User.get_by_username(username) if user is None: log.warn('got claim token with invalid userid=%r', payload['userid']) raise exc.HTTPNotFound() # User already has a password? Claimed already. if user.password: _perform_already_claimed_redirect(request) return user
def index(): """A list of all the admin users as an HTML page.""" return {"admin_users": [u.username for u in User.admins()]}