Skip to content

Instantly share code, notes, and snippets.

@fabiocerqueira
Last active October 15, 2019 19:35
Show Gist options
  • Save fabiocerqueira/d43f0f869df1de68c9de34e58ddeaa78 to your computer and use it in GitHub Desktop.
Save fabiocerqueira/d43f0f869df1de68c9de34e58ddeaa78 to your computer and use it in GitHub Desktop.
Flask exemplo simples de autenticacao
from functools import wraps
from flask import Flask, escape, request, make_response
app = Flask(__name__)
USERS = {"fabio": "12345", "italo": "abcde"}
def login_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
auth = request.authorization
unauthorized_response = make_response(
"unauthorized",
401,
{"WWW-Authenticate": 'Basic realm="Faz login ai doido!"'},
)
if auth is None:
return unauthorized_response
username = request.authorization.username
if username not in USERS:
return unauthorized_response
password = request.authorization.password
if USERS[username] != password:
return unauthorized_response
request.username = username
return func(*args, **kwargs)
return wrapper
@app.route("/")
def index():
return "Index, auth is not needed here! :D"
@app.route("/admin")
@login_required
def admin():
return f"Admin, thanks, you are logged in, {escape(request.username)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment