Init
This commit is contained in:
73
app/routers/auth.py
Normal file
73
app/routers/auth.py
Normal file
@@ -0,0 +1,73 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from firebase_admin import auth
|
||||
from ..firebase_config import get_db
|
||||
from ..models import UserCreate, UserRecord, LoginRequest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/register", response_model=UserRecord, status_code=status.HTTP_201_CREATED)
|
||||
async def register_user(user: UserCreate):
|
||||
"""
|
||||
Registers a user in Firebase Auth and creates a corresponding user document in Firestore.
|
||||
"""
|
||||
try:
|
||||
user_record = auth.create_user(
|
||||
email=user.email,
|
||||
password=user.password,
|
||||
display_name=user.full_name
|
||||
)
|
||||
|
||||
db = get_db()
|
||||
user_data = {
|
||||
"uid": user_record.uid,
|
||||
"email": user.email,
|
||||
"full_name": user.full_name,
|
||||
"role": "member"
|
||||
}
|
||||
db.collection('users').document(user_record.uid).set(user_data)
|
||||
|
||||
return user_data
|
||||
|
||||
except auth.EmailAlreadyExistsError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Email already registered",
|
||||
)
|
||||
|
||||
@router.post("/login", response_model=UserRecord)
|
||||
async def login(login_data: LoginRequest):
|
||||
"""
|
||||
Verifies a Firebase ID token, checks user role from Firestore, and returns user data.
|
||||
"""
|
||||
try:
|
||||
decoded_token = auth.verify_id_token(login_data.id_token)
|
||||
uid = decoded_token['uid']
|
||||
|
||||
db = get_db()
|
||||
user_doc = db.collection('users').document(uid).get()
|
||||
|
||||
if not user_doc.exists:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found in the database.",
|
||||
)
|
||||
|
||||
user = user_doc.to_dict()
|
||||
if user.get("role") == "member":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is not activated. Please contact an administrator."
|
||||
)
|
||||
|
||||
return UserRecord(**user)
|
||||
|
||||
except auth.InvalidIdTokenError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid Firebase ID token",
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
Reference in New Issue
Block a user