Example of authentication using flask_login

Posted on Jul 17, 2017

This is a very simple example of flask authentication. I couldn't find a complete example in the documentation (at the time), so I'm posting this for future reference.

Improved code and comments coming soon.

from Flask import Flask
from flask import request
from flask import redirect
from flask import render_template
import flask_login

class User(object):
    """
    The user class represents an ORM object one my use with sqlalchemy or
    similar. Here it's just using a dictionary to hold account information.
    """
    user_storage = {
        1: {'username': 'brahm', 'password': 'password'},
        1: {'username': 'noah', 'password': 'apples'}
    }
    def __init__(self, username, password, userid):
        self.username = username
        self.password = password
        self.id = userid

    def is_authenticated(self):
        pass

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return self.id

    @classmethod
    def get(cls, userid):
        username = cls.user_storage[user_id]['username']
        password = cls.user_storage[user_id]['password']
        user_id = userid
        return cls(username, password, userid)

app = Flask(__name__)
app.secret_key = "super secret key"

login_manager = flask_login.LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

@app.route("/")
def default():
    return """
    <html>
    <a href="/login">Login page</a>
    <a href="/logout">Logout page</a>
    <a href="/secret">Secret page</a>
    """

@app.route("/logout")
@flask_login.login_required
def logout():
    flask_login.logout_user()
    return redirect("/")

@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        print request.form['username']
        print request.form['password']
        target_user = None
        for i in USERS:
            if USERS[i]['u'] == request.form['username'] and USERS[i]['p'] == request.form['password']:
                print "valid!"
                target_user = User.get(i)
                break
        if target_user is None:
            return "<html><p>failed</p></html>"
        flask_login.login_user(target_user)
        return redirect("/")
    return """
    <html>
    <form action="/login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="login">
    </form>
    </html>"""

@app.route("/secret")
@flask_login.login_required
def secret():
    return render_template("secrets.html")

if __name__ == "__main__":
    app.run("0.0.0.0:8000")