forked from Crafty-Coders/MIREA-hack-10-22-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin_auth.py
61 lines (50 loc) · 1.94 KB
/
admin_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
import datetime
import random
from db import AdminLogin, AdminSession
def generate_token():
return "".join([chr(random.randint(97, 122)) if random.randint(0, 2) else str(random.randint(0, 9)) for _ in range(40)])
def admin_login(login="", password="", refresh_token=""):
if password and login:
return admin_session_start(login, password)
if refresh_token:
return admin_session_refresh(refresh_token)
return {
"status": 401,
"message": "Invalid credentials"
}
def admin_session_start(login, password):
print("login")
for admin in AdminLogin.select().where(AdminLogin.login == login and AdminLogin.password == password):
admin_id = admin.id
access_token, refresh_token = generate_token(), generate_token()
AdminSession.insert(access_token=access_token,
refresh_token=refresh_token,
admin_id=admin_id,
start_time=datetime.datetime.now()).execute()
return {
"status": 200,
"access_token": access_token,
"refresh_token": refresh_token,
"message": "OK"
}
return {
"status": 404,
"message": "Admin not found"
}
def admin_session_refresh(refresh_token):
print("refresh")
if len(AdminSession.select().where(AdminSession.refresh_token == refresh_token)):
access_token, new_refresh_token = generate_token(), generate_token()
AdminSession.update(access_token=access_token,
refresh_token=new_refresh_token,
start_time=datetime.datetime.now()).where(AdminSession.refresh_token == refresh_token).execute()
return {
"status": 200,
"access_token": access_token,
"refresh_token": new_refresh_token,
"message": "OK"
}
return {
"status": 404,
"message": "Session not found"
}