Skip to content
Snippets Groups Projects
app.py 2.15 KiB
Newer Older
from flask import abort, Flask, redirect, request, render_template, url_for
Mark's avatar
Mark committed
from os import urandom, environ
Mark's avatar
Mark committed
from hydra_client import HydraAdmin
from wtforms import SubmitField, StringField, PasswordField
Mark's avatar
Mark committed
from flask_wtf import FlaskForm
Mark's avatar
Mark committed
from flask_login import login_user, logout_user, LoginManager, login_required, current_user
from db import User
Mark's avatar
Mark committed

HYDRA_ADMIN_URL = environ['HYDRA_ADMIN_URL']
Mark's avatar
Mark committed

app = Flask(__name__)
Mark's avatar
Mark committed
app.config['SECRET_KEY'] = urandom(16)
Mark's avatar
Mark committed

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
Mark's avatar
Mark committed

Mark's avatar
Mark committed
class LogoutForm(FlaskForm):
    logout = SubmitField("logout")

class LoginForm(FlaskForm):
    username = StringField("username")
    password = PasswordField("password")
    submit = SubmitField("Sign in")
Mark's avatar
Mark committed

@app.route('/')
@login_required
def home():
Mark's avatar
Mark committed
    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():
Mark's avatar
Mark committed
        user = User(login_form.username.data)
Mark's avatar
Mark committed
        if user.active and user.verify_password(login_form.password.data):
            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


Mark's avatar
Mark committed
@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'))