Download fastapi-backend/app/services/auth.py from APIMoral/README: direct link, hf CLI and curl.
- Browser
- Download file 2.27 kB
-
https://huggingface.co/spaces/APIMoral/README/resolve/main/fastapi-backend/app/services/auth.py
- Command line
-
hf download hf://spaces/APIMoral/README/fastapi-backend/app/services/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/APIMoral/README/resolve/main/fastapi-backend/app/services/auth.py
2.27 kB
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import OAuth2PasswordBearer | |
| from app.database import get_db | |
| from app.models.user import User | |
| from app.schemas.user import UserCreate, UserResponse | |
| from app.core.security import verify_password, get_password_hash, decode_token | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login") | |
| async def create_user(db: AsyncSession, user_data: UserCreate) -> User: | |
| # Check if email exists | |
| result = await db.execute(select(User).where(User.email == user_data.email)) | |
| existing_user = result.scalar_one_or_none() | |
| if existing_user: | |
| return None | |
| # Create new user | |
| hashed_password = get_password_hash(user_data.password) | |
| new_user = User( | |
| email=user_data.email, | |
| hashed_password=hashed_password | |
| ) | |
| db.add(new_user) | |
| await db.flush() | |
| await db.refresh(new_user) | |
| return new_user | |
| async def authenticate_user(db: AsyncSession, email: str, password: str) -> User: | |
| result = await db.execute(select(User).where(User.email == email)) | |
| user = result.scalar_one_or_none() | |
| if not user: | |
| return None | |
| if not verify_password(password, user.hashed_password): | |
| return None | |
| return user | |
| async def get_current_user( | |
| token: str = Depends(oauth2_scheme), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> UserResponse: | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| payload = decode_token(token) | |
| if payload is None: | |
| raise credentials_exception | |
| email: str = payload.get("sub") | |
| if email is None: | |
| raise credentials_exception | |
| result = await db.execute(select(User).where(User.email == email)) | |
| user = result.scalar_one_or_none() | |
| if user is None: | |
| raise credentials_exception | |
| if not user.is_active: | |
| raise HTTPException(status_code=400, detail="Inactive user") | |
| return UserResponse( | |
| id=user.id, | |
| email=user.email, | |
| is_active=user.is_active, | |
| created_at=user.created_at | |
| ) | |