Issue
i am trying to set custom validator for login form but it always show that ‘username and password are incorrect’ even when i put the valid ones. Any suggestions?
here is my code:
def login_check(form,field):
user_email = User.query.filter_by(email=form.email.data).first()
if user_email is None:
raise ValidationError('Username or password is incorrect')
elif not check_password_hash(field.data, user_email.password):
raise ValidationError('Username or password is incorrect')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[InputRequired(), Email()])
password = PasswordField('Password', validators=[InputRequired(),login_check])
submit = SubmitField('Login')
Solution
i replaced werkzeug.security with passlib.hash pbkdf2_sha256 and now it is working, i don’t know why is that
code
from passlib.hash import pbkdf2_sha256
def login_check(form,field):
user_email = User.query.filter_by(email=form.email.data).first()
if user_email is None:
raise ValidationError('Username or password is incorrect')
elif not pbkdf2_sha256.verify(field.data, user_email.password):
raise ValidationError('Username or password is incorrect')
route
@app.route('/register', methods=['POST','GET'])
def register():
reg_form = RegistrationForm()
if reg_form.validate_on_submit():
password = reg_form.password.data
hased_pass = pbkdf2_sha256.hash(password)
user = User(name=reg_form.name.data, lastname=reg_form.lastname.data,
email=reg_form.email.data, password=hased_pass)
db.session.add(user)
db.session.commit()
login_user(user)
flash(f'Welcome {user.name}, Your account have been created')
return redirect(url_for('index'))
Answered By – Radomir Mijovic
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0