From d5d7bf1754ca9383bd0bdc5b588b5ee69527e37a Mon Sep 17 00:00:00 2001 From: Sk_Akib_Ahammed Date: Fri, 9 Jan 2026 22:27:11 +0530 Subject: [PATCH] handling new workflow for user auth --- app/app.py | 22 ++++------- app/auth.py | 107 +++++++++++++++++++++----------------------------- app/schema.py | 9 ----- 3 files changed, 52 insertions(+), 86 deletions(-) diff --git a/app/app.py b/app/app.py index 8ee8572..0091284 100644 --- a/app/app.py +++ b/app/app.py @@ -5,8 +5,6 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from .schema import ( - LoginSchema, - SignUpSchema, MenuSchema, AddStaffSchema, UpdateStaffEmailSchema, @@ -14,8 +12,7 @@ MenuScanResponse ) from .auth import ( - auth_signup_users, - auth_login_users, + authenticate_student, verify_staff_access ) from .staff import ( @@ -37,7 +34,6 @@ app.add_middleware( CORSMiddleware, - allow_origins=[ "http://localhost:5000", "http://127.0.0.1:5000", @@ -57,17 +53,13 @@ def health_check(): "environment": os.getenv("ENV", "development") } -@app.post('/auth/verify-staff', tags=["verify"]) -async def verify_staff(credentials: HTTPAuthorizationCredentials = Security(security)): +@app.post('/auth/verify-staff', tags=["auth"]) +async def verify_staff_endpoint(credentials: HTTPAuthorizationCredentials = Security(security)): return await verify_staff_access(credentials.credentials) -@app.post('/signup/users', tags=["user"]) -async def signup_users(user_data: SignUpSchema): - return await auth_signup_users(user_data) - -@app.post('/login/users', tags=["user"]) -async def login_users(user_data: LoginSchema): - return await auth_login_users(user_data) +@app.post('/auth/verify-student', tags=["auth"]) +async def verify_student_endpoint(credentials: HTTPAuthorizationCredentials = Security(security)): + return await authenticate_student(credentials.credentials) @app.get("/user/menu", tags=["user"]) async def get_student_menu_endpoint( @@ -146,4 +138,4 @@ async def delete_menu_item_endpoint( return await delete_menu_item( item_id, credentials.credentials - ) + ) \ No newline at end of file diff --git a/app/auth.py b/app/auth.py index 8d04c17..a3fdf37 100644 --- a/app/auth.py +++ b/app/auth.py @@ -1,21 +1,21 @@ # app/auth.py -import os, requests -from .schema import LoginSchema, SignUpSchema +import os from fastapi.responses import JSONResponse from starlette import status from firebase_admin import auth, firestore from .firebase_init import db -FIREBASE_API_KEY = os.getenv("FIREBASE_API_KEY") def _create_response(status_code: int, message: str, **kwargs): content = {"message": message} content.update(kwargs) return JSONResponse(status_code=status_code, content=content) + def _get_college_by_domain(email: str): try: + if not email: return None, None domain = email.split("@")[-1] query = ( db.collection("colleges") @@ -30,79 +30,63 @@ def _get_college_by_domain(email: str): print(f"College lookup error: {e}") return None, None -def _validate_passwords(password: str, confirm_password: str): - if password != confirm_password: - return False, "Passwords do not match" - return True, "" - -async def auth_signup_users(user_data: SignUpSchema): - email = user_data.email - password = user_data.password - confirm_password = user_data.confirm_password - - valid, msg = _validate_passwords(password, confirm_password) - if not valid: - return _create_response(status.HTTP_400_BAD_REQUEST, msg) - college_id, college_data = _get_college_by_domain(email) - if not college_id: - return _create_response( - status.HTTP_400_BAD_REQUEST, - "Your college domain is not registered with GreenPlate.", - ) +async def authenticate_student(token: str): try: - user = auth.create_user(email=email, password=password) - db.collection("users").document(user.uid).set( - { - "email": email, - "college_id": college_id, - "college_name": college_data.get("name"), - "role": "student", - "created_at": firestore.SERVER_TIMESTAMP, - } - ) - return _create_response( - status.HTTP_201_CREATED, "User created successfully", uid=user.uid - ) - except Exception as e: - return _create_response(status.HTTP_500_INTERNAL_SERVER_ERROR, str(e)) - + try: + decoded = auth.verify_id_token(token) + except Exception: + return _create_response(status.HTTP_401_UNAUTHORIZED, "Invalid or expired token") -async def auth_login_users(user_data: LoginSchema): - email = user_data.email - password = user_data.password + uid = decoded["uid"] + email = decoded.get("email") - college_id, _ = _get_college_by_domain(email) - if not college_id: - return _create_response( - status.HTTP_400_BAD_REQUEST, - "Your college domain is not registered.", - ) + if not email: + return _create_response(status.HTTP_400_BAD_REQUEST, "Invalid token: Email required.") - try: - request_url = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={FIREBASE_API_KEY}" - payload = { - "email": email, - "password": password, - "returnSecureToken": True - } - response = requests.post(request_url, json=payload) - response_data = response.json() + user_doc_ref = db.collection("users").document(uid) + user_doc = user_doc_ref.get() - if response.status_code == 200: + if user_doc.exists: return _create_response( status.HTTP_200_OK, "Login successful", - idToken=response_data["idToken"], + role="student", + college_id=user_doc.to_dict().get("college_id") + ) + + college_id, college_data = _get_college_by_domain(email) + + if not college_id: + try: + auth.delete_user(uid) + except: + pass + return _create_response( + status.HTTP_403_FORBIDDEN, + "Your college domain is not registered with GreenPlate.", ) - else: - error_msg = response_data.get("error", {}).get("message", "Login failed") - return _create_response(status.HTTP_401_UNAUTHORIZED, error_msg) + + user_doc_ref.set({ + "email": email, + "college_id": college_id, + "college_name": college_data.get("name"), + "role": "student", + "created_at": firestore.SERVER_TIMESTAMP, + }) + + return _create_response( + status.HTTP_201_CREATED, + "User registered and logged in", + role="student", + college_id=college_id + ) except Exception as e: return _create_response(status.HTTP_500_INTERNAL_SERVER_ERROR, str(e)) + async def verify_staff_access(token: str): try: decoded = auth.verify_id_token(token) @@ -144,7 +128,6 @@ async def verify_staff_access(token: str): break if found_stall: - new_staff_data = { "email": email, "stall_id": found_stall.id, diff --git a/app/schema.py b/app/schema.py index 02437d5..45e47bd 100644 --- a/app/schema.py +++ b/app/schema.py @@ -3,11 +3,6 @@ from pydantic import BaseModel, Field from typing import List, Optional -class SignUpSchema(BaseModel): - email: str - password: str - confirm_password: str - class AddStaffSchema(BaseModel): email: str @@ -17,10 +12,6 @@ class StaffAuthResponse(BaseModel): stall_id: str college_id: str -class LoginSchema(BaseModel): - email: str - password: str - class UpdateStaffEmailSchema(BaseModel): new_email: str