よくわkラン letting users login Section 11, Lecture 49
ログイン機能を改善する。
models.pyに以下を追記する ユーザーが入力したpasswordを渡すことでdbにあるハッシュと一致するかをチェックする。
def check_password(self, password): return bcrypt.check_password_hash(self.user_password, password)
もし、一致しなかった場合はroutes.pyで一致しませんでしたとflashメッセージを表示させる。
user = User.query.filter_by(user_email=form.email.data).first()
user_email=form.email.dataについては、user_emailはDBの情報でform.email.dataはフォームからくる情報。
.first() でもし一致するものがない場合はnoneで返答される。
not userはもしユーザーがいない場合という意味である。
not user.check_passwordはパスワードが違う場合という意味である。
if not user or not user.check_password(form.password.data): flash('Invalid Credentials, Please try again') return redirect(url_for('authentication.do_the_login'))
一致した場合はリダイレクトさせる。
login_user(user, form.stay_loggedin.data) return redirect(url_for('main.display_books'))
return redirect(url_for('authentication.do_the_login'))とする事でもう一度ログインをさせることが出来る。init.pyにイニシャライズする。
session_protectionをstrongにする
SESSION_PROTECTION setting to None, "basic", or "strong"の3段階である。 https://flask-login.readthedocs.io/en/latest/