After_Chido_Api/api/v1/auth.py

36 lines
1.6 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from services.auth_service import AuthService
from models.schemas import Token, UserCreate, UserResponse
from config.database import get_db
from utils.security import verify_password, get_password_hash
router = APIRouter()
@router.post("/signup", response_model=UserResponse, status_code=201, summary="User Signup")
async def signup(user: UserCreate, db=Depends(get_db)):
existing_user = await AuthService.get_user_by_email(user.email, db)
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered."
)
user.password = get_password_hash(user.password)
return await AuthService.create_user(user, db)
@router.post("/token", response_model=Token, summary="Login and get access token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db=Depends(get_db)):
user = await AuthService.authenticate_user(form_data.username, form_data.password, db)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = AuthService.create_access_token(data={"sub": user["email"]})
return {"access_token": access_token, "token_type": "bearer"}
@router.get("/me", response_model=UserResponse, summary="Get current user")
async def read_users_me(current_user: UserResponse = Depends(AuthService.get_current_user)):
return current_user