Debian Codegraph @

examples/roles_auth.py

raw
1 #!/usr/bin/env python
2 """Basic authentication example
3
4 This example demonstrates how to protect Flask endpoints with basic
5 authentication, using secure hashed passwords.
6
7 After running this example, visit http://localhost:5000 in your browser. To
8 gain access, you can use (username=john, password=hello) or
9 (username=susan, password=bye).
10 """
11 from flask import Flask
12 from flask_httpauth import HTTPBasicAuth
13 from werkzeug.security import generate_password_hash, check_password_hash
14
15 app = Flask(__name__)
16 auth = HTTPBasicAuth()
17
18 users = {
19 "john": generate_password_hash("hello"),
20 "susan": generate_password_hash("bye"),
21 }
22
23 roles = {
24 "john": "user",
25 "susan": ["user", "admin"],
26 }
27
28
29 @auth.get_user_roles
30 def get_user_roles(username):
31 return roles.get(username)
32
33
34 @auth.verify_password
35 def verify_password(username, password):
36 if username in users and check_password_hash(
37 users.get(username), password):
38 return username
39
40
41 @app.route('/')
42 @auth.login_required(role='user')
43 def index():
44 return "Hello, {}!".format(auth.current_user())
45
46
47 @app.route('/admin')
48 @auth.login_required(role='admin')
49 def admin():
50 return "Hello {}, you are an admin!".format(auth.current_user())
51
52
53 if __name__ == '__main__':
54 app.run(debug=True, host='0.0.0.0')