generated from nighthawkcoders/flask_portfolio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_middleware.py
35 lines (32 loc) · 1.06 KB
/
auth_middleware.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
from functools import wraps
import jwt
from flask import request, abort
from flask import current_app
from model.users import User
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.cookies.get("jwt")
if not token:
return {
"message": "Authentication Token is missing!",
"data": None,
"error": "Unauthorized"
}, 401
try:
data=jwt.decode(token, current_app.config["SECRET_KEY"], algorithms=["HS256"])
current_user=User.query.filter_by(_uid=data["_uid"]).first()
if current_user is None:
return {
"message": "Invalid Authentication token!",
"data": None,
"error": "Unauthorized"
}, 401
except Exception as e:
return {
"message": "Something went wrong",
"data": None,
"error": str(e)
}, 500
return f(current_user, *args, **kwargs)
return decorated