53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
from flask import Blueprint, render_template, redirect, url_for, flash, request
|
|
from flask_login import login_user, login_required, logout_user, current_user
|
|
from app import db, bcrypt
|
|
from app.models import User
|
|
from app.forms import LoginForm, RegistrationForm
|
|
|
|
auth_bp = Blueprint('auth', __name__)
|
|
|
|
|
|
# 用户注册
|
|
@auth_bp.route('/register', methods=['GET', 'POST'])
|
|
def register():
|
|
form = RegistrationForm()
|
|
if form.validate_on_submit():
|
|
#检查手机号或用户名是否已经存在
|
|
user = User.query.filter_by(phone_number=form.phone_number.data).first()
|
|
if user:
|
|
flash('手机号已注册', 'danger')
|
|
return redirect(url_for('auth.register'))
|
|
|
|
#密码加密存储
|
|
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
|
|
new_user = User(username=form.username.data, phone_number=form.phone_number.data, password=hashed_password)
|
|
db.session.add(new_user)
|
|
db.session.commit()
|
|
flash('注册成功,您可以登录了!', 'success')
|
|
return redirect(url_for('auth.login'))
|
|
|
|
return render_template('auth/register.html', form=form)
|
|
|
|
|
|
#用户登录
|
|
@auth_bp.route('/login', methods=['GET', 'POST'])
|
|
def login():
|
|
form = LoginForm()
|
|
if form.validate_on_submit():
|
|
user = User.query.filter_by(username=form.username.data).first()
|
|
if user and bcrypt.check_password_hash(user.password, form.password.data):
|
|
login_user(user)
|
|
flash('登录成功', 'success')
|
|
return redirect(url_for('index'))
|
|
flash('用户名或密码错误', 'danger')
|
|
return render_template('auth/login.html', form=form)
|
|
|
|
|
|
#用户注销
|
|
@auth_bp.route('/logout')
|
|
@login_required
|
|
def logout():
|
|
logout_user()
|
|
flash('您已注销', 'info')
|
|
return redirect(url_for('index'))
|