Flask Basic HTTP Auth use login page
basic-authentication, flask, python
Solution
From the documentation, here: http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/. There is a sample decorator that does just this:
from functools import wraps
from flask import g, request, redirect, url_for
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
Just return the redirect instead of calling the authenticate() method as you do now.
Problem
I'm building a test app and used the instructions here (http://flask.pocoo.org/snippets/8/) to setup simple authentication. On pages where auth is required I get a popup saying "Authorization Required". Instead of that, I'd like to redirect to a login page where the user can put their user/pass in a form. Here's what I have currently (same as the snippet in the link): ``` from functools import wraps from flask import request, Response def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == 'admin' and password == 'secret' def authenticate(): """Sends a 401 response that enables basic auth""" return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated ``` It looks like I could use Flask-Auth, but I really only need the functionality that the above provides. Thanks, Ryan