first commit
This commit is contained in:
commit
6e354ba041
109 changed files with 12110 additions and 0 deletions
1
backend/app/utils/__init__.py
Normal file
1
backend/app/utils/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
|
||||
46
backend/app/utils/security.py
Normal file
46
backend/app/utils/security.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import bcrypt
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from app.config import settings
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
|
||||
|
||||
|
||||
def create_access_token(subject: str, expires_delta: timedelta | None = None) -> str:
|
||||
expire = datetime.now(UTC) + (
|
||||
expires_delta or timedelta(minutes=settings.access_token_expire_minutes)
|
||||
)
|
||||
payload = {"sub": subject, "exp": expire, "type": "access"}
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def create_refresh_token(subject: str) -> str:
|
||||
expire = datetime.now(UTC) + timedelta(days=settings.refresh_token_expire_days)
|
||||
payload = {"sub": subject, "exp": expire, "type": "refresh"}
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> dict[str, Any]:
|
||||
return jwt.decode(token, settings.secret_key, algorithms=[ALGORITHM])
|
||||
|
||||
|
||||
def verify_token(token: str, expected_type: str = "access") -> str | None:
|
||||
try:
|
||||
payload = decode_token(token)
|
||||
if payload.get("type") != expected_type:
|
||||
return None
|
||||
subject = payload.get("sub")
|
||||
return subject if isinstance(subject, str) else None
|
||||
except JWTError:
|
||||
return None
|
||||
Loading…
Add table
Add a link
Reference in a new issue