Newer
Older
from flask import abort, Flask, redirect, request, render_template, url_for
from wtforms import SubmitField, StringField, PasswordField
from flask_login import login_user, logout_user, LoginManager, login_required, current_user
from db import User
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
@login_manager.user_loader
def user_loader(username):
user = User(username)
if not user.active:
return
return user
class LogoutForm(FlaskForm):
logout = SubmitField("logout")
class LoginForm(FlaskForm):
username = StringField("username")
password = PasswordField("password")
submit = SubmitField("Sign in")
logout_form = LogoutForm()
if request.method == "GET":
hydra = HydraAdmin(HYDRA_ADMIN_URL)
challenge = request.args.get("login_challenge")
if not challenge:
return render_template('home.html', email=current_user.email, logout_form=logout_form)
else:
login_request = hydra.login_request(challenge)
redirect_to = login_request.accept(current_user.email)
return redirect(redirect_to)
@app.route('/login', methods=['GET', 'POST'])
def login():
login_form = LoginForm()
if login_form.validate_on_submit():
login_user(user)
next_url = request.args.get('next')
if not is_safe_url(next):
return abort(400)
return redirect(next_url or url_for('home'))
return render_template('login.html', login_form=login_form)
def is_safe_url(url):
#TODO implement this
return True
@app.route('/logout', methods=['POST'])
def logout():
if request.method == "POST":
logout_form = LogoutForm()
if logout_form.validate():
logout_user()
return redirect(url_for('home'))