-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthentication.py
67 lines (44 loc) · 1.76 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
from passlib.context import CryptContext
import jwt
from dotenv import dotenv_values
from models import (User, Business, Product, user_pydantic, user_pydanticIn,
product_pydantic,product_pydanticIn, business_pydantic,
business_pydanticIn)
from fastapi.exceptions import HTTPException
from fastapi import (FastAPI, Depends, HTTPException, status)
config_credentials = dict(dotenv_values(".env"))
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def get_password_hash(password):
return pwd_context.hash(password)
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
async def authenticate_user(username: str, password: str):
user = await User.get(username = username)
if user and verify_password(password, user.password):
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, config_credentials["SECRET"])
return token
async def verify_token(token: str):
try:
payload = jwt.decode(token, config_credentials['SECRET'], algorithm='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 user