Spaces:
Paused
Paused
Update app/services/auth_service.py
Browse files- app/services/auth_service.py +124 -122
app/services/auth_service.py
CHANGED
|
@@ -1,123 +1,125 @@
|
|
| 1 |
-
from datetime import datetime, timedelta
|
| 2 |
-
from typing import Optional
|
| 3 |
-
from fastapi import Depends, HTTPException, status
|
| 4 |
-
from fastapi.security import OAuth2PasswordBearer
|
| 5 |
-
from jose import JWTError, jwt
|
| 6 |
-
from passlib.context import CryptContext
|
| 7 |
-
from ..models.auth import UserProfile, LoginResponse
|
| 8 |
-
from ..core.config import settings
|
| 9 |
-
from ..db.crud import get_user_by_email
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
to_encode.
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
to_encode.
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
)
|
|
|
|
| 1 |
+
from datetime import datetime, timedelta
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from fastapi import Depends, HTTPException, status
|
| 4 |
+
from fastapi.security import OAuth2PasswordBearer
|
| 5 |
+
from jose import JWTError, jwt
|
| 6 |
+
from passlib.context import CryptContext
|
| 7 |
+
from ..models.auth import UserProfile, LoginResponse
|
| 8 |
+
from ..core.config import settings
|
| 9 |
+
from ..db.crud import get_user_by_email
|
| 10 |
+
from ..db.database import get_db
|
| 11 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
+
|
| 13 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 14 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")
|
| 15 |
+
|
| 16 |
+
async def authenticate_user(email: str, password: str, db: AsyncSession = Depends(get_db)) -> Optional[UserProfile]:
|
| 17 |
+
"""Authenticate a user and return their profile if credentials are valid."""
|
| 18 |
+
user = await get_user_by_email(db, email)
|
| 19 |
+
if not user or not verify_password(password, user.hashed_password):
|
| 20 |
+
return None
|
| 21 |
+
return UserProfile(
|
| 22 |
+
id=user.id,
|
| 23 |
+
email=user.email,
|
| 24 |
+
full_name=user.full_name,
|
| 25 |
+
role=user.role
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
| 29 |
+
"""Verify a password against its hash."""
|
| 30 |
+
return pwd_context.verify(plain_password, hashed_password)
|
| 31 |
+
|
| 32 |
+
def get_password_hash(password: str) -> str:
|
| 33 |
+
"""Generate password hash."""
|
| 34 |
+
return pwd_context.hash(password)
|
| 35 |
+
|
| 36 |
+
def create_access_token(data: dict) -> str:
|
| 37 |
+
"""Create a JWT access token."""
|
| 38 |
+
to_encode = data.copy()
|
| 39 |
+
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 40 |
+
to_encode.update({"exp": expire})
|
| 41 |
+
encoded_jwt = jwt.encode(
|
| 42 |
+
to_encode,
|
| 43 |
+
settings.SECRET_KEY,
|
| 44 |
+
algorithm=settings.ALGORITHM
|
| 45 |
+
)
|
| 46 |
+
return encoded_jwt
|
| 47 |
+
|
| 48 |
+
def create_refresh_token(data: dict) -> str:
|
| 49 |
+
"""Create a JWT refresh token."""
|
| 50 |
+
to_encode = data.copy()
|
| 51 |
+
expire = datetime.utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
|
| 52 |
+
to_encode.update({"exp": expire, "refresh": True})
|
| 53 |
+
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
| 54 |
+
|
| 55 |
+
async def refresh_access_token(refresh_token: str) -> LoginResponse:
|
| 56 |
+
"""Create new access token using refresh token."""
|
| 57 |
+
try:
|
| 58 |
+
payload = jwt.decode(
|
| 59 |
+
refresh_token,
|
| 60 |
+
settings.SECRET_KEY,
|
| 61 |
+
algorithms=[settings.ALGORITHM]
|
| 62 |
+
)
|
| 63 |
+
if not payload.get("refresh"):
|
| 64 |
+
raise HTTPException(
|
| 65 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 66 |
+
detail="Invalid refresh token"
|
| 67 |
+
)
|
| 68 |
+
email: str = payload.get("sub")
|
| 69 |
+
if email is None:
|
| 70 |
+
raise HTTPException(
|
| 71 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 72 |
+
detail="Invalid refresh token"
|
| 73 |
+
)
|
| 74 |
+
user = await get_user_by_email(email)
|
| 75 |
+
if not user:
|
| 76 |
+
raise HTTPException(
|
| 77 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 78 |
+
detail="User not found"
|
| 79 |
+
)
|
| 80 |
+
access_token = create_access_token({"sub": user.email})
|
| 81 |
+
return LoginResponse(
|
| 82 |
+
access_token=access_token,
|
| 83 |
+
token_type="bearer",
|
| 84 |
+
user=UserProfile(
|
| 85 |
+
id=user.id,
|
| 86 |
+
email=user.email,
|
| 87 |
+
full_name=user.full_name,
|
| 88 |
+
role=user.role
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
except JWTError:
|
| 92 |
+
raise HTTPException(
|
| 93 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 94 |
+
detail="Invalid refresh token"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
async def get_current_user(token: str = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db)) -> UserProfile:
|
| 98 |
+
"""Get the current authenticated user from JWT token."""
|
| 99 |
+
credentials_exception = HTTPException(
|
| 100 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 101 |
+
detail="Could not validate credentials",
|
| 102 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 103 |
+
)
|
| 104 |
+
try:
|
| 105 |
+
payload = jwt.decode(
|
| 106 |
+
token,
|
| 107 |
+
settings.SECRET_KEY,
|
| 108 |
+
algorithms=[settings.ALGORITHM]
|
| 109 |
+
)
|
| 110 |
+
email: str = payload.get("sub")
|
| 111 |
+
if email is None:
|
| 112 |
+
raise credentials_exception
|
| 113 |
+
except JWTError:
|
| 114 |
+
raise credentials_exception
|
| 115 |
+
|
| 116 |
+
user = await get_user_by_email(db, email)
|
| 117 |
+
if user is None:
|
| 118 |
+
raise credentials_exception
|
| 119 |
+
|
| 120 |
+
return UserProfile(
|
| 121 |
+
id=user.id,
|
| 122 |
+
email=user.email,
|
| 123 |
+
full_name=user.full_name,
|
| 124 |
+
role=user.role
|
| 125 |
)
|