Spaces:
Sleeping
Sleeping
Download app/api/auth.py from bhaimavi353/Todo: direct link, hf CLI and curl.
- Browser
- Download file 3.62 kB
-
https://huggingface.co/spaces/bhaimavi353/Todo/resolve/main/app/api/auth.py
- Command line
-
hf download hf://spaces/bhaimavi353/Todo/app/api/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/bhaimavi353/Todo/resolve/main/app/api/auth.py
3.62 kB
| """Authentication API endpoints - sign-in, sign-up, logout.""" | |
| from datetime import datetime, timezone, timedelta | |
| from typing import Optional | |
| import jwt | |
| from fastapi import APIRouter, HTTPException, status | |
| from pydantic import BaseModel, EmailStr | |
| from sqlmodel import select | |
| from .deps import DBSession, CurrentUser | |
| from ..models.user import User | |
| from ..core.config import get_settings | |
| router = APIRouter(prefix="/api/auth", tags=["auth"]) | |
| settings = get_settings() | |
| class SignUpRequest(BaseModel): | |
| """Request schema for user registration.""" | |
| email: EmailStr | |
| password: str | |
| class SignInRequest(BaseModel): | |
| """Request schema for user login.""" | |
| email: EmailStr | |
| password: str | |
| class AuthResponse(BaseModel): | |
| """Response schema for authentication.""" | |
| user_id: str | |
| email: str | |
| token: str | |
| def create_jwt_token(user_id: str, email: str) -> str: | |
| """Create a JWT token for the user.""" | |
| payload = { | |
| "sub": user_id, | |
| "email": email, | |
| "iat": datetime.now(timezone.utc), | |
| "exp": datetime.now(timezone.utc) + timedelta(days=7), | |
| } | |
| return jwt.encode(payload, settings.better_auth_secret, algorithm="HS256") | |
| async def sign_up( | |
| request: SignUpRequest, | |
| session: DBSession, | |
| ) -> AuthResponse: | |
| """ | |
| Register a new user. | |
| Note: In production, password should be hashed. This is simplified for hackathon. | |
| """ | |
| # Check if user already exists | |
| query = select(User).where(User.email == request.email) | |
| result = await session.execute(query) | |
| existing_user = result.scalar_one_or_none() | |
| if existing_user: | |
| raise HTTPException( | |
| status_code=status.HTTP_409_CONFLICT, | |
| detail="User with this email already exists", | |
| ) | |
| # Create new user (simple hash for demo - use bcrypt in production) | |
| import hashlib | |
| password_hash = hashlib.sha256(request.password.encode()).hexdigest() | |
| user = User(email=request.email, password_hash=password_hash) | |
| session.add(user) | |
| await session.flush() | |
| await session.refresh(user) | |
| # Generate JWT token | |
| token = create_jwt_token(str(user.id), user.email) | |
| return AuthResponse( | |
| user_id=str(user.id), | |
| email=user.email, | |
| token=token, | |
| ) | |
| async def sign_in( | |
| request: SignInRequest, | |
| session: DBSession, | |
| ) -> AuthResponse: | |
| """ | |
| Sign in an existing user. | |
| Note: In production, password should be verified against hash. | |
| For hackathon demo, auto-creates user if not exists. | |
| """ | |
| # Find user by email | |
| query = select(User).where(User.email == request.email) | |
| result = await session.execute(query) | |
| user = result.scalar_one_or_none() | |
| # Auto-create user if not exists (for demo purposes) | |
| if not user: | |
| import hashlib | |
| password_hash = hashlib.sha256(request.password.encode()).hexdigest() | |
| user = User(email=request.email, password_hash=password_hash) | |
| session.add(user) | |
| await session.flush() | |
| await session.refresh(user) | |
| # Generate JWT token | |
| token = create_jwt_token(str(user.id), user.email) | |
| return AuthResponse( | |
| user_id=str(user.id), | |
| email=user.email, | |
| token=token, | |
| ) | |
| async def logout(current_user: CurrentUser) -> dict: | |
| """ | |
| Logout the current user. | |
| Note: With JWT, logout is primarily client-side (delete token). | |
| This endpoint exists for API completeness. | |
| """ | |
| return {"message": "Successfully logged out"} | |