xtablo-source/backend/app/routers/auth.py
Arthur Belleville 45fc8513a1
tout marche
2025-03-25 09:17:53 +01:00

132 lines
No EOL
5 KiB
Python

from fastapi import Depends, HTTPException, status, Request
from fastapi.routing import APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.security import OAuth2PasswordBearer
from fastapi.responses import RedirectResponse
from supabase import Client
from app.config import settings
from jose import JWTError, jwt
import os
from app.routers.helpers import get_supabase, get_current_user_required, get_current_user_optional
from app.schemas.user import UserCreate, UserLogin, UserOut
from app.schemas.token import RefreshResponse, RefreshToken
router = APIRouter(tags=["auth"])
@router.post("/register")
async def register(user: UserCreate, supabase: Client = Depends(get_supabase)):
try:
return supabase.auth.sign_up({
"email": user.email,
"password": user.password,
"options": {"data": {"first_name": user.first_name, "last_name": user.last_name, "business_name": user.business_name}}
})
except Exception as e:
headers = {}
if e.code == "user_already_exists":
headers = {"X-Error-Code": e.code, "X-Error-Message": "Cette adresse email est déjà utilisée"}
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
@router.post("/login")
async def login(credentials: UserLogin, supabase: Client = Depends(get_supabase)):
try:
print("Login attempt for:", credentials.email) # Debug log
response = supabase.auth.sign_in_with_password({
"email": credentials.email.strip(),
"password": credentials.password.strip()
})
print("Login response:", response)
return {
"access_token": response.session.access_token,
"token_type": "bearer"
}
except Exception as e:
headers = {}
if e.code == "invalid_credentials":
headers = {"X-Error-Code": e.code, "X-Error-Message": "Email ou mot de passe incorrect"}
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers=headers
)
@router.get("/login/google")
async def login_with_google(supabase: Client = Depends(get_supabase)):
try:
response = supabase.auth.sign_in_with_oauth({
"provider": "google",
"options": {
"redirect_to": "http://localhost:8000/auth/callback"
}
})
return {"auth_url": response.url}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str(e)
)
@router.get("/callback")
async def google_callback(request: Request, supabase: Client = Depends(get_supabase)):
code = request.query_params.get("code")
if not code:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing authorization code")
supabase.auth.exchange_code_for_session({"auth_code": code})
return RedirectResponse(url="http://localhost:5173")
@router.post("/logout")
async def logout(user=Depends(get_current_user_required), supabase: Client = Depends(get_supabase)):
try:
supabase.auth.sign_out()
return {"message": "Successfully logged out"}
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
@router.get("/users/me")
async def get_me(
user = Depends(get_current_user_required),
):
try:
return jsonable_encoder(user)
except IndexError:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found in database"
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str(e)
)
@router.post("/refresh", response_model=RefreshResponse)
async def refresh_token(refresh_request: RefreshToken, supabase: Client = Depends(get_supabase)):
"""Refresh the access token using a valid refresh token."""
try:
# Validate the refresh token and get new tokens
response = supabase.auth.refresh_session(refresh_request.refresh_token)
# Extract user data
user_data = {
"id": response.user.id,
"email": response.user.email,
"first_name": response.user.user_metadata.get("first_name", "Unknown"),
"last_name": response.user.user_metadata.get("last_name", "Unknown"),
"business_name": response.user.user_metadata.get("business_name", "Unknown")
}
# Return the new tokens and user data
return {
"access_token": response.session.access_token,
"refresh_token": response.session.refresh_token,
"expires_at": int(response.session.expires_at),
"user": user_data
}
except Exception as e:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Failed to refresh token: {str(e)}")