Guest User

Untitled

a guest
Nov 5th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. import secrets
  2. from typing import Union
  3.  
  4. from flask import Flask, Blueprint, Response, request
  5.  
  6.  
  7. class BasicAuth:
  8. def __init__(self, app: Union[Flask, Blueprint], username: str, password: str):
  9. self.app = app
  10. self.username = username
  11. self.password = password
  12.  
  13. self.app.before_request(self._before_request)
  14.  
  15. def _check_auth(self, username, password):
  16. return secrets.compare_digest(username, self.username) and secrets.compare_digest(password, self.password)
  17.  
  18. def _authenticate(self):
  19. return Response(
  20. 'Could not verify your access level for that URL.\n'
  21. 'You have to login with proper credentials', 401,
  22. {'WWW-Authenticate': 'Basic realm="Login Required"'})
  23.  
  24. def _before_request(self):
  25. auth = request.authorization
  26. if not auth or not self._check_auth(auth.username, auth.password):
  27. return self._authenticate()
  28. return
Add Comment
Please, Sign In to add comment