Created
November 5, 2018 09:13
-
-
Save eruvanos/968433a9319910f1084dbada4c6fbf35 to your computer and use it in GitHub Desktop.
Flask BasicAuth Extension
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
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