fixed auth

This commit is contained in:
2026-09-08 10:41:23 +03:00
parent 618081bc84
commit c94a6e2329
2 changed files with 10 additions and 6 deletions
+9 -5
View File
@@ -3,10 +3,10 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import Any
import bcrypt
import jwt
from fastapi import Depends, HTTPException, Security, status
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer
from passlib.context import CryptContext
from sqlalchemy import select
from sqlalchemy.orm import Session
@@ -15,16 +15,21 @@ from app.core.database import get_db
_bearer = HTTPBearer(auto_error=False)
_api_key = APIKeyHeader(name="X-API-Token", auto_error=False)
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
def _password_bytes(password: str) -> bytes:
# bcrypt limit is 72 bytes; truncate UTF-8 safely for hashing
raw = password.encode("utf-8")
return raw[:72]
def hash_password(password: str) -> str:
return _pwd.hash(password)
return bcrypt.hashpw(_password_bytes(password), bcrypt.gensalt()).decode("ascii")
def verify_password(password: str, password_hash: str) -> bool:
try:
return _pwd.verify(password, password_hash)
return bcrypt.checkpw(_password_bytes(password), password_hash.encode("ascii"))
except Exception:
return False
@@ -81,7 +86,6 @@ def require_auth(
uid = int(payload.get("uid") or 0)
user = db.scalar(select(User).where(User.id == uid)) if uid else None
if not user or user.username != username:
# allow token if user renamed but id matches username in DB
user = db.scalar(select(User).where(User.username == username))
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
+1 -1
View File
@@ -11,7 +11,7 @@ openpyxl==3.1.5
reportlab==4.2.5
alembic==1.14.0
PyJWT==2.10.1
passlib[bcrypt]==1.7.4
bcrypt==4.2.1
docxtpl==0.20.2
jinja2==3.1.3
openai>=1.0.0