Spaces:
Sleeping
Sleeping
File size: 13,185 Bytes
b6b3f7f 923dda1 b28bbf0 b6b3f7f b28bbf0 b6b3f7f 82ccb3f b6b3f7f b28bbf0 b6b3f7f b28bbf0 b6b3f7f 923dda1 b6b3f7f b28bbf0 b6b3f7f 82ccb3f b6b3f7f b28bbf0 b6b3f7f b28bbf0 b6b3f7f b28bbf0 b6b3f7f b28bbf0 923dda1 b28bbf0 923dda1 b28bbf0 923dda1 b28bbf0 923dda1 b28bbf0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | from fastapi import APIRouter, HTTPException, Depends, status
from datetime import datetime, timedelta
from app.models.user import UserCreate, UserLogin, User, Token, UserResponse, UserUpdate
from pydantic import BaseModel, model_validator
from typing import Optional
from app.core.auth import (
get_password_hash,
verify_password,
authenticate_user,
create_access_token,
get_user_by_email,
get_current_active_user,
create_user_response,
ACCESS_TOKEN_EXPIRE_MINUTES
)
from app.core.database import get_database
import logging
import secrets
import uuid
logger = logging.getLogger(__name__)
class MessageResponse(BaseModel):
message: str
class ChangePasswordRequest(BaseModel):
current_password: str
new_password: str
@model_validator(mode="after")
def passwords_must_differ(self):
if self.current_password == self.new_password:
raise ValueError("New password must be different from the current password")
return self
class UpdateProfileRequest(BaseModel):
first_name: Optional[str] = None
last_name: Optional[str] = None
@model_validator(mode="after")
def at_least_one_field(self):
if self.first_name is not None:
self.first_name = self.first_name.strip() or None
if self.last_name is not None:
self.last_name = self.last_name.strip() or None
if self.first_name is None and self.last_name is None:
raise ValueError("At least one field must be provided")
return self
class DeleteAccountRequest(BaseModel):
password: str
router = APIRouter()
@router.post("/signup", response_model=Token)
async def signup(user_data: UserCreate):
"""
Register a new user and return an access token.
@param user_data: UserCreate with name, email, password, and optional academic fields
@return: Token containing a JWT access token and the created UserResponse
"""
try:
db = get_database()
# Check if user already exists
existing_user = await get_user_by_email(user_data.email)
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
# Create new user
hashed_password = get_password_hash(user_data.password)
user = User(
firstName=user_data.firstName,
lastName=user_data.lastName,
email=user_data.email,
hashed_password=hashed_password,
academicStage=user_data.academicStage,
researchArea=user_data.researchArea,
created_at=datetime.utcnow(),
is_active=True
)
# Insert user into database
result = await db.users.insert_one(user.dict(by_alias=True))
user.id = result.inserted_id
profile_seed: dict = {
"user_id": user.id,
"updated_at": datetime.utcnow(),
}
if user_data.academicStage:
profile_seed["knowledge_level"] = user_data.academicStage
if user_data.researchArea:
profile_seed["timezone"] = user_data.researchArea
await db.user_profiles.update_one(
{"user_id": user.id},
{"$set": profile_seed},
upsert=True,
)
# Create access token
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": str(user.id)},
expires_delta=access_token_expires
)
return Token(
access_token=access_token,
token_type="bearer",
user=create_user_response(user)
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error during signup: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not create user account"
)
@router.post("/login", response_model=Token)
async def login(user_credentials: UserLogin):
"""
Authenticate a user and return an access token.
@param user_credentials: UserLogin with email and password
@return: Token containing a JWT access token and the authenticated UserResponse
"""
try:
# Authenticate user
user = await authenticate_user(user_credentials.email, user_credentials.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Update last login time
db = get_database()
await db.users.update_one(
{"_id": user.id},
{"$set": {"last_login": datetime.utcnow()}}
)
user.last_login = datetime.utcnow()
# Create access token
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": str(user.id)},
expires_delta=access_token_expires
)
return Token(
access_token=access_token,
token_type="bearer",
user=create_user_response(user)
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error during login: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Login failed"
)
@router.post("/guest", response_model=Token)
async def guest_login():
"""Create a disposable guest session so visitors can try the advisors without signing up."""
try:
db = get_database()
guest_id = uuid.uuid4().hex[:12]
# Must be a syntactically valid email: EmailStr / email-validator
# rejects reserved TLDs like `.local`, which previously made guest
# sign-in always 500.
email = f"guest-{guest_id}@guests.musclegrowth.ai"
user = User(
firstName="Guest",
lastName="Athlete",
email=email,
hashed_password=get_password_hash(secrets.token_urlsafe(32)),
created_at=datetime.utcnow(),
last_login=datetime.utcnow(),
is_active=True,
is_guest=True,
)
result = await db.users.insert_one(user.dict(by_alias=True))
user.id = result.inserted_id
await db.user_profiles.update_one(
{"user_id": user.id},
{
"$set": {
"user_id": user.id,
"updated_at": datetime.utcnow(),
}
},
upsert=True,
)
access_token = create_access_token(
data={"sub": str(user.id), "guest": True},
expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES),
)
return Token(
access_token=access_token,
token_type="bearer",
user=create_user_response(user),
)
except Exception as e:
logger.error(f"Error during guest login: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not start guest session",
)
@router.get("/me", response_model=UserResponse)
async def get_current_user_profile(current_user: User = Depends(get_current_active_user)):
"""
Retrieve the profile of the currently authenticated user.
@param current_user: Authenticated user from dependency injection
@return: UserResponse with the user's profile information
"""
return create_user_response(current_user)
@router.post("/logout", response_model=MessageResponse)
async def logout():
"""
Log out the current user (client should discard the token).
@return: MessageResponse with a confirmation message
"""
return MessageResponse(message="Successfully logged out")
@router.post("/verify-token", response_model=UserResponse)
async def verify_token(current_user: User = Depends(get_current_active_user)):
"""
Validate the caller's JWT and return their profile.
@param current_user: Authenticated user from dependency injection
@return: UserResponse with the user's profile information
"""
return create_user_response(current_user)
@router.post("/me/password", response_model=MessageResponse)
async def change_password(
body: ChangePasswordRequest,
current_user: User = Depends(get_current_active_user),
):
"""
Change the authenticated user's password.
@param body: ChangePasswordRequest with the current and new passwords
@param current_user: Authenticated user from dependency injection
@return: MessageResponse with a confirmation message
"""
try:
if not verify_password(body.current_password, current_user.hashed_password):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Current password is incorrect",
)
if len(body.new_password) < 8:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="New password must be at least 8 characters",
)
db = get_database()
await db.users.update_one(
{"_id": current_user.id},
{"$set": {"hashed_password": get_password_hash(body.new_password)}},
)
return MessageResponse(message="Password changed successfully")
except HTTPException:
raise
except Exception as e:
logger.error(f"Error during password change: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not change password"
)
@router.patch("/me", response_model=UserResponse)
async def update_profile(
body: UserUpdate,
current_user: User = Depends(get_current_active_user),
):
"""Update account fields (name, email, avatar, signup preferences)."""
try:
db = get_database()
updates = {k: v for k, v in body.dict().items() if v is not None}
if body.firstName is not None:
updates["firstName"] = body.firstName.strip()
if body.lastName is not None:
updates["lastName"] = body.lastName.strip()
if not updates:
return create_user_response(current_user)
if "email" in updates and updates["email"] != current_user.email:
existing = await get_user_by_email(updates["email"])
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already in use",
)
await db.users.update_one({"_id": current_user.id}, {"$set": updates})
profile_sync: dict = {"updated_at": datetime.utcnow()}
if body.academicStage is not None:
profile_sync["knowledge_level"] = body.academicStage
if body.researchArea is not None:
profile_sync["timezone"] = body.researchArea
if len(profile_sync) > 1:
await db.user_profiles.update_one(
{"user_id": current_user.id},
{"$set": profile_sync, "$setOnInsert": {"user_id": current_user.id}},
upsert=True,
)
updated_user = await db.users.find_one({"_id": current_user.id})
return create_user_response(User(**updated_user))
except HTTPException:
raise
except Exception as e:
logger.error(f"Error during profile update: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not update profile"
)
@router.delete("/me", response_model=MessageResponse)
async def delete_account(
body: DeleteAccountRequest,
current_user: User = Depends(get_current_active_user),
):
"""
Permanently delete the authenticated user's account, all chat sessions, and all PhD Canvas data.
@param body: DeleteAccountRequest with the user's password for confirmation
@param current_user: Authenticated user from dependency injection
@return: MessageResponse with a confirmation message
"""
try:
if not verify_password(body.password, current_user.hashed_password):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Incorrect password",
)
db = get_database()
uid = current_user.id
await db.chat_sessions.delete_many({"user_id": uid})
await db.phd_canvases.delete_many({"user_id": uid})
await db.users.delete_one({"_id": uid})
return MessageResponse(message="Account deleted")
except HTTPException:
raise
except Exception as e:
logger.error(f"Error during account deletion: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not delete account"
) |