[docs]asyncdefget_current_user(request:Request)->Optional[Any]:""" Get the current authenticated user from the request state. Args: request: The FastAPI request object Returns: The user object if authenticated, None otherwise """ifhasattr(request.state,"user"):returnrequest.state.userreturnNone
[docs]asyncdefrequire_user(request:Request,redirect_to_login:bool=False)->Any:""" Dependency to require an authenticated user for a route. Args: request: The FastAPI request object redirect_to_login: If True, redirects to /login when not authenticated If False, raises an HTTPException with 401 status Returns: The user object if authenticated Raises: HTTPException: If the user is not authenticated (when redirect_to_login is False) RedirectResponse: If the user is not authenticated (when redirect_to_login is True) """user=awaitget_current_user(request)ifuserisNone:logger.warning(f"Unauthorized access attempt to {request.url.path}")ifredirect_to_login:returnRedirectResponse(url=f"/login?next={request.url.path}",status_code=302)else:raiseHTTPException(status_code=401,detail="Not authenticated",headers={"WWW-Authenticate":"Bearer"})returnuser
[docs]asyncdefrequire_admin(request:Request,redirect_to_login:bool=False)->Any:""" Dependency to require an authenticated admin user for a route. Args: request: The FastAPI request object redirect_to_login: If True, redirects to /login when not authenticated If False, raises an HTTPException with 401/403 status Returns: The user object if authenticated and has admin role Raises: HTTPException: If the user is not authenticated or lacks admin privileges RedirectResponse: If the user is not authenticated (when redirect_to_login is True) """user=awaitrequire_user(request,redirect_to_login)# Check if user is already a RedirectResponse (from require_user)ifisinstance(user,RedirectResponse):returnuserifnothasattr(user,"roles")or"admin"notinuser.roles:logger.warning(f"Unauthorized admin access attempt by {user.username} to {request.url.path}")ifredirect_to_login:returnRedirectResponse(url=f"/login?next={request.url.path}",status_code=302)else:raiseHTTPException(status_code=403,detail="Not authorized. Admin privileges required.")returnuser