/
cbv.py
66 lines (42 loc) · 1.61 KB
/
cbv.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
from sanic import Sanic
from sanic_jwt import exceptions
from sanic_jwt import initialize
from sanic.response import json
from sanic_jwt.decorators import protected
from sanic.views import HTTPMethodView
class User:
def __init__(self, id, username, password):
self.user_id = id
self.username = username
self.password = password
def __str__(self):
return "User(id='%s')" % self.id
def to_dict(self):
return {"user_id": self.user_id}
users = [User(1, "user1", "abcxyz"), User(2, "user2", "abcxyz")]
username_table = {u.username: u for u in users}
userid_table = {u.user_id: u for u in users}
async def authenticate(request, *args, **kwargs):
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username or not password:
raise exceptions.AuthenticationFailed("Missing username or password.")
user = username_table.get(username, None)
if user is None:
raise exceptions.AuthenticationFailed("User not found.")
if password != user.password:
raise exceptions.AuthenticationFailed("Password is incorrect.")
return user
app = Sanic()
initialize(app, authenticate=authenticate)
class PublicView(HTTPMethodView):
def get(self, request):
return json({"hello": "world"})
class ProtectedView(HTTPMethodView):
decorators = [protected()]
async def get(self, request):
return json({"protected": True})
app.add_route(PublicView.as_view(), "/")
app.add_route(ProtectedView.as_view(), "/protected")
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8888)