You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
"""Authentication routes"""
|
|
|
|
from flask import Blueprint, render_template, session, redirect, url_for
|
|
|
|
from app import db
|
|
from app.models import User
|
|
from app.forms import RegisterForm, LoginForm
|
|
|
|
auth_bp = Blueprint('auth', __name__)
|
|
|
|
|
|
@auth_bp.route('/auth/register', methods=['GET', 'POST'])
|
|
def register():
|
|
"""Register a new user"""
|
|
# validate form
|
|
form = RegisterForm()
|
|
if not form.validate_on_submit():
|
|
return render_template('auth/register.html', form=form)
|
|
# create user
|
|
user = User()
|
|
form.populate_obj(user)
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
# set session
|
|
session['auth'] = user.id
|
|
return redirect(url_for('index'))
|
|
|
|
@auth_bp.route('/auth/login', methods=['GET', 'POST'])
|
|
def login():
|
|
"""Login a user"""
|
|
# validate form
|
|
form = LoginForm()
|
|
if not form.validate_on_submit():
|
|
return render_template('auth/login.html', form=form)
|
|
# fetch user
|
|
user = User.query.filter_by(name=form.name.data).first()
|
|
# authenticate
|
|
if not (user and user.authenticate(form.password.data)):
|
|
return render_template('auth/login.html')
|
|
# set session
|
|
session['auth'] = user.id
|
|
return redirect(url_for('index'))
|
|
|
|
@auth_bp.route('/auth/logout')
|
|
def logout():
|
|
"""Log out by clearing the session"""
|
|
session.clear()
|
|
return redirect(url_for('index'))
|