Flask 用户身份认证
项目代码见:GitHub - euansu123/FlaskMarket
前提条件
bash
# flask-bcrypt 用户密码加密存储
pip install flask_bcrypt -i https://pypi.tuna.tsinghua.edu.cn/simple/
# flask提供的用户登录方法
pip install flask_login -i https://pypi.tuna.tsinghua.edu.cn/simple/
用户注册
后端方法:
python
@app.route("/register", methods=["GET", "POST"])
def register_page():
form = RegisterForm()
if form.validate_on_submit():
# 创建用户
user_to_create = User(username=form.username.data,
email_address=form.email.data,
password=form.password1.data)
db.session.add(user_to_create)
db.session.commit()
print("用户{username}创建成功".format(username=form.username.data))
return redirect(url_for('login_page'))
if form.errors != {}:
for err_msg in form.errors.values():
print("{}".format(err_msg))
flash(f"There was an error with creating account:{err_msg}", category="danger")
return render_template("register.html", form=form)
模型方法:
python
# @property 获取用户密码属性
# @password.setter 设置用户密码
from market import bcrypt
class User(db.Model, UserMixin):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(length=30), nullable=False, unique=True)
email_address = db.Column(db.String(length=50), nullable=False, unique=True)
password_hash = db.Column(db.String(length=60), nullable=False)
budget = db.Column(db.Integer(), nullable=False, default=1000)
items = db.relationship('Item', backref='owned_user', lazy=True)
@property
def password(self):
return self.password
@password.setter
def password(self, plain_text_password):
self.password_hash = bcrypt.generate_password_hash(plain_text_password).decode('utf-8')
前端页面:
html
{% extends "base.html" %}
{% block title%}
Register Page
{% endblock %}
{% block content%}
<body>
<div class="container">
<form method="POST" class="form-register" style="color:white">
{{ form.hidden_tag() }}
<img class="mb-4" src="{{ url_for('static', filename='img/euansu.png') }}" style="width: 100px;height: 100px;margin-top: 30px;"/>
<h1 class="h3 mb-3 font-weight-normal">
Please Create your Account
</h1>
{{ form.username.label() }}
{{ form.username(class="form-control", placeholder="User Name") }}
{{ form.email.label() }}
{{ form.email(class="form-control", placeholder="Email Address") }}
{{ form.password1.label() }}
{{ form.password1(class="form-control", placeholder="Password") }}
{{ form.password2.label() }}
{{ form.password2(class="form-control", placeholder="Confirm Password") }}
<br />
{{form.submit(class="btn btn-lg btn-block btn-primary")}}
</form>
</div>
</body>
{% endblock %}
页面实现:
用户注册,成功后跳转至登录页面
用户登录
后端方法:
python
from market.forms import LoginForm
from flask_login import login_user, login_required
# 需要登录后才能访问的页面,添加 login_required 装饰器
@app.route("/market")
@login_required
def market_page():
items = Item.query.all()
return render_template("market.html", items=items)
@app.route('/login', methods=['GET', 'POST'])
def login_page():
form = LoginForm()
if form.validate_on_submit():
attempted_user = User.query.filter_by(username=form.username.data).first()
if attempted_user and attempted_user.check_password_correction(attempted_password=form.password.data):
login_user(attempted_user)
flash(f'Success! You are logged in as: {attempted_user.username}', category='success')
return redirect(url_for('market_page'))
else:
flash('Username and password are not match! Please try again', category='danger')
return render_template('login.html', form=form)
# 这里用到了一个表单,需要实现在forms.py,也即你自己的表单文件中进行定义
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import Length, EqualTo, Email, DataRequired
class LoginForm(FlaskForm):
username = StringField(label='User Name:', validators=[DataRequired()])
password = PasswordField(label='Password:', validators=[DataRequired()])
submit = SubmitField(label='Sign in')
模型文件也需要队用户对象做一些修改,否则直接使用 flask
自带的 login_user
会报如下的错误:
python
from market import db,login_manager
from market import bcrypt
from flask_login import UserMixin
# 添加如下内容
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# User对象需要继承UserMixin类
class User(db.Model,UserMixin):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(length=30), nullable=False, unique=True)
email_address = db.Column(db.String(length=50), nullable=False, unique=True)
password_hash = db.Column(db.String(length=60), nullable=False)
budget = db.Column(db.Integer(), nullable=False, default=1000)
items = db.relationship('Item', backref='owned_user', lazy=True)
@property
def password(self):
return self.password
@password.setter
def password(self, plain_text_password):
self.password_hash = bcrypt.generate_password_hash(plain_text_password).decode('utf-8')
# 这里是用来判断用户输入的密码是否正确
def check_password_correction(self, attempted_password):
return bcrypt.check_password_hash(self.password_hash, attempted_password)
前端文件:
html
{% extends 'base.html' %}
{% block title %}
Login Page
{% endblock %}
{% block content %}
<body>
<div class="container">
<form method="POST" class="form-signin" style="color:white">
{{ form.hidden_tag() }}
<img class="mb-4" src="{{ url_for('static', filename='img/euansu.png') }}" style="width: 100px;height: 100px;margin-top: 30px;"/>
<h1 class="h3 mb-3 font-weight-normal">
Please Login
</h1>
<br>
{{ form.username.label() }}
{{ form.username(class="form-control", placeholder="User Name") }}
{{ form.password.label() }}
{{ form.password(class="form-control", placeholder="Password") }}
<br>
<div class="checkbox mb-3">
<h6>Do not have an account?</h6>
<a class="btn btn-sm btn-secondary" href="{{ url_for('register_page') }}">Register</a>
</div>
{{ form.submit(class="btn btn-lg btn-block btn-primary") }}
</form>
</div>
</body>
{% endblock %}
实现效果:
输入密码错误,页面报错。
输入密码正确,跳转进入 market
页面。
直接访问 market
页面报错,提示缺少所需要的用户信息。
注销登录
后端方法:
python
from flask_login import logout_user
@app.route('/logout')
def logout_page():
logout_user()
flash("You have been logged out!", category='info')
return redirect(url_for("home_page"))
前端页面:
原来的 header
这里有 Login
和 Register
两个方法,这里修改一下,如果用户已经登录,这里修改为 Logout
,修改后的代码如下:
python
{% if current_user.is_authenticated %}
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" style="color: lawngreen; font-weight: bold">
<i class="fas fa-coins"></i>
{{ current_user.prettier_budget }}
</a>
</li>
<li class="nav-item">
<a class="nav-link">Welcome, {{ current_user.username }}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('logout_page') }}">Logout</a>
</li>
</ul>
{% else %}
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{{ url_for('login_page') }}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('register_page') }}">Register</a>
</li>
</ul>
{% endif %}
实现效果:
点击 Logout
调用 logout_page
方法,效果如下: