Created
January 25, 2016 07:24
-
-
Save binderclip/3966920ab065571b66ef to your computer and use it in GitHub Desktop.
basic auth demo - with flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from functools import wraps | |
from flask import request, Response, Flask | |
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 | |
app = Flask(__name__) | |
@app.route('/secret-page') | |
@requires_auth | |
def secret_page(): | |
return 'secret_page' | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment