def change_password(user_name, password, session=None): user = user_exist(name=user_name, session=session) check = safe.check(password) if check.strength not in ['medium', 'strong']: raise WeakPassword( 'Password {0} is not strong enough'.format(password)) user.password = unicode(generate_password_hash(password))
def validate_confirm_pwd(self, confirm_pwd): p = confirm_pwd.data if not (bool(safe.check(p))): raise ValidationError('Password is too predictable') elif self.username.data in p: raise ValidationError('Password is too predictable') elif p in self.username.data: raise ValidationError('Password is too predictable')
def password(self, raw: str): result = safe.check(raw, length=self.min_password_length, freq=0, min_types=1, level=PASS_COMPLEXITY.TERRIBLE) assert result, 'Incorrect password, reason: {}'.format(result.message) self._hashed_password = sha256.hash(raw)
def change_password(username='******', password='', session=None): check = safe.check(password) if check.strength not in ['medium', 'strong']: raise WeakPassword('Password {0} is not strong enough'.format(password)) user = get_user(username=username, session=session) user.password = str(generate_password_hash(password)) session.commit()
def validate_password(self, password): password_check = safe.check(password.data, length=8, min_types=4, level=3) if not password_check: raise ValidationError( 'Password is not secure. Please have at least 8 Characters including numbers, one special symbol and upper and lower case letters' )
def submit_password(): password = request.form['password'] if not safe.check(password): flash('Oops: that password is too easily guessed. ' + \ 'Try again with a longer one using a mix of numbers, ' + \ 'symbols, upper and lower case.', 'user') print_debug( ' submit_password: failed safe.check("{}")'.format(password)) return request.base_url + '?action=edit' else: request.page.user.set_password(password) print_debug(' submit_password: password reset') return request.base_url
def update_profile(self, id, data): try: updateData = {} user = self.get_user(id) for key in data: # checking for username change if key == "usernameData": if user['username'] == data[key]: continue updateData["username"] = data[key] # checking for password change if key == "passwordData": if not (bcrypt.check_password_hash( user['password'], data[key]['oldPassword'])): return False strong = safe.check(data[key]['newPassword']) if not strong: return True newPassword = bcrypt.generate_password_hash( data[key]['newPassword']).decode("utf-8") updateData["password"] = newPassword # creating the update and commiting to the DB if len(updateData) > 0: update = {"$set": updateData} filterData = {'public_id': user['public_id']} mongo.db.users.update_one(filterData, update) # getting the new data of the user userUpdate = self.get_user(id) # starting a new session for the user userData = self.init_session(userUpdate) response = { "status": True, "message": "Your profile has been updated successfully", "userData": userData } except: response = { "status": False, "error": "Something went wrong. Please try again." } # return response return response
def settings(): if request.method == 'GET': if not current_user.is_authenticated: return redirect(url_for('index')) return render_template('settings.html') if request.form.get('csrftoken', None) is None or request.form.get( 'csrftoken', None) != current_user.csrf_token: return redirect(url_for('settings')) if request.form.get('inputPassword', None) is not None and request.form.get('repeatPassword', None) is not None\ and request.form.get('oldPassword', None) is not None: old_password = request.form['oldPassword'] new_password = request.form['newPassword'] if bool(not safe.check(new_password)): flash('Password is too weak') return redirect(url_for('settings')) if hashpw(old_password, current_user.password): current_user.password = hashpw(new_password, gensalt()) db.session.commit() else: flash('Old password is invalid') return redirect(url_for('settings')) return redirect(url_for('settings')) if request.form.get('oldEmail', None) is not None and request.form.get( 'newEmail', None) is not None: old_email = request.form['oldEmail'] new_email = request.form['newEmail'] if current_user.email == old_email: if User.query.filter_by(email=new_email).first() is not None: flash('Email already taken') return redirect(url_for('settings')) current_user.email = new_email db.session.commit() else: flash('Old email is invalid') return redirect(url_for('settings')) if request.form.get('inputName', None) is not None: new_name = redirect.form['inputName'] if User.query.filter_by(name=new_name).first() is not None: flash('Username already taken') return redirect(url_for('settings')) current_user.name = new_name db.session.commit() return redirect(url_for('settings')) return redirect(url_for('badrequest'))
def check_secure_password(form, field): strength = safe.check(field.data) messages = { 'password is too short': __('La contraseña es muy corta, la longitud ' 'mínima es de 8 caracteres'), 'password has a pattern': __('La contraseña es un patrón'), 'password is too common': __('La contraseña es muy común'), 'password is too simple': __('La contraseña es muy simple'), 'password is good enough, but not strong': __('La contraseña es buena, pero no lo suficiente, utilice ' 'números, letras y símbolos'), } if not strength.valid: raise ValidationError(messages[strength.message])
def signup(): if request.method == 'GET': if current_user.is_authenticated: return redirect(url_for('index')) return render_template('signup.html') if request.form.get('inputName', None) is not None and request.form.get('inputPassword', None) is not None\ and request.form.get('inputEmail', None) is not None and request.form.get('repeatPassword', None) is not None: name = request.form['inputName'] password = request.form['inputPassword'] email = request.form['inputEmail'] repeat_password = request.form['repeatPassword'] if bool(not safe.check(password)): flash('Password is too weak') return redirect(url_for('signup')) if User.query.filter_by(email=email).first() is not None: flash('Email is already used') return redirect(url_for('signup')) if not validate_email(email, verify=True): flash('Email is not valid') return redirect(url_for('signup')) if User.query.filter_by(name=name).first() is not None: flash('Username is already taken') return redirect(url_for('signup')) if password != repeat_password: flash('Passwords do not match') return redirect(url_for('signup')) if len(password) < 8: flash('Password must be at least 8 characters long') return redirect(url_for('signup')) if len(name) >= 20: flash('Username must be less than 20 characters long') return redirect(url_for('signup')) user = User(name, password, email) db.session.add(user) db.session.commit() return redirect(url_for('login')) return redirect(url_for('badrequest'))
def test_strong(): s = safe.check('yhnolkuT.') assert bool(s) assert 'perfect' in s.message
def test_simple(): s = safe.check('yhnolku', length=6) assert not s assert 'simple' in s.message
def test_medium(): s = safe.check('yhnolkuT', length=7) assert not s assert repr(s) == 'medium'
def test_common(): s = safe.check('password') assert not s assert 'common' in s.message
def test_short(): s = safe.check('1') assert not s assert 'short' in s.message
def validate_password(self, password): p = password.data if not (bool(safe.check(p))): raise ValidationError('Password is too predictable')
def test_medium(): s = safe.check('yhnolkuT') assert s assert repr(s) == 'medium'
def validate_confirm_pwd(self, confirm_pwd): p = confirm_pwd.data if not (bool(safe.check(p))): raise ValidationError('Password is too predictable')
def __call__(self, form, field): password = field.data strength = safe.check(password) if strength.strength not in ['medium', 'strong']: raise ValidationError(self.message)
def test_step(): s = safe.check('abcdefg', length=7) assert not s assert 'pattern' in s.message
def test_no_cache_on_safe_check(): cache_file = _clear_cache_file() s = safe.check('yhnolkuT.', cache_words=False) assert not os.path.exists(cache_file)
def validate_password(self, password): """Validate password.""" if password.data != '' and repr(safe.check(password.data)) != 'strong': raise ValidationError("Password isn't strong enough.")
def test_asdf(): s = safe.check('dfghjkl', length=7) assert not s assert 'pattern' in str(s)
def validate_password(self, password): strong = safe.check(password.data) if not strong: raise ValidationError('Password not strong enough')
def test_simple(): s = safe.check('yhnolku') assert s assert 'simple' in s.message
def signup(): signup_form = RegisterForm() force_admin_creation = require_admin_account_creation() if request.method == "POST": if signup_form.validate_on_submit(): username = signup_form.username.data password = signup_form.password.data password_confirm = signup_form.confirm_password.data is_admin = signup_form.is_admin.data if is_admin != "1" and is_admin != "0": flash("Please do not tamper with the form data.", "error") return redirect(url_for("signup")) else: # Convert the is_admin value to a bool value since it's easier to work with such values # is_admin = 0 = False # is_admin = 1 = True is_admin = bool(int(is_admin)) # Check if an admin account is actually required (do not rely on passed hidden field value since it may have been tampered with) if is_admin and not force_admin_creation: flash( "Please do not tamper with the form data (admin rights were requested although an admin account already exists).", "error") return redirect(url_for("signup")) if not username or not password or not password_confirm: flash("Please fill out every field.", "warning") return redirect(url_for("signup")) if password != password_confirm: flash("Password confirmation did not match your password.", "error") return redirect(url_for("signup")) forbidden_strength_lvl = [] # Require special password strength when creating the admin account if is_admin: forbidden_strength_lvl.append("terrible") forbidden_strength_lvl.append("simple") forbidden_strength_lvl.append("medium") else: forbidden_strength_lvl.append("terrible") forbidden_strength_lvl.append("simple") pw_check = safe.check(password) app.logger.debug("strength: %s" % pw_check.strength) if pw_check.strength in forbidden_strength_lvl: flash( "Password strength is: %s (reason: %s)." % (pw_check.strength, pw_check.message), "error") return redirect(url_for("signup")) # Check if the username already exists dup = db.session.query( exists().where(User.username == username)).scalar() if dup: flash("User %s already exists." % username, "error") return redirect(url_for("signup")) new_user = User(username=username) new_user.set_password(password) # Set admin privileges depending on the hidden field new_user.is_admin = is_admin db.session.add(new_user) db.session.commit() flash("%s, your account has been successfully created." % username, "success_signup") return redirect(url_for("signup")) else: if force_admin_creation: # Set the hidden field to 1 (we need this field to evaluate whether the account to be created is doing to be an admin) # We need the field create_admin to display the info message that the account to be created is going to be an admin account signup_form.is_admin.data = "1" return render_template("signup.html", form=signup_form, create_admin="1") else: # No need to set signup_form.is_admin.data since it defaults to 0 (no admin) return render_template("signup.html", form=signup_form, create_admin="0")
def validate_password(self, field): c = safe.check(field.data) if bool(c): return True self.password.errors.append(str(c)) return False
def validate_password(self, password): if not bool(safe.check(password.data, length=4, level=2)): raise validators.ValidationError( 'Password too predictable. Try adding a capital letters, numbers or special characters.' )
def change_password(user_name, password, session=None): user = user_exist(name=user_name, session=session) check = safe.check(password) if check.strength not in ['medium', 'strong']: raise WeakPassword('Password {0} is not strong enough'.format(password)) user.password = unicode(generate_password_hash(password))