简体   繁体   English

Flask Python中的登录逻辑无效

[英]Invalid Login logic in Flask Python

I'm using Flask with SQLAlchemy and Flask-Login. 我正在使用带有SQLAlchemy和Flask-Login的Flask。

I can successfully login and logout a registered user. 我可以成功登录并注销注册用户。

What I find confusing is when I enter an incorrect password on the login page, I'm returned to the login page with a flash message of "Welcome user@email.com", which I would have thought, based on the code, would only appear if I successfully logged in. 我发现令人困惑的是,当我在登录页面输入错误的密码时,我将返回登录页面,其中包含“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)

EDIT : Thanks to Tigra, this is what I ended up with. 编辑 :感谢Tigra,这就是我最终的结果。

In views.py 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)

In forms.py 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

You have two problems: 你有两个问题:

1) You should not make such a check (login/password) after form validation. 1)您不应在表单验证后进行此类检查(登录/密码)。 It should be defined inside form itself, read about custom validators for wtforms 它应该在表单内部定义,阅读有关wtforms的自定义验证器

2) Also, make sure, that formatting you presented is actual one, becouse you have at least mistake in presented formatting: 2)另外,请确保您呈现的格式是实际格式,因为您至少在呈现的格式中出错:

form = LoginForm()
    user = User.query.filter_by(email=form.email.data).first()

So can't be sure there is not more. 所以不能确定没有更多。
Also, your passcheck function is from werzkeug.security? 另外,你的passcheck函数来自werzkeug.security?

As for Form custom validation there is one example: 至于表单自定义验证,有一个例子:
With this approach actual validation fails, not additional check 使用此方法,实际验证失败,而不是额外检查

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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM