fixed auth
This commit is contained in:
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user