forked from xzelencikova/ngo_naruc_project_be
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_middleware.py
More file actions
49 lines (41 loc) · 1.35 KB
/
Copy pathauth_middleware.py
File metadata and controls
49 lines (41 loc) · 1.35 KB
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
from functools import wraps
import jwt
from flask import request, abort
from flask import current_app
import models
from dotenv import load_dotenv
import os
from database import create_connection
load_dotenv()
conn = create_connection()
cursor = conn.cursor()
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if "X-API-KEY" in request.headers:
token = request.headers["X-API-KEY"]
if not token:
return {
"message": "Authentication Token is missing!",
"data": None,
"error": "Unauthorized"
}, 401
try:
data = jwt.decode(token, os.environ.get("SECRET_KEY"), algorithms=["HS256"])
cursor.execute("""SELECT * FROM users WHERE id={}""".format(data["sub"]))
current_user = cursor.fetchone()
if not current_user:
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(*args, **kwargs)
return decorated