Guest User

Untitled

a guest
Nov 24th, 2018
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. from functools import wraps
  2. from werkzeug import check_password
  3. # A bunch of your Flask app's code here
  4. # . . .
  5.  
  6. proxy_user = None
  7.  
  8. def check_auth(user_id, user_pass):
  9. """
  10. Checks database via SQLAlchemy to check if credentials
  11. are valid. If valid, returns a tuple containing (True,
  12. User). Otherwise, returns tuple (False, None).
  13. """
  14. try:
  15. user_id = int(user_id)
  16. user_pass = str(user_pass)
  17. except:
  18. return False, None
  19. loaded_user = User.query.filter_by(id=user_id).first()
  20. if loaded_user is None:
  21. return False, None
  22. # Assuming you use werkzeug to hash your passwords
  23. ret_boolean = check_password(str(loaded_user.pwdhash), user_pass)
  24. return ret_boolean, loaded_user
  25.  
  26. def requires_auth(f):
  27. """
  28. Decorator for methods to enforce authorization before
  29. proceding to the wrapped function. Sets a global
  30. proxy_user object to the current authorized user.
  31. """
  32. # Wrapped function has access to proxy_user
  33. @wraps(f)
  34. def decorated(*args, **kwargs):
  35. global proxy_user #declaration required to look up to global scope
  36. auth = request.authorization
  37. if not auth:
  38. return needAuthentication()
  39. authenticated, proxy_user = check_auth(auth.username, auth.password)
  40. if not authenticated:
  41. return needAuthentication(msg='Authentication failed.')
  42. return f(*args, **kwargs)
  43. return decorated
  44.  
  45. @app.route("/greet")
  46. @requires_auth
  47. def greet():
  48. global proxy_user
  49. return "Hello, %r" % proxy_user.name
Add Comment
Please, Sign In to add comment