Skip to content

Instantly share code, notes, and snippets.

@gustavonovaes
Created October 8, 2017 20:25
Show Gist options
  • Save gustavonovaes/2f1399a7e8755b4c828f3a98f201f794 to your computer and use it in GitHub Desktop.
Save gustavonovaes/2f1399a7e8755b4c828f3a98f201f794 to your computer and use it in GitHub Desktop.
Flask Auth Basic
from functools import wraps
from flask import Flask, Response, request
from flask_babel import Babel
app = Flask(__name__)
babel = Babel(app)
app.config.from_object('config')
def check_auth(username, password):
return username == 'admin' and password == 'secret'
def authenticate():
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.route('/admin', methods=['GET', 'POST'])
@requires_auth
def admin():
return 'admin'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment