Skip to content

Instantly share code, notes, and snippets.

@eruvanos
Created November 5, 2018 09:13
Show Gist options
  • Save eruvanos/968433a9319910f1084dbada4c6fbf35 to your computer and use it in GitHub Desktop.
Save eruvanos/968433a9319910f1084dbada4c6fbf35 to your computer and use it in GitHub Desktop.
Flask BasicAuth Extension
import secrets
from typing import Union
from flask import Flask, Blueprint, Response, request
class BasicAuth:
def __init__(self, app: Union[Flask, Blueprint], username: str, password: str):
self.app = app
self.username = username
self.password = password
self.app.before_request(self._before_request)
def _check_auth(self, username, password):
return secrets.compare_digest(username, self.username) and secrets.compare_digest(password, self.password)
def _authenticate(self):
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 _before_request(self):
auth = request.authorization
if not auth or not self._check_auth(auth.username, auth.password):
return self._authenticate()
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment