Files
PROJECT-CONTORL/backend/app/middleware/auth.py
beabigegg daca7798e3 feat: implement task management module
Backend (FastAPI):
- Database migration for spaces, projects, task_statuses, tasks tables
- SQLAlchemy models with relationships
- Pydantic schemas for CRUD operations
- Spaces API: CRUD with soft delete
- Projects API: CRUD with auto-created default statuses
- Tasks API: CRUD, status change, assign, subtask support
- Permission middleware with Security Level filtering
- Subtask depth limit (max 2 levels)

Frontend (React + Vite):
- Layout component with navigation
- Spaces list page
- Projects list page
- Tasks list page with status management

Fixes:
- auth_client.py: use 'username' field for external API
- config.py: extend JWT expiry to 7 days
- auth/router.py: sync Redis session with JWT expiry

Tests: 36 passed (unit + integration)
E2E: All APIs verified with real authentication

OpenSpec: add-task-management archived

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 00:31:34 +08:00

274 lines
7.3 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
def check_space_access(user: User, space) -> bool:
"""
Check if user has access to a space.
Currently all active users can see all spaces.
Owner has edit/delete permissions.
"""
# System admin has full access
if user.is_system_admin:
return True
# All active users can view spaces
return True
def check_space_edit_access(user: User, space) -> bool:
"""
Check if user can edit/delete a space.
"""
# System admin has full access
if user.is_system_admin:
return True
# Only owner can edit
return space.owner_id == user.id
def check_project_access(user: User, project) -> bool:
"""
Check if user has access to a project based on security level.
Security Levels:
- public: All logged-in users
- department: Same department users + project owner
- confidential: Only project owner (+ system admin)
"""
# System admin bypasses all restrictions
if user.is_system_admin:
return True
# Project owner always has access
if project.owner_id == user.id:
return True
# Check by security level
security_level = project.security_level
if security_level == "public":
return True
elif security_level == "department":
# Same department has access
if project.department_id and user.department_id == project.department_id:
return True
return False
else: # confidential
# Only owner has access (already checked above)
return False
def check_project_edit_access(user: User, project) -> bool:
"""
Check if user can edit/delete a project.
"""
# System admin has full access
if user.is_system_admin:
return True
# Only owner can edit
return project.owner_id == user.id
def check_task_access(user: User, task, project) -> bool:
"""
Check if user has access to a task.
Task access is based on project access.
"""
return check_project_access(user, project)
def check_task_edit_access(user: User, task, project) -> bool:
"""
Check if user can edit a task.
"""
# System admin has full access
if user.is_system_admin:
return True
# Project owner can edit all tasks
if project.owner_id == user.id:
return True
# Task creator can edit their own tasks
if task.created_by == user.id:
return True
# Assignee can edit their assigned tasks
if task.assignee_id == user.id:
return True
return False