/ code snippets

Example of authentication using flask_login

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):

	def is_active(self):
		return True

	def is_anonymous(self):
		return False

	def get_id(self):
		return self.id

	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()
def load_user(user_id):
    return User.get(user_id)

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

def logout():
    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)
		if target_user is None:
			return "<html><p>failed</p></html>"
		return redirect("/")
	return """
	<form action="/login" method="post">
	<input type="text" name="username">
	<input type="password" name="password">
	<input type="submit" value="login">

def secret():
	return render_template("secrets.html")

if __name__ == "__main__":