This repository has been archived on 2023-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
web-gpt/project/auth.py

84 lines
2.8 KiB
Python
Raw Normal View History

2023-03-31 22:11:34 +08:00
from flask_login import login_user, logout_user
from flask import Blueprint, render_template, redirect, url_for, request, flash
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_required, current_user, login_manager
from .models import User
from . import db
auth = Blueprint('auth', __name__)
@auth.route('/login')
def login():
return render_template('login.html')
@auth.route('/login', methods=['POST'])
def login_post():
# login code goes here
email = request.form.get('email')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
user = User.query.filter_by(email=email).first()
# check if the user actually exists
# take the user-supplied password, hash it, and compare it to the hashed password in the database
if not user or not check_password_hash(user.password, password):
2023-03-31 22:53:52 +08:00
flash('请检查登录信息')
2023-03-31 22:11:34 +08:00
# if the user doesn't exist or password is wrong, reload the page
return redirect(url_for('auth.login'))
# if the above check passes, then we know the user has the right credentials
login_user(user, remember=remember)
return redirect(url_for('main.profile'))
@auth.route('/signup')
def signup():
return render_template('signup.html')
@auth.route('/signup', methods=['POST'])
def signup_post():
# code to validate and add user to database goes here
email = request.form.get('email')
name = request.form.get('name')
password = request.form.get('password')
# if this returns a user, then the email already exists in database
user = User.query.filter_by(email=email).first()
if user: # if a user is found, we want to redirect back to signup page so user can try again
flash('此邮箱已注册!')
return redirect(url_for('auth.signup'))
if not (email):
flash('Email missing!')
return redirect(url_for('auth.signup'))
if not (name):
name = email
if not (password):
flash('Password missing!')
return redirect(url_for('auth.signup'))
# create a new user with the form data. Hash the password so the plaintext version isn't saved.
2023-03-31 22:53:52 +08:00
new_user = User(email=email,
name=name,
password=generate_password_hash(password, method='sha256'),
role='user',
isActivated=False)
# first user is always admin
if not db.session.query(User).count():
new_user.role='admin'
new_user.isActivated=True
2023-03-31 22:11:34 +08:00
# add the new user to the database
db.session.add(new_user)
db.session.commit()
return redirect(url_for('auth.login'))
@auth.route('/logout')
def logout():
if current_user.is_authenticated:
logout_user()
return redirect(url_for('main.index'))