Spaces:
Sleeping
Sleeping
Update api/routes/auth.py
Browse files- api/routes/auth.py +48 -111
api/routes/auth.py
CHANGED
|
@@ -1,137 +1,74 @@
|
|
| 1 |
-
from fastapi import APIRouter, HTTPException,
|
| 2 |
from fastapi.security import OAuth2PasswordRequestForm
|
| 3 |
from db.mongo import users_collection
|
| 4 |
from core.security import hash_password, verify_password, create_access_token, get_current_user
|
| 5 |
-
from models.schemas import SignupForm, TokenResponse
|
| 6 |
from datetime import datetime
|
| 7 |
import logging
|
| 8 |
|
| 9 |
-
# Configure logging
|
| 10 |
-
logging.basicConfig(
|
| 11 |
-
level=logging.INFO,
|
| 12 |
-
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'
|
| 13 |
-
)
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
router = APIRouter()
|
|
|
|
| 17 |
|
| 18 |
-
@router.post("/
|
| 19 |
-
async def
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
logger.warning(f"Signup failed: Email already exists: {email}")
|
| 25 |
-
raise HTTPException(
|
| 26 |
-
status_code=status.HTTP_409_CONFLICT,
|
| 27 |
-
detail="Email already exists"
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
hashed_pw = hash_password(data.password)
|
| 31 |
-
user_doc = {
|
| 32 |
-
"email": email,
|
| 33 |
-
"full_name": data.full_name.strip(),
|
| 34 |
-
"password": hashed_pw,
|
| 35 |
-
"role": "patient",
|
| 36 |
-
"created_at": datetime.utcnow().isoformat(),
|
| 37 |
-
"updated_at": datetime.utcnow().isoformat()
|
| 38 |
-
}
|
| 39 |
|
| 40 |
try:
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
return {
|
| 44 |
-
"
|
| 45 |
-
"
|
| 46 |
-
"
|
| 47 |
}
|
|
|
|
|
|
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
-
logger.error(f"
|
| 50 |
raise HTTPException(
|
| 51 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 52 |
-
detail=
|
| 53 |
)
|
| 54 |
|
| 55 |
-
@router.
|
| 56 |
-
async def
|
| 57 |
-
|
| 58 |
current_user: dict = Depends(get_current_user)
|
| 59 |
):
|
| 60 |
-
logger.info(f"
|
| 61 |
-
if current_user.get('role') != 'admin':
|
| 62 |
-
logger.warning(f"Unauthorized doctor creation attempt by {current_user.get('email')}")
|
| 63 |
-
raise HTTPException(
|
| 64 |
-
status_code=status.HTTP_403_FORBIDDEN,
|
| 65 |
-
detail="Only admins can create doctor accounts"
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
email = data.email.lower().strip()
|
| 69 |
-
existing = await users_collection.find_one({"email": email})
|
| 70 |
-
if existing:
|
| 71 |
-
logger.warning(f"Doctor creation failed: Email already exists: {email}")
|
| 72 |
-
raise HTTPException(
|
| 73 |
-
status_code=status.HTTP_409_CONFLICT,
|
| 74 |
-
detail="Email already exists"
|
| 75 |
-
)
|
| 76 |
-
|
| 77 |
-
hashed_pw = hash_password(data.password)
|
| 78 |
-
doctor_doc = {
|
| 79 |
-
"email": email,
|
| 80 |
-
"full_name": data.full_name.strip(),
|
| 81 |
-
"password": hashed_pw,
|
| 82 |
-
"role": "doctor",
|
| 83 |
-
"specialty": data.specialty,
|
| 84 |
-
"license_number": data.license_number,
|
| 85 |
-
"created_at": datetime.utcnow().isoformat(),
|
| 86 |
-
"updated_at": datetime.utcnow().isoformat()
|
| 87 |
-
}
|
| 88 |
|
| 89 |
try:
|
| 90 |
-
result = await users_collection.insert_one(doctor_doc)
|
| 91 |
-
logger.info(f"Doctor created successfully: {email}")
|
| 92 |
return {
|
| 93 |
-
"
|
| 94 |
-
"
|
| 95 |
-
"
|
|
|
|
| 96 |
}
|
| 97 |
except Exception as e:
|
| 98 |
-
logger.error(f"
|
| 99 |
raise HTTPException(
|
| 100 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 101 |
-
detail=
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
@router.post("/login", response_model=TokenResponse)
|
| 105 |
-
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
| 106 |
-
logger.info(f"Login attempt for email: {form_data.username}")
|
| 107 |
-
user = await users_collection.find_one({"email": form_data.username.lower()})
|
| 108 |
-
if not user or not verify_password(form_data.password, user["password"]):
|
| 109 |
-
logger.warning(f"Login failed for {form_data.username}: Invalid credentials")
|
| 110 |
-
raise HTTPException(
|
| 111 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 112 |
-
detail="Invalid credentials",
|
| 113 |
-
headers={"WWW-Authenticate": "Bearer"},
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
access_token = create_access_token(data={"sub": user["email"]})
|
| 117 |
-
logger.info(f"Successful login for {form_data.username}")
|
| 118 |
-
return {
|
| 119 |
-
"access_token": access_token,
|
| 120 |
-
"token_type": "bearer",
|
| 121 |
-
"role": user.get("role", "patient")
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
@router.get("/me")
|
| 125 |
-
async def get_me(request: Request, current_user: dict = Depends(get_current_user)):
|
| 126 |
-
logger.info(f"Fetching user profile for {current_user['email']}")
|
| 127 |
-
return {
|
| 128 |
-
"email": current_user["email"],
|
| 129 |
-
"full_name": current_user.get("full_name"),
|
| 130 |
-
"role": current_user.get("role")
|
| 131 |
-
}
|
| 132 |
-
@router.get("/test-auth")
|
| 133 |
-
async def test_token_auth(current_user: dict = Depends(get_current_user)):
|
| 134 |
-
return {"status": "ok", "email": current_user.get("email")}
|
| 135 |
-
|
| 136 |
-
# Export the router as 'auth' for api.__init__.py
|
| 137 |
-
auth = router
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, status, Depends, Request
|
| 2 |
from fastapi.security import OAuth2PasswordRequestForm
|
| 3 |
from db.mongo import users_collection
|
| 4 |
from core.security import hash_password, verify_password, create_access_token, get_current_user
|
| 5 |
+
from models.schemas import SignupForm, TokenResponse
|
| 6 |
from datetime import datetime
|
| 7 |
import logging
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
router = APIRouter()
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
+
@router.post("/login", response_model=TokenResponse)
|
| 13 |
+
async def login(
|
| 14 |
+
request: Request,
|
| 15 |
+
form_data: OAuth2PasswordRequestForm = Depends()
|
| 16 |
+
):
|
| 17 |
+
logger.info(f"Login attempt from {request.client.host} for email: {form_data.username}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
try:
|
| 20 |
+
user = await users_collection.find_one({"email": form_data.username.lower()})
|
| 21 |
+
if not user:
|
| 22 |
+
logger.warning(f"Login failed - user not found: {form_data.username}")
|
| 23 |
+
raise HTTPException(
|
| 24 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 25 |
+
detail="Invalid credentials",
|
| 26 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
if not verify_password(form_data.password, user["password"]):
|
| 30 |
+
logger.warning(f"Login failed - invalid password for: {form_data.username}")
|
| 31 |
+
raise HTTPException(
|
| 32 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 33 |
+
detail="Invalid credentials",
|
| 34 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
access_token = create_access_token(data={"sub": user["email"]})
|
| 38 |
+
logger.info(f"Successful login for {user['email']}")
|
| 39 |
+
|
| 40 |
return {
|
| 41 |
+
"access_token": access_token,
|
| 42 |
+
"token_type": "bearer",
|
| 43 |
+
"role": user.get("role", "patient")
|
| 44 |
}
|
| 45 |
+
|
| 46 |
+
except HTTPException:
|
| 47 |
+
raise
|
| 48 |
except Exception as e:
|
| 49 |
+
logger.error(f"Login error for {form_data.username}: {str(e)}")
|
| 50 |
raise HTTPException(
|
| 51 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 52 |
+
detail="Internal server error during login"
|
| 53 |
)
|
| 54 |
|
| 55 |
+
@router.get("/me")
|
| 56 |
+
async def get_current_user_profile(
|
| 57 |
+
request: Request,
|
| 58 |
current_user: dict = Depends(get_current_user)
|
| 59 |
):
|
| 60 |
+
logger.info(f"Profile request for {current_user['email']} from {request.client.host}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
try:
|
|
|
|
|
|
|
| 63 |
return {
|
| 64 |
+
"email": current_user["email"],
|
| 65 |
+
"full_name": current_user.get("full_name"),
|
| 66 |
+
"role": current_user.get("role"),
|
| 67 |
+
"created_at": current_user.get("created_at")
|
| 68 |
}
|
| 69 |
except Exception as e:
|
| 70 |
+
logger.error(f"Profile error for {current_user['email']}: {str(e)}")
|
| 71 |
raise HTTPException(
|
| 72 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 73 |
+
detail="Failed to retrieve profile"
|
| 74 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|