def validate(self): if not self.email.data or self.email.data.strip() == '': self.email.errors.append(get_message('EMAIL_NOT_PROVIDED')[0]) return False if not self.password.data: self.add_error_to_wtf_field(self.password, get_message('PASSWORD_NOT_SET')[0]) return False user = self.login_verification.get_user_from_email(self.email.data) self.user = user if self.user is not None: if not self.user.is_active: self.add_error_to_wtf_field(self.email, get_message('DISABLED_ACCOUNT')[0]) return False if self.user.password is not None and utils.verify_password( self.password.data, self.user.password): return True elif self.user.password is None and self.login_verification.is_success_pwd( self.user.email, self.password.data): return True else: self.add_error_to_wtf_field(self.email, get_message('INVALID_PASSWORD')[0]) return False else: self.add_error_to_wtf_field(self.email, get_message('USER_DOES_NOT_EXIST')[0]) return False
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=config_value('RESET_PASSWORD_WITHIN'))) if invalid or expired: return redirect(url_for('login.forgot_password')) form = ResetPasswordForm() if form.validate_on_submit(): update_password(user, form.new_password.data) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect( get_url(config_value('POST_RESET_VIEW')) or get_url(config_value('POST_LOGIN_VIEW'))) else: current_app.logger.error('Form did not validate: {}'.format( form.errors)) flash(form.errors, 'error') return render_template('login/reset_password.html', reset_password_form=form, reset_password_token=token)
def validate(self): if not super().validate(): return False self.user = find_user(self.username.data) if self.user is None: self.username.errors.append(get_message("USER_DOES_NOT_EXIST")[0]) # Reduce timing variation between existing and non-existing users hash_password(self.password.data) return False if not self.user.password: self.password.errors.append(get_message("PASSWORD_NOT_SET")[0]) # Reduce timing variation between existing and non-existing users hash_password(self.password.data) return False self.password.data = _security._password_util.normalize( self.password.data) if not self.user.verify_and_update_password(self.password.data): self.password.errors.append(get_message("INVALID_PASSWORD")[0]) return False self.requires_confirmation = requires_confirmation(self.user) if self.requires_confirmation: self.username.errors.append( get_message("CONFIRMATION_REQUIRED")[0]) return False if not self.user.is_active: self.username.errors.append(get_message("DISABLED_ACCOUNT")[0]) return False return True
def validate(self): """ Copy-pasted from flask_security and use the altered version of `verify_and_update_password`. """ if not super(LoginForm, self).validate(): return False self.user = _datastore.get_user(self.email.data) if self.user is None: self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False if not self.user.password: self.password.errors.append(get_message('PASSWORD_NOT_SET')[0]) return False if not verify_and_update_password(self.password.data, self.user): self.password.errors.append(get_message('INVALID_PASSWORD')[0]) return False if requires_confirmation(self.user): self.email.errors.append(get_message('CONFIRMATION_REQUIRED')[0]) return False if not self.user.is_active: self.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) return False return True
def confirm_email(token): """View function which handles a email confirmation request.""" security = current_app.extensions.get('security') expired, invalid, user = confirm_email_token_status(token) if not user or invalid: invalid = True do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) if expired: send_confirmation_instructions(user) do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email, within=security.confirm_email_within)) if invalid or expired: return redirect( get_url(security.confirm_error_view) or url_for('send_confirmation')) if user != current_user: logout_user() login_user(user) if confirm_user(user): msg = 'EMAIL_CONFIRMED' else: msg = 'ALREADY_CONFIRMED' do_flash(*get_message(msg)) return redirect( get_url(security.post_confirm_view) or get_url(security.post_login_view))
def validate(self): # Use super of LoginForm, not super of CustomLoginForm, since I # want to skip the LoginForm validate logic if not super(LoginForm, self).validate(): return False self.email.data = remove_null_caracters(self.email.data) self.user = _datastore.get_user(self.email.data) if self.user is None: self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False self.user.password = remove_null_caracters(self.user.password) if not self.user.password: self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False self.password.data = remove_null_caracters(self.password.data) if not verify_and_update_password(self.password.data, self.user): self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False # if requires_confirmation(self.user): # self.email.errors.append(get_message('CONFIRMATION_REQUIRED')[0]) # return False if not self.user.is_active: self.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) return False return True
def validate_cache_data(self, token): self.success_message = current_app.config[ 'SECURITY_MSG_EMAIL_CONFIRMED'][0] expired, invalid, self.user = confirm_email_token_status(token) self.new_email = get_new_email(self.user) if not self.new_email: flash( 'Unable to retrieve old email, please try updating your email address again', 'error') return self.update_error() if not self.user or invalid: do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) return self.update_error() if expired: send_confirmation_instructions(self.user, ) do_flash(*get_message('CONFIRMATION_EXPIRED', email=self.user.email, within=config_value('CONFIRM_EMAIL_WITHIN'))) return self.update_error() if self.user != current_user: logout_user() login_user(self.user) return self.validation_success()
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=_security.reset_password_within)) if invalid or expired: return redirect(url_for('browser.forgot_password')) has_error = False form = _security.reset_password_form() if form.validate_on_submit(): try: update_password(user, form.password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash( gettext( u'SMTP Socket error: {}\nYour password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash( gettext( u'SMTP error: {}\nYour password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash( gettext(u'Error: {}\nYour password has not been changed.'). format(e), 'danger') has_error = True if not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect( get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return _security.render_template( config_value('RESET_PASSWORD_TEMPLATE'), reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def validate(self): """Validate.""" log = current_app.artemis_logger log.info("RADIUS authenticate() using username %s" % self.email.data) if not super(RADIUSLoginForm, self).validate(): log.warn("super() validate was false!") return False if self.email.data.strip() == "": self.email.errors.append(get_message("USERID_NOT_PROVIDED")[0]) log.warn("userid was not provided") return False if self.password.data.strip() == "": log.warn("password was not provided") self.password.errors.append( get_message("PASSWORD_NOT_PROVIDED")[0]) return False try: admin_user = _datastore.get_user(1) if self.email.data == admin_user.username: log.info("Login using Super-user login") return self._try_local_auth() auth_result, role = _datastore.authenticate( self.email.data, self.password.data) if auth_result is None: self.password.errors.append("No response from RADIUS") log.info("RADIUS authenticate() returned None") return False if not auth_result: self.password.errors.append(get_message("INVALID_PASSWORD")[0]) log.info("RADIUS authenticate() returned False") return False log.info("RADIUS authenticate() returned True. Assigning role %s" % role) username = self.email.data self.user = _datastore.find_user(username=username) if self.user: self.user.password = None self.user.email = username else: self.user = _datastore.create_user(username=username, email=username, password=None, active=True) self._set_role(self.user, _datastore.find_role(role)) _datastore.commit() except Exception: self.password.errors.append( "Internal error. Contact developer and/or check the logs.") log.exception("Unexpected error while handling RADIUS form") return False return True
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=_security.reset_password_within)) if invalid or expired: return redirect(url_for('browser.forgot_password')) has_error = False form = _security.reset_password_form() if form.validate_on_submit(): try: update_password(user, form.password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True if not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect(get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return _security.render_template( config_value('RESET_PASSWORD_TEMPLATE'), reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def verify_login(self, user, password=None, **kwargs): """Verify the login via password.""" if not user.password: _abort(get_message("PASSWORD_NOT_SET")[0], "password") if not verify_and_update_password(password, user): _abort(get_message("INVALID_PASSWORD")[0], "password") if requires_confirmation(user): _abort(get_message("CONFIRMATION_REQUIRED")[0]) if not user.is_active: _abort(get_message("DISABLED_ACCOUNT")[0])
def validate(self): if not super(ChangePasswordForm, self).validate(): return False if not verify_and_update_password(self.password.data, current_user): self.password.errors.append(get_message('INVALID_PASSWORD')[0]) return False if self.password.data.strip() == self.new_password.data.strip(): self.password.errors.append(get_message('PASSWORD_IS_THE_SAME')[0]) return False return True
def validate(self): if not super(SignedMessageLoginForm, self).validate(): return False self.user = _user.find_beet_account_name(self.message.signed_by_name) if self.user and requires_confirmation(self.user): self.message.errors.append(get_message("CONFIRMATION_REQUIRED")[0]) return False if self.user and not self.user.is_active: self.message.errors.append(get_message("DISABLED_ACCOUNT")[0]) return False return True
def post(self, **kwargs): """Confirm user email.""" user = self.get_user(**kwargs) if user != current_user: logout_user() if confirm_user(user): after_this_request(_commit) return jsonify({"message": get_message("EMAIL_CONFIRMED")[0]}) else: return jsonify({"message": get_message("ALREADY_CONFIRMED")[0]})
def get_user(self, token=None, **kwargs): """Retrieve a user by the provided arguments.""" # Verify the token expired, invalid, user = reset_password_token_status(token) if invalid: _abort(get_message('INVALID_RESET_PASSWORD_TOKEN')[0]) if expired: _abort( get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=current_security.reset_password_within)[0]) return user
def get_user(self, token=None, **kwargs): """Retrieve a user by the provided arguments.""" expired, invalid, user = confirm_email_token_status(token) if not user or invalid: _abort(get_message('INVALID_CONFIRMATION_TOKEN')) already_confirmed = user is not None and user.confirmed_at is not None if expired and not already_confirmed: _abort( get_message('CONFIRMATION_EXPIRED', email=user.email, within=current_security.confirm_email_within)) return user
def validate(self): """Validate LDAP logins against AD.""" if not super(LDAPLoginForm, self).validate(): return False if self.email.data.strip() == '': self.email.errors.append(get_message('USERID_NOT_PROVIDED')[0]) return False if self.password.data.strip() == '': self.password.errors.append( get_message('PASSWORD_NOT_PROVIDED')[0]) return False try: user_dn, ldap_data = _datastore.query_ldap_user(self.email.data) if user_dn is None: self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False if not _datastore.verify_password(user_dn, self.password.data): self.password.errors.append(get_message('INVALID_PASSWORD')[0]) return False ldap_email = ldap_data[config_value('LDAP_EMAIL_FIELDNAME')].value password = encrypt_password(self.password.data) if _datastore.find_user(email=ldap_email): self.user = _datastore.get_user(ldap_email) # note that this is being stored per user login self.user.password = password else: self.user = _datastore.create_user(email=ldap_email, password=password) _datastore.commit() except ldap3.LDAPExceptionError: self.password.errors.append(get_message('LDAP_SERVER_DOWN')[0]) self.user = _datastore.get_user(self.email.data) if not self.user.password: self.password.errors.append(get_message('PASSWORD_NOT_SET')[0]) return False if not verify_and_update_password(self.password.data, self.user): self.password.errors.append(get_message('INVALID_PASSWORD')[0]) return False if requires_confirmation(self.user): self.email.errors.append( get_message('CONFIRMATION_REQUIRED')[0]) return False if not self.user.is_active: self.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) return False return True
def register(): form = UserCustomForm() #Create a new user if request.method == 'POST' and form.validate(): data = { 'first_name': str(request.values.get('first_name').encode('utf-8')).title(), 'last_name': str(request.values.get('last_name').encode('utf-8')).title(), 'email': str(request.values.get('email').encode('utf-8')), } if (request.values.get('user_nic')): data['extras'] = {'auth_nic': str(request.values.get('user_nic'))} userUdata = datastore.create_user(**data) datastore.commit() send_confirmation_instructions(userUdata) do_flash(*get_message('CONFIRM_REGISTRATION', email=data['email'])) return redirect(url_for('security.login')) else: form.email.data = session.get('user_email') if form.email.data: form.email.render_kw = {'readonly': True} form.first_name.data = session.get('first_name') form.last_name.data = session.get('last_name') form.user_nic.data = session.get('user_nic') return theme.render('security/register_saml.html', form=form)
def forgot_password(): """View function that handles a forgotten password request.""" has_error = False form_class = _security.forgot_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): # Check the Authentication source of the User user = User.query.filter_by(email=form.data['email'], auth_source=INTERNAL).first() if user is None: # If the user is not an internal user, raise the exception flash( gettext( 'Your account is authenticated using an ' 'external {} source. ' 'Please contact the administrators of this ' 'service if you need to reset your password.').format( form.user.auth_source), 'danger') has_error = True if not has_error: try: send_reset_password_instructions(form.user) except SOCKETErrorException as e: # Handle socket errors which are not # covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(SMTP_SOCKET_ERROR).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(SMTP_ERROR).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(PASS_ERROR).format(e), 'danger') has_error = True if request.json is None and not has_error: do_flash(*get_message('PASSWORD_RESET_REQUEST', email=form.user.email)) if request.json and not has_error: return default_render_json(form, include_user=False) return _security.render_template( config_value('FORGOT_PASSWORD_TEMPLATE'), forgot_password_form=form, **_ctx('forgot_password'))
def confirm_change_email(token): """View function which handles a change email confirmation request. Based on confirm_email in Flask-Security.""" expired, invalid, user, new_email = ( confirm_change_email_token_status(token)) if not user or invalid: invalid = True do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) if expired: send_change_email_confirmation_instructions(user, new_email) do_flash(*(('You did not confirm your change of email within {0}. ' 'New instructions to confirm your change of email have ' 'been sent to {1}.' ).format(_security.confirm_email_within, new_email), 'error')) if invalid or expired: return redirect(url_for('home')) if user != current_user: logout_user() login_user(user) if change_user_email(user, new_email): after_this_request(_commit) msg = ('Thank you. Your change of email has been confirmed.', 'success') else: msg = ('Your change of email has already been confirmed.' 'info') do_flash(*msg) return redirect(url_for('home'))
def validate_on_submit(self): if not CustomForm.validate_on_submit(self): return self.validation_error() self.user = g.datastore.find_user(username=self.username.data) if self.user is None: self.user = g.datastore.find_user(email=self.username.data) if self.user is None: self.username.errors.append( current_app.config['SECURITY_MSG_USER_DOES_NOT_EXIST'][0]) return self.validation_error() if not self.user.password: self.password.errors.append( current_app.config['SECURITY_MSG_PASSWORD_NOT_SET'][0]) return self.validation_error() if not verify_and_update_password(self.password.data, self.user): self.password.errors.append( current_app.config['SECURITY_MSG_INVALID_PASSWORD'][0]) return self.validation_error() if requires_confirmation(self.user): do_flash(*get_message('CONFIRMATION_REQUIRED')) return self.validation_error() if not self.user.is_active: do_flash(*current_app.config['SECURITY_MSG_DISABLED_ACCOUNT']) return self.validation_error() return self.validation_success()
def login(): if request.is_json: form = _security.login_form(MultiDict(request.get_json())) else: form = _security.login_form(request.form) if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.is_json: return redirect(get_post_login_redirect(form.next.data)) if not request.is_json: return _security.render_template(config_value('LOGIN_USER_TEMPLATE'), login_user_form=form, **_ctx('login')) # override error messages if necessary confirmation_required = get_message('CONFIRMATION_REQUIRED')[0] if confirmation_required in form.errors.get('email', []): return jsonify({ 'error': confirmation_required, }), HTTPStatus.UNAUTHORIZED elif form.errors: username_fields = config_value('USER_IDENTITY_ATTRIBUTES') return jsonify({ 'error': f"Invalid {', '.join(username_fields)} and/or password." }), HTTPStatus.UNAUTHORIZED return jsonify({ 'user': form.user, 'token': form.user.get_auth_token(), })
def validate(self, extra_validators=None): result = super().validate() confirm_message = get_message('CONFIRMATION_REQUIRED')[0] msg = "Can't find the confirmation email? <a href=\"{}\">Resend it</a>" if confirm_message in self.email.errors: flash(msg.format(url_for('security.send_confirmation'))) return result
def validate(self): user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) time_now = datetime.datetime.now() # Use super of LoginForm, not super of CustomLoginForm, since I # want to skip the LoginForm validate logic if not super(LoginForm, self).validate(): audit_logger.warning( f"Invalid Login - User [{self.email.data}] from IP [{user_ip}] at [{time_now}]" ) return False self.email.data = remove_null_caracters(self.email.data) self.user = _datastore.find_user(username=self.email.data) if self.user is None: audit_logger.warning( f"Invalid Login - User [{self.email.data}] from IP [{user_ip}] at [{time_now}] - " f"Reason: [Invalid Username]") self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False self.user.password = remove_null_caracters(self.user.password) if not self.user.password: audit_logger.warning( f"Invalid Login - User [{self.email.data}] from IP [{user_ip}] at [{time_now}] - " f"Reason: [Invalid Password]") self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False self.password.data = remove_null_caracters(self.password.data) if not verify_and_update_password(self.password.data, self.user): audit_logger.warning( f"Invalid Login - User [{self.email.data}] from IP [{user_ip}] at [{time_now}] - " f"Reason: [Invalid Password]") self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False # if requires_confirmation(self.user): # self.email.errors.append(get_message('CONFIRMATION_REQUIRED')[0]) # return False if not self.user.is_active: audit_logger.warning( f"Invalid Login - User [{self.email.data}] from IP [{user_ip}] at [{time_now}] - " f"Reason: [Disabled Account]") self.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) return False return True
def change_password(): """View function which handles a change password request.""" has_error = False form_class = _security.change_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): try: change_user_password(current_user, form.new_password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash( gettext( u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger' ) has_error = True if request.json is None and not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_CHANGE')) return redirect(get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.json and not has_error: form.user = current_user return _render_json(form) return _security.render_template( config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password'))
def post(self, **kwargs): """Change user password.""" if not current_security.changeable: _abort(get_message("PASSWORD_CHANGE_DISABLED")[0]) self.verify_password(**kwargs) self.change_password(**kwargs) return self.success_response()
def post(self, **kwargs): """Send reset password instructions.""" if not current_security.recoverable: _abort(get_message("PASSWORD_RECOVERY_DISABLED")[0]) user = self.get_user(**kwargs) self.send_reset_password_instructions(user) return self.success_response(user)
def post(self, **kwargs): """Register a user.""" if not current_security.registerable: _abort(get_message("REGISTRATION_DISABLED")[0]) user = register_user(**kwargs) self.login_user(user) return self.success_response(user)
def send_login(): """View function that sends login instructions for passwordless login""" form = PasswordlessLoginForm(csrf_enabled=not app.testing) if form.validate_on_submit(): user = _datastore.find_user(**form.to_dict()) if user.is_active(): send_login_instructions(user, form.next.data) do_flash(*get_message('LOGIN_EMAIL_SENT', email=user.email)) else: form.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) return render_template('security/send_login.html', login_form=form, **_ctx('send_login'))
def validate(self): if not super(RegisterForm, self).validate(): return False if Users.objects(email=self.email.data.strip()): self.email.errors.append(get_message('HAVE_USER_WITH_THIS_EMAIL')[0]) return False if Users.objects(login=self.login.data.strip()): self.login.errors.append(get_message('HAVE_USER_WITH_THIS_LOGIN')[0]) return False if self.password.data != self.confirm.data: self.password.errors.append(get_message('DIFFERENT_PASSWORDS')[0]) return False return True
def change_password(): """View function which handles a change password request.""" has_error = False form_class = _security.change_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): try: change_user_password(current_user._get_current_object(), form.new_password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(SMTP_SOCKET_ERROR).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(SMTP_ERROR).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(PASS_ERROR).format(e), 'danger') has_error = True if request.json is None and not has_error: after_this_request(view_commit) do_flash(*get_message('PASSWORD_CHANGE')) old_key = get_crypt_key()[1] set_crypt_key(form.new_password.data, False) from pgadmin.browser.server_groups.servers.utils \ import reencrpyt_server_passwords reencrpyt_server_passwords(current_user.id, old_key, form.new_password.data) return redirect( get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.json and not has_error: form.user = current_user return default_render_json(form) return _security.render_template( config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password'))
def post(self, **kwargs): """Verify and login a user.""" if not current_app.config.get("ACCOUNTS_LOCAL_LOGIN_ENABLED"): _abort(get_message("LOCAL_LOGIN_DISABLED")[0]) user = self.get_user(**kwargs) self.verify_login(user, **kwargs) self.login_user(user) return self.success_response(user)
def delete_question(opportunity_id, question_id): question = Question.query.get(question_id) if question: if not question.opportunity.can_edit(current_user): sec_utils.do_flash(*sec_utils.get_message('UNAUTHORIZED')) return redirect('/') question.delete() flash('Question successfully deleted', 'alert-info') return redirect(url_for('beacon_admin.questions', opportunity_id=opportunity_id))
def send_confirmation(): """View function which sends confirmation instructions.""" form = SendConfirmationForm(csrf_enabled=not app.testing) if form.validate_on_submit(): user = _datastore.find_user(**form.to_dict()) if user.confirmed_at is None: send_confirmation_instructions(user) msg = get_message('CONFIRMATION_REQUEST', email=user.email) _logger.debug('%s request confirmation instructions' % user) else: msg = get_message('ALREADY_CONFIRMED') do_flash(*msg) return render_template('security/send_confirmation.html', reset_confirmation_form=form, **_ctx('send_confirmation'))
def validate(self): is_verified = True if not super(ResetPayForm, self).validate(): is_verified = False user = _datastore.find_user(email=self.email.data) if user is None: self.email.errors.append(get_message("USER_DOES_NOT_EXIST")[0]) is_verified = False if not is_verified: self.generate_image_code() return is_verified
def forgot_password(): """View function that handles a forgotten password request.""" has_error = False form_class = _security.forgot_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): try: send_reset_password_instructions(form.user) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True if request.json is None and not has_error: do_flash(*get_message('PASSWORD_RESET_REQUEST', email=form.user.email)) if request.json and not has_error: return _render_json(form, include_user=False) return _security.render_template( config_value('FORGOT_PASSWORD_TEMPLATE'), forgot_password_form=form, **_ctx('forgot_password'))
def validate(self): self.email_or_login.errors, self.password.errors = [], [] if self.email_or_login.data.strip() == '': self.email_or_login.errors.append(get_message('LOGIN_NOT_PROVIDED')[0]) return False if self.password.data.strip() == '': self.password.errors.append(get_message('PASSWORD_NOT_PROVIDED')[0]) return False self.user = _datastore.find_user(login=self.email_or_login.data.strip()) if self.user is None: self.user = _datastore.find_user(email=self.email_or_login.data.strip()) if self.user is None: self.email_or_login.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False if not self.user.password: self.password.errors.append(get_message('PASSWORD_NOT_SET')[0]) return False if not verify_and_update_password(self.password.data, self.user): self.password.errors.append(get_message('INVALID_PASSWORD')[0]) return False if not self.user.is_active: self.email_or_login.errors.append(get_message('DISABLED_ACCOUNT')[0]) return False return True
def reset_password(token): """View function that handles a reset password request.""" next = None form = ResetPasswordForm(csrf_enabled=not app.testing) if form.validate_on_submit(): try: user = reset_by_token(token=token, **form.to_dict()) msg = get_message('PASSWORD_RESET') next = (get_url(_security.post_reset_view) or get_url(_security.post_login_view)) except ResetPasswordError, e: msg = (str(e), 'error') if e.user: send_reset_password_instructions(e.user) msg = get_message('PASSWORD_RESET_EXPIRED', within=_security.reset_password_within, email=e.user.email) _logger.debug('Password reset error: ' + msg[0]) do_flash(*msg)
def forgot_password(): """View function that handles a forgotten password request.""" form = ForgotPasswordForm(csrf_enabled=not app.testing) if form.validate_on_submit(): user = _datastore.find_user(**form.to_dict()) send_reset_password_instructions(user) _logger.debug('%s requested to reset their password' % user) do_flash(*get_message('PASSWORD_RESET_REQUEST', email=user.email)) return render_template('security/forgot_password.html', forgot_password_form=form, **_ctx('forgot_password'))
def validate(self): # Use super of LoginForm, not super of CustomLoginForm, since I # want to skip the LoginForm validate logic if not super(LoginForm, self).validate(): return False self.user = _datastore.get_user(self.email.data) if self.user is None: self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False if not self.user.password: self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False if not verify_and_update_password(self.password.data, self.user): self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) return False # if requires_confirmation(self.user): # self.email.errors.append(get_message('CONFIRMATION_REQUIRED')[0]) # return False if not self.user.is_active: self.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) return False return True
def questions(opportunity_id): opportunity = Opportunity.query.get(opportunity_id) if opportunity: if not opportunity.can_edit(current_user): sec_utils.do_flash(*sec_utils.get_message('UNAUTHORIZED')) return redirect('/') answered, unanswered = [], [] for question in opportunity.questions: if question.answer_text: answered.append(question) else: unanswered.append(question) return render_template( 'beacon/admin/questions.html', unanswered=unanswered, answered=answered, opportunity=opportunity, ) abort(404)
def answer_question(opportunity_id, question_id): question = Question.query.get(question_id) if question: if not question.opportunity.can_edit(current_user): sec_utils.do_flash(*sec_utils.get_message('UNAUTHORIZED')) return redirect('/') form = AnswerForm(obj=question) if form.validate_on_submit(): answer = {'answer_text': form.answer_text.data} if question.answer_text: answer['edited'] = True answer['edited_at'] = datetime.datetime.utcnow() question.update(**answer) flash('Answer successfully edited.') else: answer['answered_at'] = datetime.datetime.utcnow() answer['answered_by'] = current_user question.update(**answer) flash('This question has been answered! The Vendor has been notified and the question and answer are now public.') to_email = set([ question.opportunity.created_by.email, question.opportunity.contact.email, question.asked_by.email ]).difference(set([current_user.email])) Notification( to_email=list(to_email), subject='New answer to a questio on Beacon', html_template='beacon/emails/answered_question.html', question=question ).send(multi=True) return redirect( url_for('beacon_admin.questions', opportunity_id=opportunity_id) ) return render_template( 'beacon/admin/answer_question.html', form=form, question=question, opportunity_id=opportunity_id ) abort(404)
try: user = _security.auth_provider.authenticate(form) except ConfirmationError, e: msg = str(e) confirm_url = url_for('send_confirmation', email=e.user.email) except BadCredentialsError, e: msg = str(e) form.password.errors.append(msg) if user: if login_user(user, remember=form.remember.data): after_this_request(_commit) if request.json: return _json_auth_ok(user) return redirect(get_post_login_redirect()) form.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) _logger.debug('Unsuccessful authentication attempt: %s' % msg) if request.json: return _json_auth_error(msg) if confirm_url: do_flash(msg, 'error') return redirect(confirm_url) return render_template('security/login.html', login_form=form, **_ctx('login'))
def check_any_role(*roles): if CurrentUser.has_any_role_permission(*roles).can(): return True else: utils.do_flash(*utils.get_message('UNAUTHORIZED')) return False