-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathauthentication.py
92 lines (71 loc) · 2.62 KB
/
authentication.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
import re
from passlib.context import CryptContext
from fastapi import HTTPException, status
import jwt
from models import User
from config import get_settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def get_hashed_password(password):
return pwd_context.hash(password)
async def very_token(token: str):
'''verify token from login'''
try:
payload = jwt.decode(token, get_settings().SECRET,
algorithms=["HS256"])
user = await User.get(id=payload.get("id"))
except:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Token",
headers={"WWW-Authenticate": "Bearer"}
)
return await user
async def very_token_email(token: str):
'''verify token from email'''
try:
payload = jwt.decode(token, get_settings().SECRET,
algorithms=["HS256"])
user = await User.get(id=payload.get("id"), email=payload.get("email"))
except:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Token",
headers={"WWW-Authenticate": "Bearer"}
)
return await user
# bug: [email protected]:Trye ; [email protected]: False!!
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
def is_not_email(email):
"""if valid mail: return 'True' \n
** This is a simple way to do this and is not recommended for a real project ** """
if(re.search(regex, email)):
return False
else:
return True
async def verify_password(plain_password, database_hashed_password):
return pwd_context.verify(plain_password, database_hashed_password)
async def authenticate_user(username: str, password: str):
user = await User.get(username=username)
if user and verify_password(password, user.password):
if not user.is_verifide:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email not verifide",
headers={"WWW-Authenticate": "Bearer"}
)
return user
return False
async def token_generator(username: str, password: str):
user = await authenticate_user(username, password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Username or Password",
headers={"WWW-Authenticate": "Bearer"}
)
token_data = {
"id": user.id,
"username": user.username
}
token = jwt.encode(token_data, get_settings().SECRET, algorithm="HS256")
return token