mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
84 lines
2.2 KiB
Python
84 lines
2.2 KiB
Python
from typing import Annotated
|
|
from datetime import datetime, timedelta
|
|
from fastapi import Depends, HTTPException, status, Request
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
|
|
from handler import dbh
|
|
from models.user import User
|
|
|
|
# to get a string like this run:
|
|
# openssl rand -hex 32
|
|
SECRET_KEY = "9b9da8bfd88822ad708530bb36e61d02c130a74de7a8e84d5f456bf6fee5c518"
|
|
ALGORITHM = "HS256"
|
|
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
def verify_password(plain_password, hashed_password):
|
|
return pwd_context.verify(plain_password, hashed_password)
|
|
|
|
|
|
def get_password_hash(password):
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def authenticate_user(username: str, password: str):
|
|
user = dbh.get_user(username)
|
|
if not user:
|
|
return False
|
|
|
|
if not verify_password(password, user.hashed_password):
|
|
return False
|
|
|
|
return user
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: timedelta | None = None):
|
|
to_encode = data.copy()
|
|
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(minutes=15)
|
|
|
|
to_encode.update({"exp": expire})
|
|
|
|
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
|
|
|
|
|
async def get_current_user(request: Request):
|
|
authentication_exception = HTTPException(
|
|
status_code=status.HTTP_302_FOUND,
|
|
detail="Not authenticated",
|
|
headers={"Location": "/login"},
|
|
)
|
|
|
|
token = request.cookies.get('access_token')
|
|
if token is None:
|
|
raise authentication_exception
|
|
|
|
try:
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
username: str = payload.get("sub")
|
|
if username is None:
|
|
raise authentication_exception
|
|
except JWTError:
|
|
raise authentication_exception
|
|
|
|
user = dbh.get_user(username)
|
|
if user is None:
|
|
raise authentication_exception
|
|
|
|
return user
|
|
|
|
|
|
async def get_current_active_user(
|
|
current_user: Annotated[User, Depends(get_current_user)]
|
|
):
|
|
if current_user.disabled:
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
|
|
|
return current_user
|