-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.py
79 lines (69 loc) · 2.39 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
from utils import message
from Crypto.Cipher import AES
import json
import datetime
def authorize(request, APP_SECRET, NONCE, users_collection):
## Check if token and tag are present in request
if 'token' not in request.headers or 'tag' not in request.headers:
return {
'error': True,
'code': 401,
'message': 'Token or tag not provided',
'err': 'Unauthorized'
}
token = request.headers['token']
tag = request.headers['tag']
key = APP_SECRET.encode('utf-8')
## Creating the cypher object
cipher = AES.new(key, AES.MODE_EAX, nonce=NONCE.encode('utf-8'))
## Decrypting the token
data = cipher.decrypt(bytes.fromhex(token))
## Converting the decrypted token to a python object
data_object = json.loads(data.decode('utf-8'))
## Checking if the decrypted token has the required fields
if 'username' not in data_object or 'expiry' not in data_object:
return {
'error': True,
'code': 401,
'message': 'Invalid token',
'err': 'Unauthorized'
}
## Checking if the token has expired
if data_object['expiry'] < datetime.datetime.timestamp(datetime.datetime.now()):
return {
'error': True,
'code': 401,
'message': 'Token expired',
'err': 'Unauthorized'
}
try:
## Verifying the integrity of the tag
cipher.verify(bytes.fromhex(tag))
## Checking if the user exists in the database
cursor = users_collection.find({"username": data_object['username']})
users = list(cursor)
if len(users) == 0:
## If the user does not exist, return error
return {
'error': True,
'code': 401,
'message': 'Invalid Credentials',
'err': 'Unauthorized'
}
else:
## If the user exists, return the user object
return {
'error': False,
'code': 200,
'message': 'Valid Token',
'username': data_object['username'],
'licenseID': users[0]['licenseID']
}
except:
## If the tag is invalid, return error
return {
'error': True,
'code': 401,
'message': 'Invalid Token',
'err': 'Unauthorized'
}