-
Notifications
You must be signed in to change notification settings - Fork 72
/
demo_auth.py
executable file
·70 lines (53 loc) · 1.67 KB
/
demo_auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python3
#
# This application demonstrates how access control can be implemented for
# flask-restful API endpoints
# see also https://flask-restful.readthedocs.io/en/latest/extending.html#resource-method-decorators
#
import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from safrs import SAFRSBase, SAFRSAPI, jsonapi_rpc
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth
db = SQLAlchemy()
# Authentication with flask-httpauth
# https://flask-httpauth.readthedocs.io/en/latest/
auth = HTTPBasicAuth()
@auth.verify_password
def verify_password(username_or_token, password):
# Implement your authentication here
if username_or_token == "user" and password == "pass":
return True
return False
class User(SAFRSBase, db.Model):
"""
description: Protected user resource
"""
__tablename__ = "users"
id = db.Column(db.String(32), primary_key=True)
username = db.Column(db.String(32))
def start_app(app):
api = SAFRSAPI(app, host=HOST)
# The method_decorators will be applied to all API endpoints
api.expose_object(User, method_decorators=[auth.login_required])
user = User(username="admin2")
print(f"Starting API: http://{HOST}:{PORT}/api")
app.run(host=HOST, port=PORT)
#
# APP Initialization
#
app = Flask("demo_app")
app.config.update(
SQLALCHEMY_DATABASE_URI="sqlite:////tmp/demo2.sqlite",
SQLALCHEMY_TRACK_MODIFICATIONS=False,
SECRET_KEY=b"sdqfjqsdfqizroqnxwc",
DEBUG=True,
)
HOST = sys.argv[1] if len(sys.argv) > 1 else "0.0.0.0"
PORT = 5000
db.init_app(app)
# Start the application
with app.app_context():
db.create_all()
start_app(app)