Spaces:
Running
Running
| from fastapi import Depends, HTTPException, status, Security, Request | |
| from fastapi.security import APIKeyCookie | |
| from sqlalchemy.orm import Session | |
| from app.core.database import get_db | |
| from app.core.security import decode_access_token | |
| from app.models.user import User | |
| from typing import Generator, Optional | |
| import logging | |
| # Cookie authentication dependency | |
| oauth2_cookie = APIKeyCookie(name="access_token", auto_error=False) | |
| def get_current_user( | |
| request: Request, | |
| db: Session = Depends(get_db), | |
| cookie_token: Optional[str] = Depends(oauth2_cookie), | |
| ) -> User: | |
| """ | |
| Lấy token từ: | |
| 1. Cookie 'access_token' (khi FE & BE cùng origin hoặc HTTPS) | |
| 2. Authorization: Bearer <token> header (khi FE & BE khác port/origin) | |
| """ | |
| token: Optional[str] = cookie_token | |
| # Fallback: đọc từ Authorization header nếu không có cookie | |
| if not token: | |
| auth_header = request.headers.get("Authorization", "") | |
| if auth_header.startswith("Bearer "): | |
| token = auth_header[len("Bearer "):] | |
| if not token: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Chưa đăng nhập. Hãy đăng nhập để truy cập tài nguyên.", | |
| ) | |
| user_id = decode_access_token(token) | |
| if not user_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Phiên làm việc hết hạn hoặc token không hợp lệ.", | |
| ) | |
| user = db.query(User).filter(User.id == user_id).first() | |
| if not user: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Tài khoản không tồn tại.", | |
| ) | |
| return user | |