Don't like ads? PRO users don't see any ads ;-)
Guest

authorization

By: a guest on Sep 17th, 2012  |  syntax: Python  |  size: 0.78 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. from functools import wraps
  2.  
  3. def check_auth(username, password):
  4.     return username == 'admin' and password == 'secret'
  5.  
  6. def authenticate():
  7.     message = {'message': "Authenticate."}
  8.     resp = jsonify(message)
  9.  
  10.     resp.status_code = 401
  11.     resp.headers['WWW-Authenticate'] = 'Basic realm="Example"'
  12.  
  13.     return resp
  14.  
  15. def requires_auth(f):
  16.     @wraps(f)
  17.     def decorated(*args, **kwargs):
  18.         auth = request.authorization
  19.         if not auth:
  20.             return authenticate()
  21.  
  22.         elif not check_auth(auth.username, auth.password):
  23.             return authenticate("Authentication Failed.")
  24.         return f(*args, **kwargs)
  25.  
  26.     return decorated
  27.  
  28. @app.route('/secrets')
  29. @requires_auth
  30. def api_hello():
  31.     return "Shhh this is top secret spy stuff!"