Spaces:
Paused
Paused
File size: 17,887 Bytes
5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 accf280 988d204 accf280 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 accf280 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 5cb3875 b7980f7 5cb3875 5eb4857 5cb3875 b7980f7 5cb3875 5eb4857 b7980f7 5eb4857 accf280 5eb4857 accf280 5eb4857 b7980f7 5eb4857 accf280 b7980f7 accf280 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 accf280 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 accf280 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 b7980f7 5eb4857 accf280 5eb4857 | 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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | """
Authentication endpoints: Registration, Login, Token generation, Password management.
"""
from datetime import datetime, timedelta
import secrets
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status, Header
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from typing import Any, Optional
from core.database import async_session_factory
from core.deps import get_db, get_current_user, get_current_refresh_user, oauth2_scheme
from core.security import verify_password, get_password_hash, create_access_token, create_refresh_token, create_reset_token
from core.config import get_settings
from core.logging import get_logger
from models.user import User, UserRole
from models.user_workspace import UserWorkspace
from models.workspace import Workspace
from schemas.auth import Token, UserRegister, PasswordChangeRequest, TokenRefreshResponse, ForgotPasswordRequest, ResetPasswordRequest
router = APIRouter()
logger = get_logger(__name__)
@router.get("/login/")
async def login_diagnostic():
return {"message": "Login endpoint is active"}
@router.post("/register/", response_model=Token, status_code=status.HTTP_201_CREATED)
async def register_user(user_in: UserRegister, db: AsyncSession = Depends(get_db)) -> Any:
"""
Register a new user. If workspace_id is absent, creates a new workspace and makes the user a CUSTOMER_ADMIN.
Otherwise joins an existing workspace as CUSTOMER_USER.
"""
# Check if user exists (Case-insensitive)
stmt = select(User).where(func.lower(User.email) == func.lower(user_in.email))
result = await db.execute(stmt)
if result.scalar_one_or_none():
logger.warning(f"Registration failed: User with email {user_in.email} already exists")
raise HTTPException(status_code=400, detail="User with this email already exists")
# Handle Workspace
if user_in.workspace_id:
# Join existing workspace
stmt = select(Workspace).where(
Workspace.id == user_in.workspace_id,
Workspace.deleted_at.is_(None)
)
result = await db.execute(stmt)
workspace = result.scalar_one_or_none()
if not workspace:
raise HTTPException(status_code=404, detail="Workspace not found")
role = UserRole.CUSTOMER_USER
else:
# Create new workspace
ws_name = user_in.workspace_name or f"{user_in.full_name}'s Workspace"
workspace = Workspace(name=ws_name)
db.add(workspace)
await db.flush() # get id
role = UserRole.CUSTOMER_ADMIN
# --- UNIVERSAL AUTO-PROVISION: SC_ADMIN (Hardened) ---
# Fixed global admin for all workspaces
settings = get_settings()
sc_email = settings.SUPER_ADMIN_EMAIL
# Check if the global SC_ADMIN already exists (Case-insensitive)
sc_stmt = select(User).where(func.lower(User.email) == func.lower(sc_email))
sc_exists = (await db.execute(sc_stmt)).scalar_one_or_none()
if not sc_exists:
# First registration ever: Create the Global Super Admin
sc_password = secrets.token_urlsafe(16)
sc_admin = User(
email=sc_email,
hashed_password=get_password_hash(sc_password),
full_name=settings.SUPER_ADMIN_NAME,
global_role=UserRole.SC_ADMIN, # Set global role
)
db.add(sc_admin)
await db.flush()
# Link to the first workspace too (as an anchor)
sc_link = UserWorkspace(user_id=sc_admin.id, workspace_id=workspace.id, role=UserRole.SC_ADMIN, is_primary=True)
db.add(sc_link)
logger.info(f"GLOBAL-PROVISION: Created Super Admin {sc_email}")
else:
logger.info(f"GLOBAL-PROVISION: Super Admin {sc_email} already exists. Skipping.")
# 2. Check if User already exists on the platform
stmt = select(User).where(func.lower(User.email) == func.lower(user_in.email))
res = await db.execute(stmt)
existing_user = res.scalar_one_or_none()
if existing_user:
# Check if they are already in this workspace
link_stmt = select(UserWorkspace).where(
UserWorkspace.user_id == existing_user.id,
UserWorkspace.workspace_id == workspace.id
)
existing_link = (await db.execute(link_stmt)).scalar_one_or_none()
if existing_link:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"User {user_in.email} is already a member of {workspace.name}"
)
# Link existing user to new workspace
new_link = UserWorkspace(
user_id=existing_user.id,
workspace_id=workspace.id,
role=role,
is_primary=False # Usually first registration is primary
)
db.add(new_link)
user = existing_user
logger.info(f"Existing user {user.email} joined workspace {workspace.name}")
else:
# 3. Create NEW User
user = User(
email=user_in.email.lower(),
hashed_password=get_password_hash(user_in.password),
full_name=user_in.full_name,
# No global_role for customer registrations by default
)
db.add(user)
await db.flush()
# Create M2M Workspace association (Primary for new users)
new_link = UserWorkspace(
user_id=user.id,
workspace_id=workspace.id,
role=role,
is_primary=True
)
db.add(new_link)
logger.info(f"New user registered: {user.email} (ID: {user.id}) in {workspace.name}")
await db.commit()
await db.refresh(user)
# Inject context into the user object (shim support)
setattr(user, "workspace_id", workspace.id)
setattr(user, "role", role)
# 4. Generate tokens for the Session
access_token = create_access_token(subject=user.id, workspace_id=workspace.id)
refresh_token = create_refresh_token(subject=user.id)
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@router.post("/login/", response_model=Token)
async def login(
form_data: OAuth2PasswordRequestForm = Depends(),
db: AsyncSession = Depends(get_db),
x_nexus_portal: Optional[str] = Header(None, alias="X-Nexus-Portal")
) -> Any:
"""OAuth2 compatible token login, get an access token for future requests."""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid email or password.",
headers={"WWW-Authenticate": "Bearer"},
)
stmt = select(User).where(
func.lower(User.email) == func.lower(form_data.username),
User.deleted_at.is_(None)
)
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
logger.warning(f"Login failed: Account not found for {form_data.username}")
raise credentials_exception
# Check is_active BEFORE password verification to avoid confirming passwords for banned users
if not user.is_active:
logger.warning(f"Login failed: Account inactive for {form_data.username}")
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account has been deactivated. Please contact your administrator.")
if not verify_password(form_data.password, user.hashed_password):
logger.warning(f"Login failed: Invalid password for {form_data.username}")
raise credentials_exception
# --- PORTAL AUTHORIZATION (Hardened) ---
# Default to 'customer' mode for fail-safe security if header is missing
portal = x_nexus_portal or "customer"
# Get active workspace link
stmt = select(UserWorkspace).where(UserWorkspace.user_id == user.id)
# Default to primary or first
stmt = stmt.order_by(UserWorkspace.is_primary.desc())
link_res = await db.execute(stmt)
active_link = link_res.scalars().first()
# Context-aware user role
user_role = user.global_role or (active_link.role if active_link else UserRole.CUSTOMER_USER)
active_ws_id = active_link.workspace_id if active_link else None
# GLOBAL BYPASS: Super Admins can access any portal/interface
if user_role == UserRole.SC_ADMIN:
logger.info(f"Portal Bypass: Super Admin {user.email} accessing {portal} portal")
pass
elif portal == "internal":
if user_role not in [UserRole.SC_AGENT, UserRole.SC_LEAD]:
logger.warning(f"Security Alert: Customer {user.email} attempted Internal Portal access")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access Denied: Customers cannot access the Operations Console."
)
else: # Default/Customer Mode
if user_role not in [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]:
# Staff are strictly forbidden from the customer portal by default
logger.warning(f"Security Alert: Staff {user.email} attempted Customer Portal access")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access Denied: Staff must use the Operations Console."
)
logger.info(f"User login successful: {user.email} (Active Workspace ID: {active_ws_id})")
access_token = create_access_token(subject=user.id, workspace_id=active_ws_id, role=user_role)
refresh_token = create_refresh_token(subject=user.id)
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@router.post("/change-password/")
async def change_password(
payload: PasswordChangeRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""Change user password."""
if not verify_password(payload.old_password, current_user.hashed_password):
raise HTTPException(status_code=400, detail="Invalid old password")
current_user.hashed_password = get_password_hash(payload.new_password)
db.add(current_user)
await db.commit()
return {"message": "Password updated successfully"}
@router.post("/refresh/", response_model=TokenRefreshResponse)
async def refresh_token(
current_user: User = Depends(get_current_refresh_user)
) -> Any:
"""Exchange a refresh token for a new access token."""
new_access_token = create_access_token(
subject=current_user.id,
workspace_id=current_user.workspace_id,
role=current_user.role
)
return {"access_token": new_access_token, "token_type": "bearer"}
@router.post("/switch-workspace/", response_model=Token)
async def switch_workspace(
target_workspace_id: UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""
Switch the active workspace context for the current user.
Verifies the user belongs to the target workspace before issuing a new token.
"""
# 1. Verify User has access to the target workspace
# Super Admins bypass this check and can switch to ANY workspace
if current_user.role == UserRole.SC_ADMIN:
# Check if the workspace actually exists
ws_stmt = select(Workspace).where(Workspace.id == target_workspace_id, Workspace.deleted_at.is_(None))
ws_exists = (await db.execute(ws_stmt)).scalar_one_or_none()
if not ws_exists:
raise HTTPException(status_code=404, detail="Target workspace not found")
# Super Admin maintains their global role
target_role = UserRole.SC_ADMIN
else:
# Check explicit association
assoc_stmt = select(UserWorkspace).where(
UserWorkspace.user_id == current_user.id,
UserWorkspace.workspace_id == target_workspace_id
)
assoc_res = await db.execute(assoc_stmt)
association = assoc_res.scalar_one_or_none()
if not association:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access Denied: You are not associated with this workspace."
)
target_role = association.role
# 2. Issue new tokens for the new context
access_token = create_access_token(
subject=current_user.id,
workspace_id=target_workspace_id,
role=target_role
)
refresh_token = create_refresh_token(subject=current_user.id)
logger.info(f"User {current_user.email} switched to workspace {target_workspace_id}")
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@router.post("/logout/")
async def logout(
current_user: User = Depends(get_current_user),
token: str = Depends(oauth2_scheme)
) -> Any:
"""
Log out the current user by adding the token's JTI to the blocklist.
The token becomes immediately invalid and will be rejected by get_current_user().
"""
from jose import jwt as jwt_lib
from core.token_blocklist import blocklist_token
try:
payload = jwt_lib.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
jti = payload.get("jti")
exp = payload.get("exp")
if jti and exp:
import time
remaining_seconds = max(0, int(exp - time.time()))
await blocklist_token(jti, remaining_seconds)
logger.info(f"User {current_user.email} logged out (token revoked, TTL: {remaining_seconds}s)")
else:
# Legacy tokens without JTI — can't revoke, just acknowledge
logger.warning(f"User {current_user.email} logged out (legacy token without JTI, cannot revoke)")
except Exception as e:
logger.error(f"Logout token revocation error: {e}")
return {"message": "Successfully logged out"}
@router.post("/forgot-password/")
async def forgot_password(payload: ForgotPasswordRequest, db: AsyncSession = Depends(get_db)) -> Any:
"""
Initiate password reset.
Always returns 200 to prevent email enumeration attacks.
Uses a dedicated reset token type that cannot be used as an access token.
"""
# Verify user exists and is active (Case-insensitive)
stmt = select(User).where(
func.lower(User.email) == func.lower(payload.email),
User.deleted_at.is_(None)
)
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
logger.warning(f"Password reset requested for non-existent email: {payload.email}")
# Always return 200 to prevent email enumeration (Gap 1 fix)
return {"message": "If an account exists with this email, a password reset link has been sent."}
# Use dedicated reset token with type='reset' (Gap 2 fix)
reset_token = create_reset_token(subject=payload.email)
# TODO: In production, send this token via email service instead of returning it.
# For development/demo purposes, we still include the token in the response.
logger.info(f"Password reset token generated for {payload.email}")
return {
"message": "If an account exists with this email, a password reset link has been sent.",
"token": reset_token, # DEV ONLY — remove in production
"reset_token": reset_token # DEV ONLY — remove in production
}
@router.post("/reset-password/")
async def reset_password(
payload: ResetPasswordRequest,
db: AsyncSession = Depends(get_db)
) -> Any:
"""Reset password using a token."""
from jose import jwt, JWTError
from core.config import get_settings
settings = get_settings()
try:
try:
decoded_payload = jwt.decode(payload.token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
except JWTError:
raise HTTPException(status_code=400, detail="Invalid or expired reset token")
# Validate this is actually a reset token, not an access/refresh token (Gap 2 fix)
token_type = decoded_payload.get("type")
if token_type != "reset":
logger.warning(f"Password reset attempted with non-reset token (type={token_type})")
raise HTTPException(status_code=400, detail="Invalid reset token. Please request a new password reset.")
email: str = decoded_payload.get("sub")
if not email:
raise HTTPException(status_code=400, detail="Invalid token payload")
stmt = select(User).where(
func.lower(User.email) == func.lower(email),
User.deleted_at.is_(None)
)
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="User associated with this token no longer exists")
user.hashed_password = get_password_hash(payload.new_password)
db.add(user)
await db.commit()
logger.info(f"Password reset successful for {email}")
return {"message": "Password reset successful"}
except HTTPException:
raise
except Exception as e:
logger.error(f"Unexpected error during password reset: {e}")
raise HTTPException(status_code=500, detail="An internal error occurred during password reset")
@router.get("/me/", response_model=Any)
async def get_my_profile(current_user: User = Depends(get_current_user)) -> Any:
"""Get profile of the currently logged-in user."""
return {
"id": str(current_user.id),
"email": current_user.email,
"full_name": current_user.full_name,
"role": current_user.role,
"workspace_id": str(current_user.workspace_id)
}
|