from flask import render_template, flash, redirect, url_for from flask_login import login_user, logout_user, current_user, login_required from app import db from app.auth import bp from app.models import Player from app.auth.forms import LoginForm, RegistrationForm @bp.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = LoginForm() if form.validate_on_submit(): player = Player.query.filter_by(name=form.username.data).first() if player is None or not player.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('auth.login')) login_user(player, remember=form.remember_me.data) return redirect(url_for('main.index')) return render_template('auth/login.html', title='Sign In', form=form) @bp.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('main.index')) @bp.route('/register', methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = RegistrationForm() if form.validate_on_submit(): player = Player(name=form.username.data) player.set_password(form.password.data) player.set_auth_hash() db.session.add(player) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('auth.login')) return render_template('auth/register.html', title='Register', form=form)