Spaces:
Sleeping
Sleeping
Download app/api/auth.py from sandy898/resonate-api: direct link, hf CLI and curl.
- Browser
- Download file 2.35 kB
-
https://huggingface.co/spaces/sandy898/resonate-api/resolve/main/app/api/auth.py
- Command line
-
hf download hf://spaces/sandy898/resonate-api/app/api/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/sandy898/resonate-api/resolve/main/app/api/auth.py
2.35 kB
| import uuid | |
| from datetime import timedelta | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy.future import select | |
| from pydantic import BaseModel | |
| from app.db.database import get_db | |
| from app.db.models import User | |
| from app.core.security import get_password_hash, verify_password, create_access_token | |
| from app.api.deps import get_current_user | |
| from app.core.config import settings | |
| router = APIRouter(prefix="/auth", tags=["auth"]) | |
| class UserCreate(BaseModel): | |
| email: str | |
| password: str | |
| class UserLogin(BaseModel): | |
| email: str | |
| password: str | |
| class UserResponse(BaseModel): | |
| id: str | |
| email: str | |
| username: str | |
| reputation_score: int | |
| class Config: | |
| from_attributes = True | |
| async def register(user_in: UserCreate, db: AsyncSession = Depends(get_db)): | |
| result = await db.execute(select(User).where(User.email == user_in.email)) | |
| if result.scalars().first(): | |
| raise HTTPException(status_code=400, detail="Email already registered") | |
| user_id = str(uuid.uuid4()) | |
| username = user_in.email.split("@")[0] + str(uuid.uuid4())[:4] | |
| new_user = User( | |
| id=user_id, | |
| email=user_in.email, | |
| username=username, | |
| hashed_password=get_password_hash(user_in.password) | |
| ) | |
| db.add(new_user) | |
| await db.commit() | |
| await db.refresh(new_user) | |
| return new_user | |
| async def login(user_in: UserLogin, db: AsyncSession = Depends(get_db)): | |
| result = await db.execute(select(User).where(User.email == user_in.email)) | |
| user = result.scalars().first() | |
| if not user or not verify_password(user_in.password, user.hashed_password): | |
| raise HTTPException(status_code=400, detail="Incorrect email or password") | |
| access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) | |
| access_token = create_access_token( | |
| data={"sub": user.id}, expires_delta=access_token_expires | |
| ) | |
| return {"access_token": access_token, "token_type": "bearer", "user": {"id": user.id, "email": user.email, "username": user.username}} | |
| async def get_me(current_user: User = Depends(get_current_user)): | |
| return current_user | |