我正在使用带有SQLAlchemy和Flask-Login的Flask。
我可以成功登录并注销注册用户。
我发现令人困惑的是当我在登录页面输入错误的密码时,我将返回登录页面,其中包含“Welcome user@email.com”的flash消息,我原本想到的是,基于代码,只有在我成功登录后才会显示。
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
user = User.query.filter_by(email=form.email.data).first()
if form.validate_on_submit():
if user and check_password_hash(user.password, form.password.data):
session['user_id'] = user.id
flash('Welcome %s' % user.email)
return redirect(url_for('dashboard'))
else:
flash('Wrong email or password')
return render_template("login.html", form=form)
flash('The email or password is wrong.')
return render_template("login.html", form=form)
编辑:感谢Tigra,这就是我最终的目标。
在 views.py
中@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
user = User.query.filter_by(email=form.email.data).first()
if request.method == "POST":
if form.validate():
# the session can't be modified as it's signed,
# so it's a safe place to store the user
session['user_id'] = user.id
flash('Welcome %s' % user.email)
return redirect(url_for('dashboard'))
else:
flash('Wrong email or password')
return render_template("login.html", form=form)
return render_template("login.html", form=form)
在 forms.py
中from models import User
from werkzeug import check_password_hash
class LoginForm(Form):
email = TextField('email', validators = [Required(), Email()])
password = PasswordField('password', validators = [Required()])
remember_me = BooleanField('remember_me', default = False)
def __init__(self, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
self.user = None
def validate(self):
rv = Form.validate(self)
if not rv:
return False
user = User.query.filter_by(email=self.email.data).first()
if user is None:
self.email.errors.append('Unknown username')
return False
if not check_password_hash(user.password,self.password.data):
self.password.errors.append('Invalid password')
return False
self.user = user
return True
答案 0 :(得分:3)
你有两个问题:
1)您不应在表单验证后进行此类检查(登录/密码)。它应该在表单内部定义,阅读有关wtforms的自定义验证器
2)另外,请确保您提供的格式是实际格式,因为您在呈现的格式中至少有错误:
form = LoginForm()
user = User.query.filter_by(email=form.email.data).first()
所以不能确定没有更多 另外,你的passcheck函数来自werzkeug.security?
对于表单自定义验证,有一个例子:
使用这种方法,实际验证失败,而不是额外检查
class LoginForm(SafeForm):
email=TextField(__("E-Mail"),validators=[Required()])
password=PasswordField(__("Password"),validators=[Required()])
submit=SubmitField(__("Login"))
def __init__(self,*k,**kk):
self._user=None #for internal user storing
super(LoginForm,self).__init__(*k,**kk)
def validate(self):
self._user=User.query.filter(User.email==self.email.data).first()
return super(LoginForm,self).validate()
def validate_email(self,field):
if self._user is None:
raise ValidationError(_("E-Mail not recognized"))
def validate_password(self,field):
if self._user is None:
raise ValidationError() #just to be sure
if not self._user.validate_password(self.password.data): #passcheck embedded into user model
raise ValidationError(_("Password incorrect"))