-
Notifications
You must be signed in to change notification settings - Fork 5
/
auth.py
108 lines (74 loc) · 2.42 KB
/
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from flask import Response, abort, jsonify, make_response
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
get_jwt_identity,
jwt_required,
set_access_cookies,
set_refresh_cookies,
unset_jwt_cookies,
)
from flask_restful import Resource, reqparse
from .database import UserModel
def unauthorized() -> Response:
"""
401 error handler.
:return: response.
:rtype: Response
"""
response = make_response(jsonify(msg="Unauthorized"), 401)
response.headers["WWW-Authenticate"] = 'Basic realm="Login Required"'
return response
def get_auth_parser() -> reqparse.RequestParser:
"""
Get request parser.
:return: request parser.
:rtype: reqparse.RequestParser
"""
parser = reqparse.RequestParser()
parser.add_argument(
"username", type=str, required=True, help="This field cannot be blank"
)
parser.add_argument(
"password", type=str, required=True, help="This field cannot be blank"
)
return parser
class UserLogin(Resource):
"""
User login API resource.
"""
def post(self) -> Response:
parser = get_auth_parser()
args = parser.parse_args()
current_user = UserModel.find_by_username(args["username"])
if not current_user:
abort(unauthorized())
if not UserModel.verify_hash(args["password"], current_user.password):
abort(unauthorized())
else:
access_token = create_access_token(identity=args["username"])
refresh_token = create_refresh_token(identity=args["username"])
response = jsonify(message="Logged in")
# set cookies
set_access_cookies(response, access_token)
set_refresh_cookies(response, refresh_token)
return response
class UserLogout(Resource):
"""
User logout API resource.
"""
def post(self) -> Response:
response = jsonify(message="Logged out")
unset_jwt_cookies(response)
return response
class TokenRefresh(Resource):
"""
Token refresh API resource.
"""
@jwt_required(refresh=True)
def post(self) -> Response:
current_user = get_jwt_identity()
access_token = create_access_token(identity=current_user)
response = jsonify(message="Access token has been refreshed")
set_access_cookies(response, access_token)
return response