Files
PROJECT-CONTORL/backend/app/middleware/auth.py
beabigegg 1fda7da2c2 feat: implement user authentication module
- Backend (FastAPI):
  - External API authentication (pj-auth-api.vercel.app)
  - JWT token validation with Redis session storage
  - RBAC with department isolation
  - User, Role, Department models with pjctrl_ prefix
  - Alembic migrations with project-specific version table
  - Complete test coverage (13 tests)

- Frontend (React + Vite):
  - AuthContext for state management
  - Login page with error handling
  - Protected route component
  - Dashboard with user info display

- OpenSpec:
  - 7 capability specs defined
  - add-user-auth change archived

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 23:41:37 +08:00

170 lines
4.8 KiB
Python

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from typing import Optional
from app.core.database import get_db
from app.core.security import decode_access_token
from app.core.redis import get_redis
from app.models.user import User
security = HTTPBearer()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db),
redis_client=Depends(get_redis),
) -> User:
"""
Dependency to get the current authenticated user.
Validates the JWT token and checks session in Redis.
"""
token = credentials.credentials
# Decode and verify token
payload = decode_access_token(token)
if payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
)
user_id = payload.get("sub")
if user_id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token payload",
headers={"WWW-Authenticate": "Bearer"},
)
# Check session in Redis
stored_token = redis_client.get(f"session:{user_id}")
if stored_token is None or stored_token != token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Session expired or invalid",
headers={"WWW-Authenticate": "Bearer"},
)
# Get user from database
user = db.query(User).filter(User.id == user_id).first()
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found",
headers={"WWW-Authenticate": "Bearer"},
)
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="User account is disabled",
)
return user
async def get_current_active_user(
current_user: User = Depends(get_current_user),
) -> User:
"""
Dependency to ensure user is active.
"""
if not current_user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Inactive user",
)
return current_user
def require_system_admin(
current_user: User = Depends(get_current_user),
) -> User:
"""
Dependency to require system admin privileges.
"""
if not current_user.is_system_admin:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="System admin privileges required",
)
return current_user
def require_permission(permission: str):
"""
Decorator factory to require specific permission.
Usage:
@router.get("/protected")
async def protected_route(user: User = Depends(require_permission("users.read"))):
...
"""
def permission_checker(current_user: User = Depends(get_current_user)) -> User:
# System admin has all permissions
if current_user.is_system_admin:
return current_user
# Check role permissions
if current_user.role is None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="No role assigned",
)
permissions = current_user.role.permissions or {}
# Check for "all" permission
if permissions.get("all"):
return current_user
# Check specific permission
if not permissions.get(permission):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission '{permission}' required",
)
return current_user
return permission_checker
def check_department_access(
user: User,
resource_department_id: Optional[str],
resource_security_level: str = "department",
) -> bool:
"""
Check if user has access to a resource based on department isolation.
Args:
user: The current user
resource_department_id: Department ID of the resource
resource_security_level: Security level ('public', 'department', 'confidential')
Returns:
bool: True if user has access, False otherwise
"""
# System admin bypasses department isolation
if user.is_system_admin:
return True
# Public resources are accessible to all
if resource_security_level == "public":
return True
# No department specified on resource means accessible to all
if resource_department_id is None:
return True
# User must be in the same department
if user.department_id == resource_department_id:
return True
return False