formaptix-server/routes/utils.py

52 lines
1.6 KiB
Python
Raw Permalink Normal View History

2024-08-10 17:01:34 +03:00
from typing import Annotated
import hashlib
import jwt
from fastapi import Depends, HTTPException, Header
from sqlalchemy import select
from models import settings
import database
def hash_password(password: str, salt: str) -> str:
return hashlib.sha512((password + salt).encode("utf-8")).hexdigest()
def verify_admin(password: Annotated[str, Header(alias="x-token")]):
2024-09-22 11:34:48 +03:00
if password.strip() != settings.ADMIN_PASSWORD:
2024-08-10 17:01:34 +03:00
raise HTTPException(401, "Unauthorized")
return True
async def verify_user(token: Annotated[str, Header(alias="x-token")]) -> database.User:
try:
data = jwt.decode(
token, algorithms=["HS256"], options={"verify_signature": False}
)
except jwt.exceptions.DecodeError:
raise HTTPException(401, "Invalid token")
if "sub" not in data and not isinstance(data["sub"], int):
raise HTTPException(401, "Invalid token")
async with database.sessions.begin() as session:
stmt = select(database.User).where(database.User.id == data.get("sub"))
db_request = await session.execute(stmt)
user = db_request.scalar_one_or_none()
if user is None:
raise HTTPException(401, "Invalid token")
try:
2024-09-22 11:34:48 +03:00
jwt.decode(token, settings.SECRET + user.password, algorithms=["HS256"])
2024-08-10 17:01:34 +03:00
except jwt.exceptions.InvalidSignatureError:
raise HTTPException(401, "Invalid token")
2024-08-12 16:57:40 +03:00
session.expunge(user)
2024-08-10 17:01:34 +03:00
return user
User = Annotated[database.User, Depends(verify_user, use_cache=False)]
Admin = Annotated[bool, Depends(verify_admin, use_cache=False)]