36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
from fastapi import HTTPException, Depends, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
import jwt
|
|
|
|
from app.core.config import settings
|
|
from app.db.database import get_connection
|
|
|
|
security = HTTPBearer()
|
|
|
|
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
|
token = credentials.credentials
|
|
try:
|
|
payload = jwt.decode(
|
|
token,
|
|
settings.secret_key,
|
|
algorithms=[settings.algorithm]
|
|
)
|
|
user_id = payload.get("sub")
|
|
if user_id is None:
|
|
raise HTTPException(status_code=401, detail="Invalid token")
|
|
|
|
conn = get_connection()
|
|
user = conn.execute(
|
|
"SELECT id, email, phone FROM users WHERE id = ?",
|
|
(user_id,)
|
|
).fetchone()
|
|
conn.close()
|
|
|
|
if user is None:
|
|
raise HTTPException(status_code=401, detail="User not found")
|
|
|
|
return dict(user)
|
|
except jwt.ExpiredSignatureError:
|
|
raise HTTPException(status_code=401, detail="Token expired")
|
|
except jwt.InvalidTokenError:
|
|
raise HTTPException(status_code=401, detail="Invalid token") |