-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthentication.py
65 lines (51 loc) · 1.69 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
from passlib.context import CryptContext
import jwt
from dotenv import dotenv_values
from models import User
from fastapi import HTTPException
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
from dotenv import dotenv_values
config_crdentials = dotenv_values(".env")
async def get_hash_password(password: str):
"""
Hashes a password using bcrypt.
Args:
password (str): The password to hash.
Returns:
str: The hashed password.
"""
return pwd_context.hash(password)
async def verify_token(token: str):
try:
payload = jwt.decode(token, config_crdentials["SECRET"], algorithms=["HS256"])
user_id = payload["id"]
user = await User.get(id=user_id)
await user.save()
return user
except jwt.exceptions.InvalidTokenError as exc:
raise HTTPException(
status_code=401,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"},
) from exc
async def authenticate_user(username: str, password: str):
user = await User.get(username=username)
if not user:
return False
if not pwd_context.verify(password, user.password):
return False
return user
async def token_generator(username: str, password: str):
user = await authenticate_user(username, password)
if not user:
raise HTTPException(
status_code=401,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Bearer"},
)
token_payload = {
"id": user.id,
"username": username,
# "password": password,
}
return jwt.encode(token_payload, config_crdentials["SECRET"], algorithm="HS256")