imetting_backend/app/api/endpoints/auth.py

38 lines
1.3 KiB
Python

from fastapi import APIRouter, HTTPException
from app.models.models import LoginRequest, LoginResponse
from app.core.database import get_db_connection
import hashlib
import datetime
router = APIRouter()
def hash_password(password: str) -> str:
return hashlib.sha256(password.encode()).hexdigest()
@router.post("/auth/login", response_model=LoginResponse)
def login(request: LoginRequest):
with get_db_connection() as connection:
cursor = connection.cursor(dictionary=True)
query = "SELECT user_id, username, caption, email, password_hash FROM users WHERE username = %s"
cursor.execute(query, (request.username,))
user = cursor.fetchone()
if not user:
raise HTTPException(status_code=401, detail="用户名或密码错误")
hashed_input = hash_password(request.password)
if user['password_hash'] != hashed_input and user['password_hash'] != request.password:
raise HTTPException(status_code=401, detail="用户名或密码错误")
token = f"token_{user['user_id']}_{hash_password(str(datetime.datetime.now()))[:16]}"
return LoginResponse(
user_id=user['user_id'],
username=user['username'],
caption=user['caption'],
email=user['email'],
token=token
)