asmaakbar commited on
Commit
35cd1bc
·
1 Parent(s): c091657
Files changed (48) hide show
  1. .gitignore +55 -0
  2. Dockerfile +25 -0
  3. docs/readme.md +64 -0
  4. docs/security.md +104 -0
  5. requirements.txt +14 -0
  6. src/api/__init__.py +5 -0
  7. src/api/decorators.py +61 -0
  8. src/api/deps.py +72 -0
  9. src/api/main.py +98 -0
  10. src/api/mcp_server.py +224 -0
  11. src/api/routes/__init__.py +5 -0
  12. src/api/routes/auth.py +638 -0
  13. src/api/routes/chat.py +581 -0
  14. src/api/routes/tasks.py +293 -0
  15. src/config.py +33 -0
  16. src/database/__init__.py +5 -0
  17. src/database/database.py +139 -0
  18. src/database/migrate.py +80 -0
  19. src/middleware/auth.py +128 -0
  20. src/middleware/chat_auth.py +82 -0
  21. src/middleware/security.py +74 -0
  22. src/models/__init__.py +27 -0
  23. src/models/conversation.py +37 -0
  24. src/models/error.py +20 -0
  25. src/models/error_response.py +45 -0
  26. src/models/message.py +46 -0
  27. src/models/session.py +30 -0
  28. src/models/task.py +40 -0
  29. src/models/user.py +42 -0
  30. src/services/__init__.py +5 -0
  31. src/services/ai_service.py +234 -0
  32. src/services/auth_service.py +235 -0
  33. src/services/conversation_service.py +150 -0
  34. src/services/task_service.py +249 -0
  35. src/services/user_service.py +116 -0
  36. src/utils/__init__.py +5 -0
  37. src/utils/date_validator.py +123 -0
  38. src/utils/error_handlers.py +152 -0
  39. src/utils/jwt_utils.py +58 -0
  40. src/utils/logger.py +97 -0
  41. tests/__init__.py +5 -0
  42. tests/conftest.py +32 -0
  43. tests/contract/test_api_contracts.py +110 -0
  44. tests/integration/test_task_endpoints.py +62 -0
  45. tests/test_auth_api.py +247 -0
  46. tests/test_auth_service.py +177 -0
  47. tests/unit/test_error_handlers.py +172 -0
  48. tests/unit/test_task_model.py +83 -0
.gitignore ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual Environment
24
+ venv/
25
+ env/
26
+ ENV/
27
+ env.bak/
28
+ venv.bak/
29
+
30
+ # Database
31
+ *.db
32
+ todo_app.db
33
+ *.db-journal
34
+
35
+ # Local development settings
36
+ .env
37
+ .env.local
38
+ .env.backup
39
+ .env.dev
40
+ .env.production
41
+ .env.staging
42
+ .env.test
43
+ .env.local
44
+ .env.shared
45
+
46
+ # IDE
47
+ .vscode/
48
+ .idea/
49
+ *.swp
50
+ *.swo
51
+ *~
52
+
53
+ # OS
54
+ .DS_Store
55
+ Thumbs.db
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Create non-root user for security
6
+ RUN useradd --create-home --shell /bin/bash app && chown -R app:app /app
7
+ USER app
8
+
9
+ # Copy requirements first to leverage Docker cache
10
+ COPY --chown=app:app requirements.txt .
11
+
12
+ # Install dependencies
13
+ RUN pip install --no-cache-dir --user -r requirements.txt
14
+
15
+ # Copy the rest of the application
16
+ COPY --chown=app:app . .
17
+
18
+ # Set environment variables (update these with actual values in production)
19
+ ENV PYTHONPATH=/app
20
+
21
+ # Expose port
22
+ EXPOSE 8000
23
+
24
+ # Run the application with uvicorn
25
+ CMD ["python", "-m", "uvicorn", "src.api.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
docs/readme.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Todo Backend API Documentation
2
+
3
+ ## Overview
4
+ The Todo Backend API is a secure, RESTful API built with FastAPI for managing personal tasks. It provides endpoints for creating, reading, updating, and deleting tasks with strict user-based access controls.
5
+
6
+ ## Features
7
+ - JWT-based authentication
8
+ - User isolation - users can only access their own tasks
9
+ - Comprehensive error handling
10
+ - Async database operations with SQLModel
11
+ - Full CRUD operations for tasks
12
+
13
+ ## Getting Started
14
+
15
+ ### Prerequisites
16
+ - Python 3.11+
17
+ - Poetry (recommended) or pip
18
+ - PostgreSQL database
19
+
20
+ ### Installation
21
+ 1. Clone the repository
22
+ 2. Install dependencies: `poetry install` or `pip install -r requirements.txt`
23
+ 3. Set up environment variables (see .env.example)
24
+ 4. Run database migrations: `alembic upgrade head`
25
+ 5. Start the server: `uvicorn backend.src.api.main:app --reload`
26
+
27
+ ### Environment Variables
28
+ - `DATABASE_URL`: Database connection string
29
+ - `BETTER_AUTH_SECRET`: Secret key for JWT token signing
30
+ - `DEBUG`: Enable/disable debug mode
31
+
32
+ ## API Endpoints
33
+
34
+ ### Authentication
35
+ All endpoints require JWT authentication in the Authorization header:
36
+ ```
37
+ Authorization: Bearer <jwt_token>
38
+ ```
39
+
40
+ ### Tasks
41
+ - `GET /api/tasks` - Get all tasks for the authenticated user
42
+ - `POST /api/tasks` - Create a new task
43
+ - `GET /api/tasks/{task_id}` - Get a specific task
44
+ - `PUT /api/tasks/{task_id}` - Update a specific task
45
+ - `DELETE /api/tasks/{task_id}` - Delete a specific task
46
+ - `PATCH /api/tasks/{task_id}/toggle` - Toggle task completion status
47
+
48
+ ## Error Handling
49
+ All errors follow the standard format:
50
+ ```json
51
+ {
52
+ "success": false,
53
+ "error": {
54
+ "code": "ERROR_CODE",
55
+ "message": "Human-readable error message"
56
+ }
57
+ }
58
+ ```
59
+
60
+ ## Security
61
+ - All endpoints require authentication
62
+ - Users can only access their own tasks
63
+ - Input validation on all endpoints
64
+ - Secure JWT token handling
docs/security.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Documentation: Todo Web App
2
+
3
+ ## JWT Authentication
4
+
5
+ ### Overview
6
+ The application uses JWT (JSON Web Tokens) for stateless authentication. All API requests require a valid JWT token in the Authorization header.
7
+
8
+ ### Token Structure
9
+ - Algorithm: HS256
10
+ - Payload includes:
11
+ - `sub`: User ID (subject)
12
+ - `exp`: Expiration timestamp
13
+ - `iat`: Issued at timestamp
14
+
15
+ ### Configuration
16
+ - Environment variable: `BETTER_AUTH_SECRET`
17
+ - Expiration time: 30 minutes (configurable in settings)
18
+ - Algorithm: HS256
19
+
20
+ ### Token Lifecycle
21
+ 1. User authenticates with credentials
22
+ 2. Server generates JWT with user ID as subject
23
+ 3. Token is returned to client and stored securely
24
+ 4. Client includes token in Authorization header for all requests
25
+ 5. Server validates token signature and expiration
26
+ 6. Token grants access to user-specific resources only
27
+
28
+ ## Authorization & Access Control
29
+
30
+ ### Task Ownership
31
+ - Each task is associated with a specific user via `user_id`
32
+ - Users can only access, modify, or delete their own tasks
33
+ - Attempts to access other users' tasks result in 401 Unauthorized
34
+
35
+ ### API Endpoints Protection
36
+ All API endpoints require valid authentication except:
37
+ - `/api/auth/login` - for authentication
38
+ - `/api/auth/register` - for registration
39
+ - `/api/health` - for health checks
40
+
41
+ ## Session Management
42
+
43
+ ### Client-Side
44
+ - Tokens stored in localStorage (production apps should consider HttpOnly cookies)
45
+ - Token expiration checked before requests
46
+ - Automatic logout on 401 responses
47
+ - Redirect to login page after session expiration
48
+
49
+ ### Security Headers
50
+ - All API responses include appropriate security headers
51
+ - CORS configured for allowed origins only
52
+ - Content Security Policy implemented
53
+
54
+ ## Error Handling
55
+
56
+ ### 401 Unauthorized Scenarios
57
+ - Missing Authorization header
58
+ - Invalid JWT token format
59
+ - Expired JWT token
60
+ - Tampered JWT token
61
+ - User account deactivated
62
+
63
+ ### Response Format
64
+ ```json
65
+ {
66
+ "success": false,
67
+ "error": {
68
+ "code": "AUTH_001",
69
+ "message": "Could not validate credentials"
70
+ }
71
+ }
72
+ ```
73
+
74
+ ## Best Practices
75
+
76
+ ### For Developers
77
+ 1. Always validate user ownership before performing operations
78
+ 2. Sanitize and validate all inputs
79
+ 3. Use parameterized queries to prevent SQL injection
80
+ 4. Log security-relevant events appropriately
81
+ 5. Never expose sensitive data in error messages
82
+
83
+ ### For Operations
84
+ 1. Rotate JWT secrets regularly
85
+ 2. Monitor authentication failure logs
86
+ 3. Implement rate limiting for auth endpoints
87
+ 4. Use HTTPS in all environments
88
+ 5. Regular security audits of dependencies
89
+
90
+ ## Environment Variables
91
+
92
+ Required environment variables for security:
93
+ - `BETTER_AUTH_SECRET`: Secret key for JWT signing (minimum 32 characters)
94
+ - `DATABASE_URL`: Secure database connection string
95
+ - `DATABASE_ECHO`: Set to "False" in production
96
+
97
+ ## Compliance
98
+
99
+ This implementation follows industry-standard security practices:
100
+ - OWASP Top 10 compliance
101
+ - Statelessness of JWT tokens
102
+ - Proper error handling without information disclosure
103
+ - Input validation and sanitization
104
+ - Principle of least privilege for access control
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ sqlmodel
3
+ uvicorn[standard]
4
+ python-multipart
5
+ python-jose[cryptography]
6
+ passlib[bcrypt]
7
+ python-dotenv
8
+ pydantic
9
+ pydantic-settings
10
+ SQLAlchemy
11
+ aiosqlite
12
+ psycopg2-binary
13
+ openai
14
+ mcp
src/api/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ API package for the Todo Backend API.
3
+
4
+ Contains the main FastAPI application and route definitions.
5
+ """
src/api/decorators.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ from typing import Callable, Any
3
+ from fastapi import HTTPException, status, Depends
4
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
5
+
6
+ from .deps import get_current_user
7
+ from ..models.user import UserRead
8
+
9
+ security = HTTPBearer()
10
+
11
+ def require_auth(func: Callable) -> Callable:
12
+ """
13
+ Decorator to require authentication for API endpoints.
14
+
15
+ This decorator ensures that the user is authenticated before allowing access to the endpoint.
16
+ It uses the get_current_user dependency to validate the JWT token.
17
+ """
18
+ @wraps(func)
19
+ async def wrapper(*args, **kwargs):
20
+ # The get_current_user dependency will automatically validate the token
21
+ # and raise an HTTPException if the token is invalid
22
+ current_user: UserRead = kwargs.get('current_user') or args[-1] # Assuming current_user is passed as a param
23
+
24
+ # If we reach this point, the user is authenticated
25
+ return await func(*args, **kwargs)
26
+
27
+ # Add the dependency to the wrapper function
28
+ wrapper.__annotations__['current_user'] = UserRead
29
+ wrapper.__defaults__ = (Depends(get_current_user),)
30
+
31
+ return wrapper
32
+
33
+ def auth_required():
34
+ """
35
+ Alternative decorator to require authentication for API endpoints.
36
+
37
+ This is a more explicit way to add authentication to routes.
38
+ """
39
+ def decorator(func: Callable) -> Callable:
40
+ @wraps(func)
41
+ async def wrapper(*args, **kwargs):
42
+ return await func(*args, **kwargs)
43
+
44
+ # Inject the dependency
45
+ if 'current_user' not in func.__annotations__:
46
+ func.__annotations__['current_user'] = UserRead
47
+ if 'current_user' not in kwargs:
48
+ kwargs['current_user'] = Depends(get_current_user)
49
+
50
+ return wrapper
51
+ return decorator
52
+
53
+ # Alternative implementation that works better with FastAPI's dependency injection
54
+ def get_auth_dependency():
55
+ """
56
+ Helper function to get the authentication dependency.
57
+
58
+ This can be used in route definitions like:
59
+ @router.get("/protected", dependencies=[Depends(get_auth_dependency())])
60
+ """
61
+ return Depends(get_current_user)
src/api/deps.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Depends, HTTPException, status
2
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
3
+ from typing import Optional
4
+ from sqlmodel import select
5
+ from datetime import datetime
6
+
7
+ from ..utils.jwt_utils import decode_access_token
8
+ from ..models.user import User, UserRead
9
+ from ..database.database import get_async_session
10
+ from sqlmodel.ext.asyncio.session import AsyncSession
11
+
12
+ security = HTTPBearer()
13
+
14
+
15
+ async def get_current_user(
16
+ credentials: HTTPAuthorizationCredentials = Depends(security),
17
+ session: AsyncSession = Depends(get_async_session)
18
+ ) -> UserRead:
19
+ """
20
+ Dependency to get the current authenticated user from the JWT token.
21
+
22
+ Args:
23
+ credentials: HTTP authorization credentials from the request
24
+ session: Async database session
25
+
26
+ Returns:
27
+ UserRead object if token is valid and user exists
28
+
29
+ Raises:
30
+ HTTPException: If token is invalid, expired, or user doesn't exist
31
+ """
32
+ credentials_exception = HTTPException(
33
+ status_code=status.HTTP_401_UNAUTHORIZED,
34
+ detail="Could not validate credentials",
35
+ headers={"WWW-Authenticate": "Bearer"},
36
+ )
37
+
38
+ token = credentials.credentials
39
+
40
+ payload = decode_access_token(token)
41
+ if payload is None:
42
+ raise credentials_exception
43
+
44
+ user_id: Optional[str] = payload.get("sub")
45
+ if user_id is None:
46
+ raise credentials_exception
47
+
48
+ # Fetch the user from the database
49
+ user = await session.get(User, int(user_id))
50
+ if user is None:
51
+ raise credentials_exception
52
+
53
+ # Create UserRead object manually to ensure required fields are present
54
+ # This handles potential issues with datetime fields being None
55
+ from datetime import datetime
56
+ created_at = user.created_at or datetime.utcnow()
57
+ updated_at = user.updated_at or datetime.utcnow()
58
+
59
+ # Generate username if not set (for response only, not database update)
60
+ username = user.username or f"{user.email.split('@')[0]}_{int(datetime.utcnow().timestamp())}"
61
+
62
+ return UserRead(
63
+ id=user.id,
64
+ email=user.email,
65
+ username=username,
66
+ name=user.name,
67
+ date_of_birth=user.date_of_birth,
68
+ signup_date=user.signup_date,
69
+ force_password_change=user.force_password_change,
70
+ created_at=created_at,
71
+ updated_at=updated_at
72
+ )
src/api/main.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import asynccontextmanager
2
+ from typing import AsyncGenerator
3
+ import logging
4
+
5
+ from fastapi import FastAPI
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+
8
+ from .routes.tasks import router as tasks_router
9
+ from .routes.auth import router as auth_router
10
+ from .routes.chat import router as chat_router
11
+ from .mcp_server import server as mcp_server
12
+ from ..config import settings
13
+ from ..utils.error_handlers import add_exception_handlers
14
+ from ..middleware.security import SecurityHeadersMiddleware
15
+
16
+ # Reduce SQLAlchemy logging to reduce noise
17
+ logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
18
+ logging.getLogger('sqlalchemy.dialects').setLevel(logging.WARNING)
19
+ logging.getLogger('sqlalchemy.pool').setLevel(logging.WARNING)
20
+ logging.getLogger('sqlalchemy.orm').setLevel(logging.WARNING)
21
+
22
+
23
+ @asynccontextmanager
24
+ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
25
+ """
26
+ Lifespan event handler for FastAPI application.
27
+
28
+ Handles startup and shutdown events.
29
+ """
30
+ # Startup
31
+ print("Starting up Todo Backend API...")
32
+
33
+ # Add exception handlers
34
+ add_exception_handlers(app)
35
+
36
+ yield
37
+
38
+ # Shutdown
39
+ print("Shutting down Todo Backend API...")
40
+
41
+
42
+ def create_app() -> FastAPI:
43
+ """
44
+ Create and configure the FastAPI application.
45
+
46
+ Returns:
47
+ Configured FastAPI application instance
48
+ """
49
+ app = FastAPI(
50
+ title=settings.app_name,
51
+ debug=settings.debug,
52
+ lifespan=lifespan
53
+ )
54
+
55
+ # Add security headers middleware first
56
+ app.add_middleware(SecurityHeadersMiddleware)
57
+
58
+ # Add CORS middleware
59
+ app.add_middleware(
60
+ CORSMiddleware,
61
+ allow_origins=[
62
+ "http://localhost:3000",
63
+ "http://127.0.0.1:3000",
64
+ "http://localhost:3001",
65
+ "http://127.0.0.1:3001",
66
+ ],
67
+ allow_credentials=True,
68
+ allow_methods=["*"],
69
+ allow_headers=["*"],
70
+ )
71
+
72
+ # Include API routes
73
+ app.include_router(tasks_router, prefix=settings.api_prefix)
74
+ app.include_router(auth_router, prefix=settings.api_prefix)
75
+ app.include_router(chat_router, prefix=settings.api_prefix)
76
+
77
+ @app.get("/")
78
+ async def root():
79
+ """Root endpoint for the API."""
80
+ return {
81
+ "message": "Welcome to the Todo Backend API",
82
+ "app_name": settings.app_name,
83
+ "version": "1.0.0"
84
+ }
85
+
86
+ return app
87
+
88
+
89
+ app = create_app()
90
+
91
+ if __name__ == "__main__":
92
+ import uvicorn
93
+ uvicorn.run(
94
+ "src.api.main:app",
95
+ host="0.0.0.0",
96
+ port=8000,
97
+ reload=True
98
+ )
src/api/mcp_server.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP (Model Context Protocol) Server Implementation for the Todo Backend API.
3
+
4
+ Implements the MCP server with 5 task management tools using the Official MCP SDK.
5
+ """
6
+ from mcp.server import Server
7
+ from mcp.types import CallToolResult, Tool
8
+ from typing import Dict, Any, List
9
+ import json
10
+ from sqlmodel import create_engine, Session
11
+ from sqlmodel.ext.asyncio.session import AsyncSession
12
+ from contextlib import asynccontextmanager
13
+
14
+ from ..models.user import UserRead
15
+ from ..services.task_service import TaskService
16
+ from ..services.ai_service import ai_service
17
+
18
+
19
+ # Create the MCP server instance
20
+ server = Server("todo-mcp-server")
21
+
22
+
23
+
24
+
25
+ @server.list_tools()
26
+ async def list_tools() -> List[Tool]:
27
+ """List all available tools in the MCP server."""
28
+ return [
29
+ Tool(
30
+ name="add_task",
31
+ description="Create a new task",
32
+ input_schema={
33
+ "type": "object",
34
+ "properties": {
35
+ "user_id": {"type": "string", "description": "User identifier"},
36
+ "title": {"type": "string", "description": "Task title"},
37
+ "description": {"type": "string", "description": "Task description (optional)"}
38
+ },
39
+ "required": ["user_id", "title"]
40
+ }
41
+ ),
42
+ Tool(
43
+ name="list_tasks",
44
+ description="Retrieve tasks from the list",
45
+ input_schema={
46
+ "type": "object",
47
+ "properties": {
48
+ "user_id": {"type": "string", "description": "User identifier"},
49
+ "status": {"type": "string", "enum": ["all", "pending", "completed"], "description": "Filter by status"}
50
+ },
51
+ "required": ["user_id"]
52
+ }
53
+ ),
54
+ Tool(
55
+ name="complete_task",
56
+ description="Mark a task as complete",
57
+ input_schema={
58
+ "type": "object",
59
+ "properties": {
60
+ "user_id": {"type": "string", "description": "User identifier"},
61
+ "task_id": {"type": "integer", "description": "Task ID to complete"}
62
+ },
63
+ "required": ["user_id", "task_id"]
64
+ }
65
+ ),
66
+ Tool(
67
+ name="delete_task",
68
+ description="Remove a task from the list",
69
+ input_schema={
70
+ "type": "object",
71
+ "properties": {
72
+ "user_id": {"type": "string", "description": "User identifier"},
73
+ "task_id": {"type": "integer", "description": "Task ID to delete"}
74
+ },
75
+ "required": ["user_id", "task_id"]
76
+ }
77
+ ),
78
+ Tool(
79
+ name="update_task",
80
+ description="Modify task title or description",
81
+ input_schema={
82
+ "type": "object",
83
+ "properties": {
84
+ "user_id": {"type": "string", "description": "User identifier"},
85
+ "task_id": {"type": "integer", "description": "Task ID to update"},
86
+ "title": {"type": "string", "description": "New title (optional)"},
87
+ "description": {"type": "string", "description": "New description (optional)"}
88
+ },
89
+ "required": ["user_id", "task_id"]
90
+ }
91
+ )
92
+ ]
93
+
94
+
95
+ @server.call_tool()
96
+ async def call_tool(name: str, arguments: Dict[str, Any]) -> CallToolResult:
97
+ """
98
+ Handle tool calls from the MCP server.
99
+
100
+ Args:
101
+ name: Name of the tool to call
102
+ arguments: Arguments to pass to the tool
103
+
104
+ Returns:
105
+ Result of the tool call
106
+ """
107
+ try:
108
+ # Extract user_id from arguments
109
+ user_id = int(arguments.get("user_id"))
110
+
111
+ # Create a mock user object for compatibility with existing services
112
+ # In a real implementation, you would fetch the user from the database
113
+ current_user = UserRead(
114
+ id=user_id,
115
+ email=f"user_{user_id}@example.com" # Placeholder email
116
+ )
117
+
118
+ # Get the database session - in a real implementation, you would get this properly
119
+ # For now, we'll use the AI service which handles the database operations
120
+ if name == "add_task":
121
+ title = arguments.get("title")
122
+ description = arguments.get("description")
123
+
124
+ # Using the AI service's method for consistency
125
+ result = await ai_service.add_task_tool(
126
+ title=title,
127
+ description=description,
128
+ user=current_user,
129
+ session=None # Will be handled internally
130
+ )
131
+
132
+ return CallToolResult(content=json.dumps(result))
133
+
134
+ elif name == "list_tasks":
135
+ status = arguments.get("status", "all")
136
+
137
+ # Using the AI service's method for consistency
138
+ result = await ai_service.list_tasks_tool(
139
+ user=current_user,
140
+ session=None # Will be handled internally
141
+ )
142
+
143
+ # Filter results based on status if needed
144
+ if status != "all" and "tasks" in result:
145
+ if status == "pending":
146
+ result["tasks"] = [task for task in result["tasks"] if not task.get("completed")]
147
+ elif status == "completed":
148
+ result["tasks"] = [task for task in result["tasks"] if task.get("completed")]
149
+
150
+ return CallToolResult(content=json.dumps(result))
151
+
152
+ elif name == "complete_task":
153
+ task_id = arguments.get("task_id")
154
+
155
+ # Using the AI service's method for consistency
156
+ result = await ai_service.complete_task_tool(
157
+ task_id=task_id,
158
+ user=current_user,
159
+ session=None # Will be handled internally
160
+ )
161
+
162
+ return CallToolResult(content=json.dumps(result))
163
+
164
+ elif name == "delete_task":
165
+ task_id = arguments.get("task_id")
166
+
167
+ # Using the AI service's method for consistency
168
+ result = await ai_service.delete_task_tool(
169
+ task_id=task_id,
170
+ user=current_user,
171
+ session=None # Will be handled internally
172
+ )
173
+
174
+ return CallToolResult(content=json.dumps(result))
175
+
176
+ elif name == "update_task":
177
+ task_id = arguments.get("task_id")
178
+ title = arguments.get("title")
179
+ description = arguments.get("description")
180
+
181
+ # Using the AI service's method for consistency
182
+ result = await ai_service.update_task_tool(
183
+ task_id=task_id,
184
+ title=title,
185
+ description=description,
186
+ user=current_user,
187
+ session=None # Will be handled internally
188
+ )
189
+
190
+ return CallToolResult(content=json.dumps(result))
191
+
192
+ else:
193
+ return CallToolResult(
194
+ content=json.dumps({
195
+ "success": False,
196
+ "error": f"Unknown tool: {name}",
197
+ "message": f"Tool '{name}' not found"
198
+ })
199
+ )
200
+
201
+ except Exception as e:
202
+ return CallToolResult(
203
+ content=json.dumps({
204
+ "success": False,
205
+ "error": str(e),
206
+ "message": f"Error executing tool {name}: {str(e)}"
207
+ })
208
+ )
209
+
210
+
211
+ # For standalone execution
212
+ if __name__ == "__main__":
213
+ import asyncio
214
+ import argparse
215
+
216
+ parser = argparse.ArgumentParser(description="Run the Todo MCP Server")
217
+ parser.add_argument("--port", type=int, default=3000, help="Port to run the server on")
218
+ args = parser.parse_args()
219
+
220
+ async def main():
221
+ # Start the server
222
+ await server.run(port=args.port)
223
+
224
+ asyncio.run(main())
src/api/routes/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ Routes package for the Todo Backend API.
3
+
4
+ Contains all API route definitions.
5
+ """
src/api/routes/auth.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status
2
+ from fastapi.security import HTTPBearer
3
+ from typing import Optional
4
+ from datetime import timedelta, datetime
5
+ from sqlmodel import select
6
+ from pydantic import BaseModel
7
+
8
+ from ...models.user import User, UserCreate, UserRead
9
+ from ...services.auth_service import AuthService, AuthException
10
+ from ...database.database import get_async_session
11
+ from sqlmodel.ext.asyncio.session import AsyncSession
12
+ from ...utils.jwt_utils import create_access_token, decode_access_token, get_password_hash, verify_password
13
+ from ...config import settings
14
+ from ...utils.date_validator import validate_signup_date
15
+ from ..deps import get_current_user
16
+
17
+ router = APIRouter(prefix="/auth", tags=["auth"])
18
+
19
+ # Initialize the auth service
20
+ auth_service = AuthService()
21
+
22
+ class SignupRequest(BaseModel):
23
+ email: str
24
+ password: str
25
+ name: Optional[str] = None
26
+ date_of_birth: Optional[str] = None
27
+ signup_date: Optional[str] = None # Allow client to send signup date (will be validated and potentially overridden)
28
+
29
+ class SigninRequest(BaseModel):
30
+ email: str
31
+ password: str
32
+
33
+ class ErrorResponse(BaseModel):
34
+ error: str
35
+ message: str
36
+
37
+ @router.post("/signup", response_model=dict, responses={
38
+ 400: {"model": ErrorResponse, "description": "Invalid request format or validation error"},
39
+ 409: {"model": ErrorResponse, "description": "Email already exists"}
40
+ })
41
+ async def signup_user(
42
+ signup_request: SignupRequest,
43
+ session: AsyncSession = Depends(get_async_session)
44
+ ):
45
+ """
46
+ Create new user account with signup date validation.
47
+ """
48
+ try:
49
+ # Validate and set signup date
50
+ validated_signup_date = validate_signup_date(signup_request.signup_date)
51
+
52
+ # Hash the password before storing
53
+ hashed_password = get_password_hash(signup_request.password)
54
+
55
+ # Generate a username based on the email if not already set
56
+ from datetime import datetime
57
+ generated_username = f"{signup_request.email.split('@')[0]}_{int(datetime.utcnow().timestamp())}"
58
+
59
+ # Create new user with signup date validation
60
+ db_user = User(
61
+ email=signup_request.email,
62
+ username=generated_username,
63
+ password=hashed_password,
64
+ name=signup_request.name,
65
+ date_of_birth=signup_request.date_of_birth,
66
+ signup_date=validated_signup_date # Non-nullable field, enforced here
67
+ )
68
+ session.add(db_user)
69
+ await session.commit()
70
+ await session.refresh(db_user)
71
+
72
+ # Create access token
73
+ access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
74
+ access_token = create_access_token(
75
+ data={"sub": str(db_user.id)}, expires_delta=access_token_expires
76
+ )
77
+
78
+ return {
79
+ "success": True,
80
+ "data": {
81
+ "user": UserRead.model_validate(db_user),
82
+ "access_token": access_token,
83
+ "token_type": "bearer"
84
+ }
85
+ }
86
+ except HTTPException:
87
+ raise
88
+ except Exception as e:
89
+ raise HTTPException(
90
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
91
+ detail=f"Signup failed: {str(e)}"
92
+ )
93
+
94
+ @router.post("/signin", response_model=dict, responses={
95
+ 400: {"model": ErrorResponse, "description": "Invalid request format"},
96
+ 401: {"model": ErrorResponse, "description": "Authentication failed"}
97
+ })
98
+ async def signin_user(
99
+ signin_request: SigninRequest,
100
+ session: AsyncSession = Depends(get_async_session)
101
+ ):
102
+ """
103
+ Authenticate user with enhanced error handling to differentiate between email and password errors.
104
+ """
105
+ try:
106
+ # Find user by email using async session
107
+ statement = select(User).where(User.email == signin_request.email)
108
+ result = await session.execute(statement)
109
+ user = result.scalar_one_or_none()
110
+
111
+ if user is None:
112
+ raise HTTPException(
113
+ status_code=status.HTTP_401_UNAUTHORIZED,
114
+ detail="Invalid email or password"
115
+ )
116
+
117
+ # Ensure username exists (for existing users that might not have it set)
118
+ if not user.username:
119
+ from datetime import datetime
120
+ user.username = f"{user.email.split('@')[0]}_{int(datetime.utcnow().timestamp())}"
121
+ await session.commit()
122
+
123
+ # Verify password using async-compatible code
124
+ from passlib.context import CryptContext
125
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
126
+
127
+ if not pwd_context.verify(signin_request.password, user.password):
128
+ raise HTTPException(
129
+ status_code=status.HTTP_401_UNAUTHORIZED,
130
+ detail="Invalid email or password"
131
+ )
132
+
133
+ # Create access token
134
+ from datetime import timedelta
135
+ from ...utils.jwt_utils import create_access_token
136
+ from ...config import settings
137
+ access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
138
+ access_token = create_access_token(
139
+ data={"sub": str(user.id)}, expires_delta=access_token_expires
140
+ )
141
+
142
+ return {
143
+ "success": True,
144
+ "data": {
145
+ "user": UserRead.model_validate(user),
146
+ "access_token": access_token,
147
+ "token_type": "bearer"
148
+ }
149
+ }
150
+ except HTTPException:
151
+ raise
152
+ except Exception as e:
153
+ raise HTTPException(
154
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
155
+ detail=f"Signin failed: {str(e)}"
156
+ )
157
+
158
+
159
+ class LoginRequest(BaseModel):
160
+ email: str
161
+ password: str
162
+
163
+ class ForgotPasswordRequest(BaseModel):
164
+ email: str
165
+ date_of_birth: str # Format: YYYY-MM-DD
166
+
167
+ @router.post("/forgot-password", response_model=dict)
168
+ async def forgot_password(
169
+ request_data: ForgotPasswordRequest,
170
+ session: AsyncSession = Depends(get_async_session)
171
+ ):
172
+ """
173
+ Verify user identity using email and date of birth for password reset.
174
+ """
175
+ try:
176
+ # Find user by email
177
+ statement = select(User).where(User.email == request_data.email)
178
+ result = await session.execute(statement)
179
+ user = result.scalar_one_or_none()
180
+
181
+ if not user:
182
+ # Return the same error message even if email doesn't exist to prevent email enumeration
183
+ raise HTTPException(
184
+ status_code=status.HTTP_404_NOT_FOUND,
185
+ detail="If an account with that email exists, a password reset link has been sent."
186
+ )
187
+
188
+ # Verify the date of birth matches
189
+ print(f"DEBUG: Looking up user by email: {request_data.email}")
190
+ print(f"DEBUG: Found user date_of_birth: {user.date_of_birth} (type: {type(user.date_of_birth)})")
191
+
192
+ if not user.date_of_birth:
193
+ print(f"DEBUG: User has no date of birth set in database")
194
+ raise HTTPException(
195
+ status_code=status.HTTP_400_BAD_REQUEST,
196
+ detail="Date of birth verification failed. Please contact support."
197
+ )
198
+
199
+ # Parse the provided date of birth
200
+ from datetime import datetime
201
+ try:
202
+ provided_dob = datetime.strptime(request_data.date_of_birth, '%Y-%m-%d')
203
+ except ValueError:
204
+ raise HTTPException(
205
+ status_code=status.HTTP_400_BAD_REQUEST,
206
+ detail="Invalid date format. Please use YYYY-MM-DD format."
207
+ )
208
+
209
+ # Compare dates (ignoring time component)
210
+ print(f"DEBUG: Comparing user.date_of_birth: {user.date_of_birth} with provided: {provided_dob.date()}")
211
+
212
+ if user.date_of_birth != provided_dob.date(): # Both should be date objects now
213
+ raise HTTPException(
214
+ status_code=status.HTTP_400_BAD_REQUEST,
215
+ detail="Date of birth verification failed. Please check your date of birth and try again."
216
+ )
217
+
218
+ # In a real app, you'd send a password reset link to the user's email
219
+ # For demo purposes, we'll just return success
220
+
221
+ return {
222
+ "success": True,
223
+ "data": {
224
+ "message": "Identity verified successfully. Please set your new password.",
225
+ "email": request_data.email
226
+ }
227
+ }
228
+ except HTTPException:
229
+ raise
230
+ except Exception as e:
231
+ raise HTTPException(
232
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
233
+ detail=f"Forgot password request failed: {str(e)}"
234
+ )
235
+
236
+
237
+ class SetNewPasswordRequest(BaseModel):
238
+ email: str
239
+ new_password: str
240
+
241
+ @router.post("/set-new-password", response_model=dict)
242
+ async def set_new_password(
243
+ request_data: SetNewPasswordRequest,
244
+ session: AsyncSession = Depends(get_async_session)
245
+ ):
246
+ """
247
+ Set new password after successful verification.
248
+ """
249
+ try:
250
+ # Find user by email
251
+ statement = select(User).where(User.email == request_data.email)
252
+ result = await session.execute(statement)
253
+ user = result.scalar_one_or_none()
254
+
255
+ if not user:
256
+ raise HTTPException(
257
+ status_code=status.HTTP_404_NOT_FOUND,
258
+ detail="User not found"
259
+ )
260
+
261
+ # Hash the new password before storing
262
+ hashed_new_password = get_password_hash(request_data.new_password)
263
+ user.password = hashed_new_password
264
+ user.updated_at = datetime.utcnow()
265
+
266
+ session.add(user)
267
+ await session.commit()
268
+
269
+ return {
270
+ "success": True,
271
+ "data": {
272
+ "message": "Password changed successfully"
273
+ }
274
+ }
275
+ except HTTPException:
276
+ raise
277
+ except Exception as e:
278
+ raise HTTPException(
279
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
280
+ detail=f"Password change failed: {str(e)}"
281
+ )
282
+
283
+
284
+ class ResetPasswordRequest(BaseModel):
285
+ email: str
286
+ new_password: str
287
+
288
+ @router.post("/reset-password", response_model=dict)
289
+ async def reset_password(
290
+ request_data: ResetPasswordRequest,
291
+ session: AsyncSession = Depends(get_async_session)
292
+ ):
293
+ """
294
+ Reset user password directly (for admin or special cases).
295
+ """
296
+ try:
297
+ # Find user by email
298
+ statement = select(User).where(User.email == request_data.email)
299
+ result = await session.execute(statement)
300
+ user = result.scalar_one_or_none()
301
+
302
+ if not user:
303
+ raise HTTPException(
304
+ status_code=status.HTTP_404_NOT_FOUND,
305
+ detail="User not found"
306
+ )
307
+
308
+ # Hash the new password before storing
309
+ hashed_new_password = get_password_hash(request_data.new_password)
310
+ user.password = hashed_new_password
311
+ user.updated_at = datetime.utcnow()
312
+
313
+ session.add(user)
314
+ await session.commit()
315
+
316
+ return {
317
+ "success": True,
318
+ "data": {
319
+ "message": "Password reset successfully"
320
+ }
321
+ }
322
+ except HTTPException:
323
+ raise
324
+ except Exception as e:
325
+ raise HTTPException(
326
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
327
+ detail=f"Password reset failed: {str(e)}"
328
+ )
329
+
330
+
331
+ class ChangePasswordRequest(BaseModel):
332
+ current_password: str
333
+ new_password: str
334
+
335
+ @router.post("/change-password", response_model=dict)
336
+ async def change_password(
337
+ request_data: ChangePasswordRequest,
338
+ current_user: UserRead = Depends(get_current_user),
339
+ session: AsyncSession = Depends(get_async_session)
340
+ ):
341
+ """
342
+ Change user's current password after verifying the current password.
343
+ """
344
+ try:
345
+ # Verify the current password
346
+ statement = select(User).where(User.id == current_user.id)
347
+ result = await session.execute(statement)
348
+ user = result.scalar_one_or_none()
349
+
350
+ if not user:
351
+ raise HTTPException(
352
+ status_code=status.HTTP_404_NOT_FOUND,
353
+ detail="User not found"
354
+ )
355
+
356
+ # Verify the provided current password against the stored hash
357
+ if not verify_password(request_data.current_password, user.password):
358
+ raise HTTPException(
359
+ status_code=status.HTTP_400_BAD_REQUEST,
360
+ detail="Current password is incorrect"
361
+ )
362
+
363
+ # Hash the new password before storing
364
+ hashed_new_password = get_password_hash(request_data.new_password)
365
+ user.password = hashed_new_password
366
+ user.updated_at = datetime.utcnow()
367
+
368
+ # Reset the force_password_change flag if set
369
+ user.force_password_change = False
370
+
371
+ session.add(user)
372
+ await session.commit()
373
+
374
+ return {
375
+ "success": True,
376
+ "data": {
377
+ "message": "Password changed successfully"
378
+ }
379
+ }
380
+ except HTTPException:
381
+ raise
382
+ except Exception as e:
383
+ raise HTTPException(
384
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
385
+ detail=f"Password change failed: {str(e)}"
386
+ )
387
+
388
+
389
+ @router.post("/token", response_model=dict)
390
+ async def login_for_access_token(
391
+ login_request: LoginRequest,
392
+ session: AsyncSession = Depends(get_async_session)
393
+ ):
394
+ """
395
+ OAuth2 compatible token login, get an access token for future requests.
396
+ """
397
+ try:
398
+ # Find user by email
399
+ statement = select(User).where(User.email == login_request.email)
400
+ result = await session.execute(statement)
401
+ user = result.scalar_one_or_none()
402
+
403
+ if not user:
404
+ raise HTTPException(
405
+ status_code=status.HTTP_401_UNAUTHORIZED,
406
+ detail="Incorrect email or password",
407
+ headers={"WWW-Authenticate": "Bearer"},
408
+ )
409
+
410
+ # Verify the provided password against the stored hash
411
+ if not verify_password(login_request.password, user.password):
412
+ raise HTTPException(
413
+ status_code=status.HTTP_401_UNAUTHORIZED,
414
+ detail="Incorrect email or password",
415
+ headers={"WWW-Authenticate": "Bearer"},
416
+ )
417
+
418
+ # Create access token
419
+ access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
420
+ access_token = create_access_token(
421
+ data={"sub": str(user.id)}, expires_delta=access_token_expires
422
+ )
423
+
424
+ return {
425
+ "access_token": access_token,
426
+ "token_type": "bearer",
427
+ "user": UserRead.model_validate(user)
428
+ }
429
+ except HTTPException:
430
+ raise
431
+ except Exception as e:
432
+ raise HTTPException(
433
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
434
+ detail=f"Token creation failed: {str(e)}"
435
+ )
436
+
437
+
438
+ # Also add a test endpoint that doesn't require auth to verify the token works
439
+ @router.get("/test-token", response_model=dict)
440
+ async def test_token():
441
+ """
442
+ Test endpoint to verify authentication is working.
443
+ """
444
+ return {
445
+ "message": "Token is valid!",
446
+ "success": True
447
+ }
448
+
449
+
450
+ @router.post("/register", response_model=dict)
451
+ async def register_user(
452
+ user_create: UserCreate,
453
+ session: AsyncSession = Depends(get_async_session)
454
+ ):
455
+ """
456
+ Register a new user.
457
+ """
458
+ try:
459
+ # Check if user already exists
460
+ existing_user_statement = select(User).where(User.email == user_create.email)
461
+ existing_user_result = await session.execute(existing_user_statement)
462
+ existing_user = existing_user_result.scalar_one_or_none()
463
+
464
+ if existing_user:
465
+ raise HTTPException(
466
+ status_code=status.HTTP_400_BAD_REQUEST,
467
+ detail="User with this email already exists"
468
+ )
469
+
470
+ # Hash the password before storing
471
+ hashed_password = get_password_hash(user_create.password)
472
+
473
+ # Create new user with hashed password, optional name and date of birth
474
+ from datetime import datetime, date
475
+ date_of_birth_obj = None
476
+
477
+ # Generate a username if not provided in the request (e.g., based on email)
478
+ generated_username = user_create.username or f"{user_create.email.split('@')[0]}_{int(datetime.utcnow().timestamp())}"
479
+
480
+ # Debug: Print incoming date of birth for troubleshooting
481
+ print(f"DEBUG: Incoming date_of_birth value: {user_create.date_of_birth}, type: {type(user_create.date_of_birth)}")
482
+
483
+ # Handle date of birth conversion - supports string, date, or datetime objects
484
+ if user_create.date_of_birth is not None:
485
+ dob_input = user_create.date_of_birth
486
+
487
+ print(f"DEBUG: Processing date of birth input: {dob_input}, type: {type(dob_input)}")
488
+
489
+ if isinstance(dob_input, str):
490
+ # Handle string input - strip whitespace and parse
491
+ dob_str = dob_input.strip()
492
+ print(f"DEBUG: String date stripped: '{dob_str}'")
493
+ if dob_str: # Only process if not empty after stripping
494
+ try:
495
+ # Parse string to date object (to match database schema)
496
+ date_of_birth_obj = datetime.strptime(dob_str, '%Y-%m-%d').date()
497
+ print(f"DEBUG: Successfully parsed date: {date_of_birth_obj}")
498
+ except ValueError as e:
499
+ # Handle invalid date format
500
+ print(f"Date of birth parsing error: {e}")
501
+ raise HTTPException(
502
+ status_code=status.HTTP_400_BAD_REQUEST,
503
+ detail="Invalid date of birth format. Please use YYYY-MM-DD format."
504
+ )
505
+ elif isinstance(dob_input, date):
506
+ # If it's already a date object, use it as is
507
+ date_of_birth_obj = dob_input
508
+ print(f"DEBUG: Using date object directly: {date_of_birth_obj}")
509
+ elif isinstance(dob_input, datetime):
510
+ # If it's a datetime object, convert to date to match database schema
511
+ date_of_birth_obj = dob_input.date()
512
+ print(f"DEBUG: Converted datetime to date: {date_of_birth_obj}")
513
+ else:
514
+ print("DEBUG: No date of birth provided in request")
515
+
516
+ print(f"DEBUG: Final date_of_birth_obj value: {date_of_birth_obj}")
517
+
518
+ # Use current time as signup_date if not provided in the request
519
+ current_time = datetime.utcnow()
520
+
521
+ db_user = User(
522
+ email=user_create.email,
523
+ username=generated_username,
524
+ password=hashed_password,
525
+ name=user_create.name,
526
+ date_of_birth=date_of_birth_obj,
527
+ signup_date=current_time, # Non-nullable field, enforced here
528
+ force_password_change=False # New users don't need to change password immediately
529
+ )
530
+ session.add(db_user)
531
+ await session.commit()
532
+ await session.refresh(db_user)
533
+
534
+ # Additional debug: Check what was actually saved
535
+ print(f"DEBUG: User saved with date_of_birth: {db_user.date_of_birth}, signup_date: {db_user.signup_date}")
536
+
537
+ # Create access token
538
+ access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
539
+ access_token = create_access_token(
540
+ data={"sub": str(db_user.id)}, expires_delta=access_token_expires
541
+ )
542
+
543
+ return {
544
+ "success": True,
545
+ "data": {
546
+ "user": UserRead.model_validate(db_user),
547
+ "access_token": access_token,
548
+ "token_type": "bearer"
549
+ }
550
+ }
551
+ except HTTPException:
552
+ raise
553
+ except Exception as e:
554
+ raise HTTPException(
555
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
556
+ detail=f"Registration failed: {str(e)}"
557
+ )
558
+
559
+
560
+ @router.post("/login", response_model=dict)
561
+ async def login_user(
562
+ login_request: LoginRequest,
563
+ session: AsyncSession = Depends(get_async_session)
564
+ ):
565
+ """
566
+ Authenticate user and return access token.
567
+ """
568
+ try:
569
+ # Find user by email
570
+ statement = select(User).where(User.email == login_request.email)
571
+ result = await session.execute(statement)
572
+ user = result.scalar_one_or_none()
573
+
574
+ if not user:
575
+ raise HTTPException(
576
+ status_code=status.HTTP_401_UNAUTHORIZED,
577
+ detail="Invalid email or password"
578
+ )
579
+
580
+ # Ensure username exists (for existing users that might not have it set)
581
+ if not user.username:
582
+ from datetime import datetime
583
+ user.username = f"{user.email.split('@')[0]}_{int(datetime.utcnow().timestamp())}"
584
+ await session.commit()
585
+
586
+ # Verify the provided password against the stored hash
587
+ if not verify_password(login_request.password, user.password):
588
+ raise HTTPException(
589
+ status_code=status.HTTP_401_UNAUTHORIZED,
590
+ detail="Invalid email or password"
591
+ )
592
+
593
+ # Create access token
594
+ access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
595
+ access_token = create_access_token(
596
+ data={"sub": str(user.id)}, expires_delta=access_token_expires
597
+ )
598
+
599
+ return {
600
+ "success": True,
601
+ "data": {
602
+ "user": UserRead.model_validate(user),
603
+ "access_token": access_token,
604
+ "token_type": "bearer"
605
+ }
606
+ }
607
+ except HTTPException:
608
+ raise
609
+ except Exception as e:
610
+ raise HTTPException(
611
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
612
+ detail=f"Login failed: {str(e)}"
613
+ )
614
+
615
+
616
+ @router.post("/logout", response_model=dict)
617
+ async def logout_user():
618
+ """
619
+ Logout endpoint to invalidate session (for future implementation).
620
+ Currently just returns success, but can be extended to handle server-side session invalidation.
621
+ """
622
+ return {
623
+ "success": True,
624
+ "message": "Logged out successfully"
625
+ }
626
+
627
+
628
+ @router.get("/me", response_model=dict)
629
+ async def get_current_user_info(
630
+ current_user: UserRead = Depends(get_current_user)
631
+ ):
632
+ """
633
+ Get current authenticated user's information.
634
+ """
635
+ return {
636
+ "success": True,
637
+ "user": current_user
638
+ }
src/api/routes/chat.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chat API routes for the Todo Backend API.
3
+
4
+ Implements the chat endpoint using FastAPI.
5
+ """
6
+ import re
7
+ from typing import Optional, Dict, Any
8
+ from fastapi import APIRouter, Depends, HTTPException, status
9
+ from sqlmodel.ext.asyncio.session import AsyncSession
10
+ from pydantic import BaseModel
11
+
12
+ from ...models.user import UserRead
13
+ from ...models.conversation import Conversation, ConversationCreate
14
+ from ...models.message import Message, MessageCreate, MessageRole
15
+ from ...services.conversation_service import ConversationService
16
+ from ...services.ai_service import ai_service
17
+ from ...database.database import get_async_session
18
+ from ...middleware.chat_auth import chat_auth
19
+
20
+
21
+ router = APIRouter(prefix="/chat", tags=["chat"])
22
+
23
+
24
+ class ChatRequest(BaseModel):
25
+ """Request model for chat endpoint."""
26
+ message: str
27
+ conversation_id: Optional[int] = None
28
+
29
+
30
+ class ChatResponse(BaseModel):
31
+ """Response model for chat endpoint."""
32
+ success: bool
33
+ data: Dict[str, Any]
34
+
35
+
36
+ @router.post("/{user_id}/chat", response_model=ChatResponse)
37
+ async def chat_with_ai(
38
+ user_id: str, # The user ID from the path parameter
39
+ chat_request: ChatRequest,
40
+ session: AsyncSession = Depends(get_async_session)
41
+ ):
42
+ """
43
+ Process natural language input from user and return AI-generated response with appropriate task operations.
44
+
45
+ Args:
46
+ user_id: ID of the authenticated user (from JWT token via path)
47
+ chat_request: Chat request containing message and optional conversation_id
48
+ session: Async database session
49
+
50
+ Returns:
51
+ Dictionary containing AI response and any actions taken
52
+ """
53
+ try:
54
+ # In this implementation, the user_id from the path is expected to be a string representation
55
+ # of the database user ID. For example, if the database user ID is 1, it would come as "1".
56
+ # We validate that the user exists in the database.
57
+ try:
58
+ user_id_int = int(user_id) # Convert the path user_id to int to match database ID
59
+ from sqlmodel import select
60
+ from ...models.user import User, UserRead
61
+
62
+ user_statement = select(User).where(User.id == user_id_int)
63
+ user_result = await session.execute(user_statement)
64
+ db_user = user_result.scalar_one_or_none()
65
+
66
+ if not db_user:
67
+ raise HTTPException(
68
+ status_code=status.HTTP_404_NOT_FOUND,
69
+ detail="User not found"
70
+ )
71
+
72
+ current_user = UserRead.model_validate(db_user)
73
+ except ValueError:
74
+ # If user_id is not a numeric string, then it's invalid
75
+ raise HTTPException(
76
+ status_code=status.HTTP_404_NOT_FOUND,
77
+ detail="Invalid user ID format"
78
+ )
79
+
80
+
81
+ # Get or create conversation
82
+ if chat_request.conversation_id:
83
+ # Load existing conversation
84
+ conversation = await ConversationService.get_conversation_by_id(
85
+ session, chat_request.conversation_id, user_id_int
86
+ )
87
+ if not conversation:
88
+ raise HTTPException(
89
+ status_code=status.HTTP_404_NOT_FOUND,
90
+ detail="Conversation not found"
91
+ )
92
+ else:
93
+ # Create new conversation
94
+ conversation_data = ConversationCreate(title=chat_request.message[:50] + "..." if len(chat_request.message) > 50 else chat_request.message, user_id=str(user_id_int))
95
+ conversation = await ConversationService.create_conversation(session, conversation_data)
96
+
97
+ # Save user message to conversation
98
+ user_message = MessageCreate(
99
+ role=MessageRole.USER,
100
+ content=chat_request.message,
101
+ conversation_id=conversation.id,
102
+ user_id=str(user_id_int) # Convert to string to match database schema
103
+ )
104
+ await ConversationService.add_message_to_conversation(session, user_message)
105
+
106
+ # Process the message with AI service
107
+ # In a real implementation, we would use the OpenAI Agent to determine
108
+ # which MCP tools to call based on the user's natural language
109
+ # For this implementation, we'll simulate natural language processing
110
+
111
+ # Get the previous messages to understand the context
112
+ # At this point, the current user message has already been added to the conversation
113
+ # So we need to get all messages and exclude the current one
114
+ all_messages = await ConversationService.get_messages_by_conversation_id(session, conversation.id)
115
+
116
+ # Filter out the current user message that was just added
117
+ # We identify it by matching both content and role
118
+ previous_messages = [
119
+ msg for msg in all_messages
120
+ if not (msg.content == chat_request.message and msg.role == MessageRole.USER)
121
+ ]
122
+
123
+ # Check if the user is replying to a specific prompt (like after choosing option 1 to add a task)
124
+ if previous_messages:
125
+ last_assistant_msg = None
126
+ # Find the last assistant message before the current user message
127
+ for msg in reversed(previous_messages):
128
+ if msg.role == MessageRole.ASSISTANT:
129
+ last_assistant_msg = msg
130
+ break
131
+
132
+ # If the last assistant message was asking for a task title (after option 1)
133
+ if last_assistant_msg and ("provide the task title" in last_assistant_msg.content.lower() or
134
+ "add your task now" in last_assistant_msg.content.lower()):
135
+ # This means the user is now providing the task title
136
+ task_title = chat_request.message.strip()
137
+
138
+ # Call the add_task_tool
139
+ result = await ai_service.add_task_tool(task_title, current_user, session, description=None)
140
+ if result["success"]:
141
+ ai_response = f"Task added: {result['message']}"
142
+ actions_taken = [{
143
+ "action": "task_created",
144
+ "task_id": result["task_id"],
145
+ "details": result["message"]
146
+ }]
147
+ else:
148
+ ai_response = f"Failed to add task: {result['message']}"
149
+
150
+ # If the last assistant message was asking to select a task to complete
151
+ elif last_assistant_msg and "mark as complete" in last_assistant_msg.content.lower():
152
+ # Extract task ID from user's response
153
+ import re
154
+ task_id_match = re.search(r'\b(\d+)\b', chat_request.message)
155
+ if task_id_match:
156
+ task_id = int(task_id_match.group(1))
157
+ # Call the complete_task_tool
158
+ result = await ai_service.complete_task_tool(task_id, current_user, session)
159
+ if result["success"]:
160
+ status_text = "completed" if result["completed"] else "marked as incomplete"
161
+ ai_response = result["message"]
162
+ actions_taken = [{
163
+ "action": "task_completed",
164
+ "task_id": task_id,
165
+ "details": f"Task {status_text}"
166
+ }]
167
+ else:
168
+ ai_response = f"Failed to complete task: {result['message']}"
169
+ else:
170
+ ai_response = "Invalid task number. Please select a valid task number from the list."
171
+
172
+
173
+ # If the last assistant message was asking to select a task to delete
174
+ elif last_assistant_msg and "delete" in last_assistant_msg.content.lower():
175
+ # Extract task ID from user's response
176
+ import re
177
+ task_id_match = re.search(r'\b(\d+)\b', chat_request.message)
178
+ if task_id_match:
179
+ task_id = int(task_id_match.group(1))
180
+ # Call the delete_task_tool
181
+ result = await ai_service.delete_task_tool(task_id, current_user, session)
182
+ if result["success"]:
183
+ ai_response = result["message"]
184
+ actions_taken = [{
185
+ "action": "task_deleted",
186
+ "task_id": task_id,
187
+ "details": result["message"]
188
+ }]
189
+ else:
190
+ ai_response = f"Failed to delete task: {result['message']}"
191
+ else:
192
+ ai_response = "Invalid task number. Please select a valid task number from the list."
193
+
194
+ # If none of the above conditions matched, process as normal
195
+ else:
196
+ # Analyze the user's message to determine intent
197
+ actions_taken = []
198
+ ai_response = ""
199
+
200
+ # Simple keyword-based intent detection (would be replaced with proper NLP in production)
201
+ message_lower = chat_request.message.lower()
202
+
203
+ if any(word in message_lower for word in ["add", "create", "new task", "make"]):
204
+ # Extract task title from message (simple extraction)
205
+ task_title = chat_request.message.replace("Add", "").replace("add", "").replace("Create", "").replace("create", "").strip()
206
+ if task_title.startswith("a task to ") or task_title.startswith("a task that "):
207
+ task_title = task_title[10:].strip()
208
+ elif task_title.startswith("to "):
209
+ task_title = task_title[3:].strip()
210
+
211
+ # Call the add_task_tool
212
+ result = await ai_service.add_task_tool(task_title, current_user, session, description=None)
213
+ if result["success"]:
214
+ ai_response = f"Task added: {result['message']}"
215
+ actions_taken = [{
216
+ "action": "task_created",
217
+ "task_id": result["task_id"],
218
+ "details": result["message"]
219
+ }]
220
+ else:
221
+ ai_response = f"Failed to add task: {result['message']}"
222
+
223
+ elif any(word in message_lower for word in ["list", "show", "display", "my tasks", "get"]):
224
+ # Call the list_tasks_tool
225
+ result = await ai_service.list_tasks_tool(current_user, session)
226
+ if result["success"]:
227
+ task_list = [f"- {task['title']} ({'✓' if task['completed'] else '○'})" for task in result["tasks"]]
228
+ ai_response = f"Here are your tasks:\n" + "\n".join(task_list) if task_list else "You have no tasks."
229
+ actions_taken = [{
230
+ "action": "tasks_listed",
231
+ "count": result["count"],
232
+ "details": f"Listed {result['count']} tasks"
233
+ }]
234
+ else:
235
+ ai_response = f"Failed to list tasks: {result['message']}"
236
+
237
+ elif any(word in message_lower for word in ["update", "change", "modify"]):
238
+ # Simple implementation - would need more sophisticated parsing in production
239
+ ai_response = "Task update functionality would be implemented here with proper NLP parsing."
240
+
241
+ elif any(word in message_lower for word in ["delete", "remove"]):
242
+ # Extract task ID from message if specified
243
+ import re
244
+ task_id_match = re.search(r'\b(\d+)\b', chat_request.message)
245
+ if task_id_match:
246
+ task_id = int(task_id_match.group(1))
247
+ # Call the delete_task_tool
248
+ result = await ai_service.delete_task_tool(task_id, current_user, session)
249
+ if result["success"]:
250
+ ai_response = result["message"]
251
+ actions_taken = [{
252
+ "action": "task_deleted",
253
+ "task_id": task_id,
254
+ "details": result["message"]
255
+ }]
256
+ else:
257
+ ai_response = f"Failed to delete task: {result['message']}"
258
+ else:
259
+ ai_response = "Please specify a task ID to delete. Example: 'Delete task 1' or 'Remove task 5'."
260
+
261
+ elif any(word in message_lower for word in ["complete", "done", "finish", "mark as"]):
262
+ # Extract task ID from message if specified
263
+ import re
264
+ task_id_match = re.search(r'\b(\d+)\b', chat_request.message)
265
+ if task_id_match:
266
+ task_id = int(task_id_match.group(1))
267
+ # Call the complete_task_tool
268
+ result = await ai_service.complete_task_tool(task_id, current_user, session)
269
+ if result["success"]:
270
+ status_text = "completed" if result["completed"] else "marked as incomplete"
271
+ ai_response = result["message"]
272
+ actions_taken = [{
273
+ "action": "task_completed",
274
+ "task_id": task_id,
275
+ "details": f"Task {status_text}"
276
+ }]
277
+ else:
278
+ ai_response = f"Failed to complete task: {result['message']}"
279
+ else:
280
+ ai_response = "Please specify a task ID to mark as complete. Example: 'Complete task 1' or 'Mark task 3 as done'."
281
+
282
+ else:
283
+ # Check if the user is initiating a conversation or asking for help
284
+ message_lower = chat_request.message.lower()
285
+ if any(greeting in message_lower for greeting in ["hello", "hi", "hey", "chat", "help", "start"]):
286
+ ai_response = "Hello! I'm your AI Task Assistant. How can I help you today?\n\n" \
287
+ "Select an option:\n" \
288
+ "1. Add task\n" \
289
+ "2. List tasks\n" \
290
+ "3. Mark as complete\n" \
291
+ "4. Delete task\n\n" \
292
+ "Enter the number of your choice (1-4)"
293
+ # Handle numeric inputs for menu selection
294
+ elif message_lower == "1":
295
+ ai_response = "Add your task now. Please provide the task title:"
296
+ elif message_lower == "2":
297
+ # Call the list_tasks_tool
298
+ result = await ai_service.list_tasks_tool(current_user, session)
299
+ if result["success"]:
300
+ if result["tasks"]:
301
+ task_list = [f"{i+1}. {task['title']} ({'✓' if task['completed'] else '○'})" for i, task in enumerate(result["tasks"])]
302
+ ai_response = "Your tasks:\n" + "\n".join(task_list)
303
+ else:
304
+ ai_response = "You have no tasks."
305
+ else:
306
+ ai_response = f"Failed to list tasks: {result['message']}"
307
+ elif message_lower == "3":
308
+ # First list tasks so user knows which ones to complete
309
+ result = await ai_service.list_tasks_tool(current_user, session)
310
+ if result["success"]:
311
+ if result["tasks"]:
312
+ task_list = [f"{task['id']}. {task['title']} ({'✓' if task['completed'] else '○'})" for task in result["tasks"]]
313
+ ai_response = "Which task would you like to mark as complete? Select the task number:\n" + "\n".join(task_list) + "\n\nReply with the task number (e.g., '1' to complete the first task)"
314
+ else:
315
+ ai_response = "You have no tasks to complete."
316
+ else:
317
+ ai_response = f"Failed to list tasks: {result['message']}"
318
+ elif message_lower == "4":
319
+ # First list tasks so user knows which ones to delete
320
+ result = await ai_service.list_tasks_tool(current_user, session)
321
+ if result["success"]:
322
+ if result["tasks"]:
323
+ task_list = [f"{task['id']}. {task['title']} ({'✓' if task['completed'] else '○'})" for task in result["tasks"]]
324
+ ai_response = "Which task would you like to delete? Select the task number:\n" + "\n".join(task_list) + "\n\nReply with the task number (e.g., '1' to delete the first task)"
325
+ else:
326
+ ai_response = "You have no tasks to delete."
327
+ else:
328
+ ai_response = f"Failed to list tasks: {result['message']}"
329
+ else:
330
+ # Default response for unrecognized commands
331
+ ai_response = f"I received your message: '{chat_request.message}'. I can help you manage your tasks. Type 'hello' for options."
332
+ else:
333
+ # This is the first message in the conversation
334
+ # Analyze the user's message to determine intent
335
+ actions_taken = []
336
+ ai_response = ""
337
+
338
+ # Simple keyword-based intent detection (would be replaced with proper NLP in production)
339
+ message_lower = chat_request.message.lower()
340
+
341
+ if any(word in message_lower for word in ["add", "create", "new task", "make"]):
342
+ # Extract task title from message (simple extraction)
343
+ task_title = chat_request.message.replace("Add", "").replace("add", "").replace("Create", "").replace("create", "").strip()
344
+ if task_title.startswith("a task to ") or task_title.startswith("a task that "):
345
+ task_title = task_title[10:].strip()
346
+ elif task_title.startswith("to "):
347
+ task_title = task_title[3:].strip()
348
+
349
+ # Call the add_task_tool
350
+ result = await ai_service.add_task_tool(task_title, current_user, session, description=None)
351
+ if result["success"]:
352
+ ai_response = f"Task added: {result['message']}"
353
+ actions_taken = [{
354
+ "action": "task_created",
355
+ "task_id": result["task_id"],
356
+ "details": result["message"]
357
+ }]
358
+ else:
359
+ ai_response = f"Failed to add task: {result['message']}"
360
+
361
+ elif any(word in message_lower for word in ["list", "show", "display", "my tasks", "get"]):
362
+ # Call the list_tasks_tool
363
+ result = await ai_service.list_tasks_tool(current_user, session)
364
+ if result["success"]:
365
+ task_list = [f"- {task['title']} ({'✓' if task['completed'] else '○'})" for task in result["tasks"]]
366
+ ai_response = f"Here are your tasks:\n" + "\n".join(task_list) if task_list else "You have no tasks."
367
+ actions_taken = [{
368
+ "action": "tasks_listed",
369
+ "count": result["count"],
370
+ "details": f"Listed {result['count']} tasks"
371
+ }]
372
+ else:
373
+ ai_response = f"Failed to list tasks: {result['message']}"
374
+
375
+ elif any(word in message_lower for word in ["update", "change", "modify"]):
376
+ # Simple implementation - would need more sophisticated parsing in production
377
+ ai_response = "Task update functionality would be implemented here with proper NLP parsing."
378
+
379
+ elif any(word in message_lower for word in ["delete", "remove"]):
380
+ # Extract task ID from message if specified
381
+ import re
382
+ task_id_match = re.search(r'\b(\d+)\b', chat_request.message)
383
+ if task_id_match:
384
+ task_id = int(task_id_match.group(1))
385
+ # Call the delete_task_tool
386
+ result = await ai_service.delete_task_tool(task_id, current_user, session)
387
+ if result["success"]:
388
+ ai_response = result["message"]
389
+ actions_taken = [{
390
+ "action": "task_deleted",
391
+ "task_id": task_id,
392
+ "details": result["message"]
393
+ }]
394
+ else:
395
+ ai_response = f"Failed to delete task: {result['message']}"
396
+ else:
397
+ ai_response = "Please specify a task ID to delete. Example: 'Delete task 1' or 'Remove task 5'."
398
+
399
+ elif any(word in message_lower for word in ["complete", "done", "finish", "mark as"]):
400
+ # Extract task ID from message if specified
401
+ import re
402
+ task_id_match = re.search(r'\b(\d+)\b', chat_request.message)
403
+ if task_id_match:
404
+ task_id = int(task_id_match.group(1))
405
+ # Call the complete_task_tool
406
+ result = await ai_service.complete_task_tool(task_id, current_user, session)
407
+ if result["success"]:
408
+ status_text = "completed" if result["completed"] else "marked as incomplete"
409
+ ai_response = result["message"]
410
+ actions_taken = [{
411
+ "action": "task_completed",
412
+ "task_id": task_id,
413
+ "details": f"Task {status_text}"
414
+ }]
415
+ else:
416
+ ai_response = f"Failed to complete task: {result['message']}"
417
+ else:
418
+ ai_response = "Please specify a task ID to mark as complete. Example: 'Complete task 1' or 'Mark task 3 as done'."
419
+
420
+ else:
421
+ # Check if the user is initiating a conversation or asking for help
422
+ message_lower = chat_request.message.lower()
423
+ if any(greeting in message_lower for greeting in ["hello", "hi", "hey", "chat", "help", "start"]):
424
+ ai_response = "Hello! I'm your AI Task Assistant. How can I help you today?\n\n" \
425
+ "Select an option:\n" \
426
+ "1. Add task\n" \
427
+ "2. List tasks\n" \
428
+ "3. Mark as complete\n" \
429
+ "4. Delete task\n\n" \
430
+ "Enter the number of your choice (1-4)"
431
+ # Handle numeric inputs for menu selection
432
+ elif message_lower == "1":
433
+ ai_response = "Add your task now. Please provide the task title.\n\nExample: 'Buy groceries' or 'Finish project report'"
434
+ elif message_lower == "2":
435
+ # Call the list_tasks_tool
436
+ result = await ai_service.list_tasks_tool(current_user, session)
437
+ if result["success"]:
438
+ if result["tasks"]:
439
+ task_list = [f"{i+1}. {task['title']} ({'✓' if task['completed'] else '○'})" for i, task in enumerate(result["tasks"])]
440
+ ai_response = "Your tasks:\n" + "\n".join(task_list)
441
+ else:
442
+ ai_response = "You have no tasks."
443
+ else:
444
+ ai_response = f"Failed to list tasks: {result['message']}"
445
+ elif message_lower == "3":
446
+ # First list tasks so user knows which ones to complete
447
+ result = await ai_service.list_tasks_tool(current_user, session)
448
+ if result["success"]:
449
+ if result["tasks"]:
450
+ task_list = [f"{task['id']}. {task['title']} ({'✓' if task['completed'] else '○'})" for task in result["tasks"]]
451
+ ai_response = "Which task would you like to mark as complete? Select the task number:\n" + "\n".join(task_list) + "\n\nReply with the task number (e.g., '1' to complete the first task)\n\nExample: Reply with '1' to mark the first task as complete"
452
+ else:
453
+ ai_response = "You have no tasks to complete."
454
+ else:
455
+ ai_response = f"Failed to list tasks: {result['message']}"
456
+ elif message_lower == "4":
457
+ # First list tasks so user knows which ones to delete
458
+ result = await ai_service.list_tasks_tool(current_user, session)
459
+ if result["success"]:
460
+ if result["tasks"]:
461
+ task_list = [f"{task['id']}. {task['title']} ({'✓' if task['completed'] else '○'})" for task in result["tasks"]]
462
+ ai_response = "Which task would you like to delete? Select the task number:\n" + "\n".join(task_list) + "\n\nReply with the task number (e.g., '1' to delete the first task)\n\nExample: Reply with '1' to delete the first task"
463
+ else:
464
+ ai_response = "You have no tasks to delete."
465
+ else:
466
+ ai_response = f"Failed to list tasks: {result['message']}"
467
+ else:
468
+ # Default response for unrecognized commands
469
+ ai_response = f"I received your message: '{chat_request.message}'. I can help you manage your tasks. Type 'hello' for options."
470
+
471
+ # Save AI response to conversation
472
+ ai_message = MessageCreate(
473
+ role=MessageRole.ASSISTANT,
474
+ content=ai_response,
475
+ conversation_id=conversation.id,
476
+ user_id=str(user_id_int) # Convert to string to match database schema
477
+ )
478
+ await ConversationService.add_message_to_conversation(session, ai_message)
479
+
480
+ return {
481
+ "success": True,
482
+ "data": {
483
+ "response": ai_response,
484
+ "conversation_id": conversation.id,
485
+ "actions_taken": actions_taken
486
+ }
487
+ }
488
+ except HTTPException:
489
+ # Re-raise HTTP exceptions as-is
490
+ raise
491
+ except Exception as e:
492
+ raise HTTPException(
493
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
494
+ detail=f"Chat processing failed: {str(e)}"
495
+ )
496
+
497
+
498
+ @router.get("/{user_id}/conversations")
499
+ async def get_user_conversations(
500
+ user_id: str, # The user ID from the path parameter
501
+ session: AsyncSession = Depends(get_async_session)
502
+ ):
503
+ """
504
+ Retrieve list of conversation summaries for the authenticated user.
505
+
506
+ Args:
507
+ user_id: ID of the authenticated user
508
+ session: Async database session
509
+
510
+ Returns:
511
+ Dictionary containing list of conversations
512
+ """
513
+ try:
514
+ # Convert the path user_id to int to match database ID
515
+ user_id_int = int(user_id)
516
+ conversations = await ConversationService.get_conversations_by_user_id(session, user_id_int)
517
+
518
+ return {
519
+ "success": True,
520
+ "data": {
521
+ "conversations": [conv.model_dump() for conv in conversations],
522
+ "total": len(conversations)
523
+ }
524
+ }
525
+ except Exception as e:
526
+ raise HTTPException(
527
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
528
+ detail=f"Failed to retrieve conversations: {str(e)}"
529
+ )
530
+
531
+
532
+ @router.get("/{user_id}/conversations/{conversation_id}")
533
+ async def get_conversation_history(
534
+ user_id: str, # Changed from int to str to match path parameter format
535
+ conversation_id: int,
536
+ session: AsyncSession = Depends(get_async_session)
537
+ ):
538
+ """
539
+ Retrieve full conversation history with messages.
540
+
541
+ Args:
542
+ user_id: ID of the authenticated user
543
+ conversation_id: ID of the conversation to retrieve
544
+ session: Async database session
545
+
546
+ Returns:
547
+ Dictionary containing conversation details with messages
548
+ """
549
+ try:
550
+ # Convert the path user_id to int to match database ID
551
+ user_id_int = int(user_id)
552
+ conversation = await ConversationService.get_conversation_by_id(session, conversation_id, user_id_int)
553
+
554
+ if not conversation:
555
+ raise HTTPException(
556
+ status_code=status.HTTP_404_NOT_FOUND,
557
+ detail="Conversation not found"
558
+ )
559
+
560
+ messages = await ConversationService.get_messages_by_conversation_id(session, conversation_id)
561
+
562
+ return {
563
+ "success": True,
564
+ "data": {
565
+ "conversation": {
566
+ "id": conversation.id,
567
+ "title": conversation.title,
568
+ "created_at": conversation.created_at,
569
+ "updated_at": conversation.updated_at,
570
+ "messages": [msg.model_dump() for msg in messages]
571
+ }
572
+ }
573
+ }
574
+ except HTTPException:
575
+ # Re-raise HTTP exceptions as-is
576
+ raise
577
+ except Exception as e:
578
+ raise HTTPException(
579
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
580
+ detail=f"Failed to retrieve conversation history: {str(e)}"
581
+ )
src/api/routes/tasks.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from fastapi import APIRouter, Depends, HTTPException, status
4
+
5
+ from ...models.task import TaskCreate, TaskRead, TaskUpdate
6
+ from ...services.task_service import TaskService
7
+ from ..deps import get_current_user
8
+ from ...models.user import UserRead
9
+ from ...database.database import get_async_session
10
+ from sqlmodel.ext.asyncio.session import AsyncSession
11
+
12
+ router = APIRouter(prefix="/tasks", tags=["tasks"])
13
+
14
+
15
+ @router.get("/", response_model=dict)
16
+ async def get_tasks(
17
+ current_user: UserRead = Depends(get_current_user),
18
+ session: AsyncSession = Depends(get_async_session),
19
+ limit: int = 20,
20
+ offset: int = 0
21
+ ):
22
+ """
23
+ Retrieve all tasks for the authenticated user.
24
+
25
+ Args:
26
+ current_user: The authenticated user
27
+ session: Async database session
28
+ limit: Maximum number of tasks to return (default: 20)
29
+ offset: Number of tasks to skip (default: 0)
30
+
31
+ Returns:
32
+ Dictionary containing tasks and total count
33
+ """
34
+ try:
35
+ print(f"Getting tasks for user ID: {current_user.id}")
36
+ tasks = await TaskService.get_tasks_for_user(session, current_user.id, limit, offset)
37
+ print(f"Retrieved {len(tasks)} tasks from database")
38
+
39
+ # Convert tasks to dict to ensure proper serialization
40
+ task_dicts = []
41
+ for task in tasks:
42
+ task_dict = {
43
+ "id": task.id,
44
+ "title": task.title,
45
+ "description": task.description,
46
+ "completed": task.completed,
47
+ "user_id": task.user_id,
48
+ "created_at": task.created_at.isoformat() if task.created_at else None,
49
+ "updated_at": task.updated_at.isoformat() if task.updated_at else None
50
+ }
51
+ task_dicts.append(task_dict)
52
+
53
+ print(f"Successfully converted {len(task_dicts)} tasks to dict format")
54
+
55
+ return {
56
+ "success": True,
57
+ "data": {
58
+ "tasks": task_dicts,
59
+ "total": len(task_dicts)
60
+ }
61
+ }
62
+ except Exception as e:
63
+ print(f"Error in get_tasks: {str(e)}")
64
+ import traceback
65
+ traceback.print_exc()
66
+ raise HTTPException(
67
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
68
+ detail=f"Unable to retrieve tasks: {str(e)}"
69
+ )
70
+
71
+
72
+ @router.post("/", response_model=dict)
73
+ async def create_task(
74
+ task_create: TaskCreate,
75
+ current_user: UserRead = Depends(get_current_user),
76
+ session: AsyncSession = Depends(get_async_session)
77
+ ):
78
+ """
79
+ Create a new task for the authenticated user.
80
+
81
+ Args:
82
+ task_create: Task creation data
83
+ current_user: The authenticated user
84
+ session: Async database session
85
+
86
+ Returns:
87
+ Dictionary containing the created task
88
+ """
89
+ try:
90
+ # Create the task with the authenticated user's ID
91
+ created_task = await TaskService.create_task(session, task_create, current_user.id)
92
+
93
+ # Convert to dict to ensure proper serialization
94
+ task_dict = {
95
+ "id": created_task.id,
96
+ "title": created_task.title,
97
+ "description": created_task.description,
98
+ "completed": created_task.completed,
99
+ "user_id": created_task.user_id,
100
+ "created_at": created_task.created_at.isoformat() if created_task.created_at else None,
101
+ "updated_at": created_task.updated_at.isoformat() if created_task.updated_at else None
102
+ }
103
+
104
+ return {
105
+ "success": True,
106
+ "data": task_dict
107
+ }
108
+ except Exception as e:
109
+ print(f"Error in create_task: {str(e)}")
110
+ import traceback
111
+ traceback.print_exc()
112
+ raise HTTPException(
113
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
114
+ detail=f"Unable to create task: {str(e)}"
115
+ )
116
+
117
+
118
+ @router.get("/{task_id}", response_model=dict)
119
+ async def get_task(
120
+ task_id: int,
121
+ current_user: UserRead = Depends(get_current_user),
122
+ session: AsyncSession = Depends(get_async_session)
123
+ ):
124
+ """
125
+ Retrieve a specific task by ID for the authenticated user.
126
+
127
+ Args:
128
+ task_id: ID of the task to retrieve
129
+ current_user: The authenticated user
130
+ session: Async database session
131
+
132
+ Returns:
133
+ Dictionary containing the task data
134
+ """
135
+ try:
136
+ task = await TaskService.get_task_by_id(session, task_id, current_user.id)
137
+
138
+ # Convert to dict to ensure proper serialization
139
+ task_dict = {
140
+ "id": task.id,
141
+ "title": task.title,
142
+ "description": task.description,
143
+ "completed": task.completed,
144
+ "user_id": task.user_id,
145
+ "created_at": task.created_at.isoformat() if task.created_at else None,
146
+ "updated_at": task.updated_at.isoformat() if task.updated_at else None
147
+ }
148
+
149
+ return {
150
+ "success": True,
151
+ "data": task_dict
152
+ }
153
+ except HTTPException:
154
+ # Re-raise HTTP exceptions as-is
155
+ raise
156
+ except Exception as e:
157
+ print(f"Error in get_task: {str(e)}")
158
+ import traceback
159
+ traceback.print_exc()
160
+ raise HTTPException(
161
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
162
+ detail=f"Unable to retrieve task: {str(e)}"
163
+ )
164
+
165
+
166
+ @router.put("/{task_id}", response_model=dict)
167
+ async def update_task(
168
+ task_id: int,
169
+ task_update: TaskUpdate,
170
+ current_user: UserRead = Depends(get_current_user),
171
+ session: AsyncSession = Depends(get_async_session)
172
+ ):
173
+ """
174
+ Update a specific task by ID for the authenticated user.
175
+
176
+ Args:
177
+ task_id: ID of the task to update
178
+ task_update: Task update data
179
+ current_user: The authenticated user
180
+ session: Async database session
181
+
182
+ Returns:
183
+ Dictionary containing the updated task
184
+ """
185
+ try:
186
+ updated_task = await TaskService.update_task(session, task_id, task_update, current_user.id)
187
+
188
+ # Convert to dict to ensure proper serialization
189
+ task_dict = {
190
+ "id": updated_task.id,
191
+ "title": updated_task.title,
192
+ "description": updated_task.description,
193
+ "completed": updated_task.completed,
194
+ "user_id": updated_task.user_id,
195
+ "created_at": updated_task.created_at.isoformat() if updated_task.created_at else None,
196
+ "updated_at": updated_task.updated_at.isoformat() if updated_task.updated_at else None
197
+ }
198
+
199
+ return {
200
+ "success": True,
201
+ "data": task_dict
202
+ }
203
+ except HTTPException:
204
+ # Re-raise HTTP exceptions as-is
205
+ raise
206
+ except Exception as e:
207
+ print(f"Error in update_task: {str(e)}")
208
+ import traceback
209
+ traceback.print_exc()
210
+ raise HTTPException(
211
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
212
+ detail=f"Unable to update task: {str(e)}"
213
+ )
214
+
215
+
216
+ @router.delete("/{task_id}", response_model=dict)
217
+ async def delete_task(
218
+ task_id: int,
219
+ current_user: UserRead = Depends(get_current_user),
220
+ session: AsyncSession = Depends(get_async_session)
221
+ ):
222
+ """
223
+ Delete a specific task by ID for the authenticated user.
224
+
225
+ Args:
226
+ task_id: ID of the task to delete
227
+ current_user: The authenticated user
228
+ session: Async database session
229
+
230
+ Returns:
231
+ Dictionary containing success message
232
+ """
233
+ try:
234
+ await TaskService.delete_task(session, task_id, current_user.id)
235
+
236
+ return {
237
+ "success": True,
238
+ "data": {
239
+ "message": "Task deleted successfully"
240
+ }
241
+ }
242
+ except HTTPException:
243
+ # Re-raise HTTP exceptions as-is
244
+ raise
245
+ except Exception as e:
246
+ print(f"Error in delete_task: {str(e)}")
247
+ import traceback
248
+ traceback.print_exc()
249
+ raise HTTPException(
250
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
251
+ detail=f"Unable to delete task: {str(e)}"
252
+ )
253
+
254
+
255
+ @router.patch("/{task_id}/toggle", response_model=dict)
256
+ async def toggle_task_completion(
257
+ task_id: int,
258
+ current_user: UserRead = Depends(get_current_user),
259
+ session: AsyncSession = Depends(get_async_session)
260
+ ):
261
+ """
262
+ Toggle the completion status of a specific task.
263
+
264
+ Args:
265
+ task_id: ID of the task to toggle
266
+ current_user: The authenticated user
267
+ session: Async database session
268
+
269
+ Returns:
270
+ Dictionary containing the updated task
271
+ """
272
+ try:
273
+ updated_task = await TaskService.toggle_task_completion(session, task_id, current_user.id)
274
+
275
+ return {
276
+ "success": True,
277
+ "data": {
278
+ "id": updated_task.id,
279
+ "completed": updated_task.completed,
280
+ "updated_at": updated_task.updated_at.isoformat() if updated_task.updated_at else None
281
+ }
282
+ }
283
+ except HTTPException:
284
+ # Re-raise HTTP exceptions as-is
285
+ raise
286
+ except Exception as e:
287
+ print(f"Error in toggle_task_completion: {str(e)}")
288
+ import traceback
289
+ traceback.print_exc()
290
+ raise HTTPException(
291
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
292
+ detail=f"Unable to toggle task completion: {str(e)}"
293
+ )
src/config.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional
3
+
4
+ from pydantic_settings import BaseSettings
5
+
6
+
7
+ class Settings(BaseSettings):
8
+ # Database settings - using Neon PostgreSQL database
9
+ database_url: str = os.getenv("DATABASE_URL", "postgresql://neondb_owner:npg_ZHpDlAIVvQ67@ep-late-star-aip8khsg-pooler.c-4.us-east-1.aws.neon.tech/neondb?sslmode=require")
10
+ async_database_url: str = os.getenv(
11
+ "ASYNC_DATABASE_URL",
12
+ "postgresql+asyncpg://neondb_owner:npg_ZHpDlAIVvQ67@ep-late-star-aip8khsg-pooler.c-4.us-east-1.aws.neon.tech/neondb?ssl=true"
13
+ )
14
+ database_echo: bool = os.getenv("DATABASE_ECHO", "False").lower() == "true"
15
+
16
+ # JWT settings
17
+ secret_key: str = os.getenv("SECRET_KEY", "your-super-secret-jwt-key-change-in-production")
18
+ algorithm: str = "HS256"
19
+ access_token_expire_minutes: int = 30
20
+
21
+ # OpenAI settings
22
+ openai_api_key: str = os.getenv("OPENAI_API_KEY", "")
23
+
24
+ # Application settings
25
+ app_name: str = "Todo Backend API"
26
+ debug: bool = os.getenv("DEBUG", "False").lower() == "true"
27
+ api_prefix: str = "/api"
28
+
29
+ class Config:
30
+ env_file = ".env"
31
+
32
+
33
+ settings = Settings()
src/database/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ Database package for the Todo Backend API.
3
+
4
+ Contains database connection and session management.
5
+ """
src/database/database.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import create_engine, Session
2
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
3
+ from sqlalchemy.orm import sessionmaker
4
+ from urllib.parse import urlparse, parse_qs, urlencode
5
+
6
+ from ..config import settings
7
+
8
+ # Helper function to clean database URLs for asyncpg compatibility
9
+ def clean_database_url(url: str, is_async: bool = True) -> str:
10
+ """Remove query parameters that asyncpg doesn't support and ensure SSL is configured"""
11
+ # Skip processing for SQLite
12
+ if url.startswith('sqlite'):
13
+ return url
14
+
15
+ try:
16
+ # Parse the URL properly
17
+ parsed = urlparse(url)
18
+ query_params = parse_qs(parsed.query) if parsed.query else {}
19
+
20
+ if is_async:
21
+ # For async (asyncpg), remove parameters that asyncpg doesn't support
22
+ # asyncpg doesn't support 'channel_binding' or 'sslmode' parameters
23
+ # It handles SSL automatically for secure connections
24
+ params_to_remove = ['channel_binding', 'sslmode', 'ssl']
25
+ for param in params_to_remove:
26
+ if param in query_params:
27
+ del query_params[param]
28
+ else:
29
+ # For sync (psycopg2), keep sslmode=require format
30
+ # Just remove channel_binding which psycopg2 doesn't support
31
+ if 'channel_binding' in query_params:
32
+ del query_params['channel_binding']
33
+ # Ensure sslmode is set to require for secure connection
34
+ if 'sslmode' not in query_params:
35
+ query_params['sslmode'] = ['require']
36
+
37
+ # Rebuild the query string
38
+ cleaned_params = urlencode(query_params, doseq=True)
39
+
40
+ # Rebuild the URL
41
+ cleaned_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
42
+ if cleaned_params:
43
+ cleaned_url += f"?{cleaned_params}"
44
+
45
+ return cleaned_url
46
+ except Exception as e:
47
+ print(f"Error cleaning database URL: {e}")
48
+ # Fallback: just remove the problematic params manually
49
+ base_url = url.split('?')[0]
50
+ if is_async:
51
+ return f"{base_url}?ssl=true"
52
+ else:
53
+ return f"{base_url}?sslmode=require"
54
+
55
+ # Clean URLs for asyncpg compatibility (skip for SQLite)
56
+ clean_sync_url = clean_database_url(settings.database_url, is_async=False)
57
+ clean_async_url = clean_database_url(settings.async_database_url, is_async=True)
58
+
59
+ # Optional: Enable debug prints if needed - commented out by default
60
+ # print(f"DEBUG: Original sync URL: {settings.database_url}")
61
+ # print(f"DEBUG: Cleaned sync URL: {clean_sync_url}")
62
+ # print(f"DEBUG: Original async URL: {settings.async_database_url}")
63
+ # print(f"DEBUG: Cleaned async URL: {clean_async_url}")
64
+
65
+ # Determine if we're using SQLite (which doesn't support pooling parameters)
66
+ is_sqlite_sync = clean_sync_url.startswith('sqlite')
67
+ is_sqlite_async = clean_async_url.startswith('sqlite')
68
+
69
+ # Synchronous engine for general use
70
+ if is_sqlite_sync:
71
+ # SQLite doesn't support pooling parameters
72
+ sync_engine = create_engine(
73
+ clean_sync_url,
74
+ echo=settings.database_echo, # Set to True for SQL query logging
75
+ poolclass=None, # Use NullPool for SQLite
76
+ )
77
+ else:
78
+ # PostgreSQL supports pooling parameters
79
+ sync_engine = create_engine(
80
+ clean_sync_url,
81
+ echo=settings.database_echo, # Set to True for SQL query logging
82
+ pool_pre_ping=True, # Verify connections before use
83
+ pool_recycle=300, # Recycle connections every 5 minutes
84
+ pool_size=5, # Number of connections to maintain
85
+ max_overflow=10, # Additional connections beyond pool_size
86
+ pool_timeout=30, # Timeout for getting connection from pool
87
+ )
88
+
89
+ # Async engine for async operations
90
+ if is_sqlite_async:
91
+ # SQLite doesn't support pooling parameters
92
+ async_engine = create_async_engine(
93
+ clean_async_url,
94
+ echo=settings.database_echo, # Set to True for SQL query logging
95
+ poolclass=None, # Use NullPool for SQLite
96
+ )
97
+ else:
98
+ # PostgreSQL supports pooling parameters
99
+ async_engine = create_async_engine(
100
+ clean_async_url,
101
+ echo=settings.database_echo, # Set to True for SQL query logging
102
+ pool_pre_ping=True, # Verify connections before use
103
+ pool_recycle=300, # Recycle connections every 5 minutes
104
+ pool_size=5, # Number of connections to maintain
105
+ max_overflow=10, # Additional connections beyond pool_size
106
+ pool_timeout=30, # Timeout for getting connection from pool
107
+ )
108
+
109
+ # Session makers
110
+ AsyncSessionLocal = sessionmaker(
111
+ autocommit=False,
112
+ autoflush=False,
113
+ bind=async_engine,
114
+ class_=AsyncSession,
115
+ expire_on_commit=False
116
+ )
117
+
118
+ SyncSessionLocal = sessionmaker(
119
+ autocommit=False,
120
+ autoflush=False,
121
+ bind=sync_engine,
122
+ expire_on_commit=False
123
+ )
124
+
125
+
126
+ def get_sync_session():
127
+ """Get a synchronous database session."""
128
+ session = SyncSessionLocal()
129
+ try:
130
+ yield session
131
+ finally:
132
+ session.close()
133
+
134
+
135
+ async def get_async_session():
136
+ """Get an asynchronous database session."""
137
+ async with AsyncSessionLocal() as session:
138
+ yield session
139
+ await session.close()
src/database/migrate.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database migration script for Todo Backend API.
3
+
4
+ This script handles database schema creation and updates.
5
+ """
6
+ import sys
7
+ import os
8
+
9
+ # Add the src directory to the path so we can import modules
10
+ sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
11
+
12
+ from sqlmodel import SQLModel
13
+ from sqlalchemy import text
14
+ from .database import sync_engine
15
+ from ..models.user import User
16
+ from ..models.task import Task
17
+ from ..models.conversation import Conversation
18
+ from ..models.message import Message
19
+
20
+
21
+ def create_db_and_tables():
22
+ """Create database tables based on SQLModel models."""
23
+ print("Creating database tables...")
24
+
25
+ # Create all tables
26
+ SQLModel.metadata.create_all(bind=sync_engine)
27
+
28
+ # Add columns that might be missing in existing tables
29
+ print("Checking for missing columns...")
30
+ with sync_engine.connect() as conn:
31
+ try:
32
+ # PostgreSQL specific: ADD COLUMN IF NOT EXISTS for user.username
33
+ conn.execute(text("ALTER TABLE \"user\" ADD COLUMN IF NOT EXISTS username VARCHAR(255);"))
34
+
35
+ # Update existing users to have a username based on their email or id
36
+ conn.execute(text("UPDATE \"user\" SET username = 'user_' || id WHERE username IS NULL OR username = '';"))
37
+
38
+ # Make username required and unique
39
+ conn.execute(text("ALTER TABLE \"user\" ALTER COLUMN username SET NOT NULL;"))
40
+ conn.execute(text("ALTER TABLE \"user\" ADD CONSTRAINT username_unique UNIQUE (username);"))
41
+
42
+ # PostgreSQL specific: ADD COLUMN IF NOT EXISTS for conversation.title
43
+ conn.execute(text("ALTER TABLE conversation ADD COLUMN IF NOT EXISTS title VARCHAR(255) DEFAULT 'New Conversation';"))
44
+
45
+ # PostgreSQL specific: ADD COLUMN IF NOT EXISTS for message.timestamp
46
+ conn.execute(text("ALTER TABLE message ADD COLUMN IF NOT EXISTS timestamp TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP;"))
47
+
48
+ # PostgreSQL specific: ADD COLUMN IF NOT EXISTS for message.user_id
49
+ # Corrected syntax for foreign key constraint with NOT NULL
50
+ conn.execute(text('ALTER TABLE message ADD COLUMN IF NOT EXISTS user_id INTEGER REFERENCES "user"(id);'))
51
+
52
+ conn.commit()
53
+ print("Missing columns check/add completed.")
54
+ except Exception as e:
55
+ print(f"Non-critical error adding columns: {e}")
56
+ # Fallback for SQLite or other DBs if needed
57
+ try:
58
+ # For fallback, add username column first
59
+ conn.execute(text("ALTER TABLE \"user\" ADD COLUMN username VARCHAR(255);"))
60
+
61
+ # Update existing users to have a username
62
+ conn.execute(text("UPDATE \"user\" SET username = 'user_' || id WHERE username IS NULL OR username = '';"))
63
+
64
+ # Add constraints for SQLite
65
+ conn.execute(text("ALTER TABLE \"user\" ADD CONSTRAINT username_unique UNIQUE (username);"))
66
+
67
+ conn.execute(text("ALTER TABLE conversation ADD COLUMN title VARCHAR(255) DEFAULT 'New Conversation';"))
68
+ conn.execute(text("ALTER TABLE message ADD COLUMN timestamp DATETIME DEFAULT CURRENT_TIMESTAMP;"))
69
+ # Corrected syntax for fallback foreign key constraint
70
+ conn.execute(text('ALTER TABLE message ADD COLUMN user_id INTEGER REFERENCES "user"(id);'))
71
+ conn.commit()
72
+ print("Missing columns added via fallback.")
73
+ except Exception as e2:
74
+ print(f"Could not add columns (they might already exist): {e2}")
75
+
76
+ print("Database tables created successfully!")
77
+
78
+
79
+ if __name__ == "__main__":
80
+ create_db_and_tables()
src/middleware/auth.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timedelta
2
+ from typing import Optional
3
+ import os
4
+ from fastapi import HTTPException, status, Depends, Request
5
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
6
+ from sqlmodel import Session
7
+ from jose import JWTError, jwt
8
+ from backend.src.database import get_session
9
+ from backend.src.models.user import User
10
+
11
+ # Initialize security scheme
12
+ security = HTTPBearer()
13
+
14
+ # Get secret key from environment - check both BETTER_AUTH_SECRET and SECRET_KEY
15
+ SECRET_KEY = os.getenv("BETTER_AUTH_SECRET") or os.getenv("SECRET_KEY", "fallback_secret_key_for_development")
16
+ ALGORITHM = "HS256"
17
+ ACCESS_TOKEN_EXPIRE_MINUTES = 30
18
+
19
+ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
20
+ """Create a new JWT access token"""
21
+ to_encode = data.copy()
22
+ if expires_delta:
23
+ expire = datetime.utcnow() + expires_delta
24
+ else:
25
+ expire = datetime.utcnow() + timedelta(minutes=15)
26
+
27
+ to_encode.update({"exp": expire})
28
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
29
+ return encoded_jwt
30
+
31
+ def verify_token(token: str, credentials_exception):
32
+ """Verify JWT token and extract user information"""
33
+ try:
34
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
35
+ user_id: str = payload.get("sub")
36
+ if user_id is None:
37
+ raise credentials_exception
38
+ return user_id
39
+ except JWTError:
40
+ raise credentials_exception
41
+
42
+ def get_current_user(
43
+ credentials: HTTPAuthorizationCredentials = Depends(security),
44
+ session: Session = Depends(get_session)
45
+ ):
46
+ """Dependency to get current user from JWT token"""
47
+ credentials_exception = HTTPException(
48
+ status_code=status.HTTP_401_UNAUTHORIZED,
49
+ detail="Could not validate credentials",
50
+ headers={"WWW-Authenticate": "Bearer"},
51
+ )
52
+
53
+ user_id = verify_token(credentials.credentials, credentials_exception)
54
+
55
+ user = session.get(User, user_id)
56
+ if user is None:
57
+ raise credentials_exception
58
+
59
+ return user
60
+
61
+ class JWTBearer(HTTPBearer):
62
+ """Custom JWT Bearer authentication class with enhanced functionality"""
63
+ def __init__(self, auto_error: bool = True):
64
+ super(JWTBearer, self).__init__(auto_error=auto_error)
65
+
66
+ async def __call__(self, request: Request):
67
+ credentials: Optional[HTTPAuthorizationCredentials] = await super(JWTBearer, self).__call__(request)
68
+
69
+ if credentials:
70
+ if not credentials.scheme == "Bearer":
71
+ raise HTTPException(
72
+ status_code=status.HTTP_403_FORBIDDEN,
73
+ detail="Invalid authentication scheme."
74
+ )
75
+ token = credentials.credentials
76
+ user_id = self.verify_jwt(token)
77
+ if not user_id:
78
+ raise HTTPException(
79
+ status_code=status.HTTP_403_FORBIDDEN,
80
+ detail="Invalid token or expired token."
81
+ )
82
+
83
+ # Attach user info to request
84
+ request.state.user_id = user_id
85
+ return token
86
+ else:
87
+ raise HTTPException(
88
+ status_code=status.HTTP_403_FORBIDDEN,
89
+ detail="Invalid authorization code."
90
+ )
91
+
92
+ def verify_jwt(self, jwtoken: str) -> Optional[str]:
93
+ """
94
+ Verify JWT token and return user ID if valid
95
+
96
+ Args:
97
+ jwtoken: JWT token to verify
98
+
99
+ Returns:
100
+ str: User ID if token is valid, None otherwise
101
+ """
102
+ try:
103
+ payload = jwt.decode(jwtoken, SECRET_KEY, algorithms=[ALGORITHM])
104
+ user_id = payload.get("sub")
105
+ return user_id
106
+ except jwt.ExpiredSignatureError:
107
+ return None
108
+ except jwt.InvalidTokenError:
109
+ return None
110
+
111
+
112
+ def verify_token_detailed(token: str) -> Optional[dict]:
113
+ """
114
+ Verify JWT token and return detailed payload information
115
+
116
+ Args:
117
+ token: JWT token to verify
118
+
119
+ Returns:
120
+ dict: Payload information if token is valid, None otherwise
121
+ """
122
+ try:
123
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
124
+ return payload
125
+ except jwt.ExpiredSignatureError:
126
+ return {"error": "EXPIRED_TOKEN", "message": "Token has expired"}
127
+ except jwt.InvalidTokenError:
128
+ return {"error": "INVALID_TOKEN", "message": "Invalid token format"}
src/middleware/chat_auth.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Authentication middleware for chat endpoints in the Todo Backend API.
3
+
4
+ Handles JWT validation specifically for chat endpoints.
5
+ """
6
+ from typing import Optional
7
+ from fastapi import Request, HTTPException, status
8
+ from fastapi.security.http import HTTPBearer, HTTPAuthorizationCredentials
9
+ from jose import JWTError, jwt
10
+ from ..config import settings
11
+ from ..utils.jwt_utils import decode_access_token
12
+ from ..models.user import UserRead
13
+ from sqlmodel.ext.asyncio.session import AsyncSession
14
+ from ..database.database import get_async_session
15
+ from sqlmodel import select
16
+
17
+
18
+ class ChatAuthMiddleware:
19
+ """
20
+ Middleware to handle authentication for chat endpoints.
21
+ Validates JWT tokens and ensures user access rights.
22
+ """
23
+
24
+ def __init__(self):
25
+ self.security = HTTPBearer()
26
+
27
+ async def verify_token(self, token: str, user_id: int) -> Optional[UserRead]:
28
+ """
29
+ Verify the JWT token and ensure it belongs to the specified user_id.
30
+
31
+ Args:
32
+ token: JWT token to verify
33
+ user_id: Expected user ID from the endpoint path
34
+
35
+ Returns:
36
+ UserRead object if token is valid and belongs to user_id, None otherwise
37
+ """
38
+ try:
39
+ payload = decode_access_token(token)
40
+ token_user_id: str = payload.get("sub")
41
+
42
+ if token_user_id is None:
43
+ raise HTTPException(
44
+ status_code=status.HTTP_401_UNAUTHORIZED,
45
+ detail="Could not validate credentials",
46
+ headers={"WWW-Authenticate": "Bearer"},
47
+ )
48
+
49
+ # Convert to int for comparison
50
+ token_user_id_int = int(token_user_id)
51
+
52
+ # Check if the token user_id matches the requested user_id
53
+ if token_user_id_int != user_id:
54
+ raise HTTPException(
55
+ status_code=status.HTTP_403_FORBIDDEN,
56
+ detail="Access denied: Token does not match requested user"
57
+ )
58
+
59
+ # Here we would typically fetch user details from the database
60
+ # For now, we'll return a basic UserRead object
61
+ return UserRead(
62
+ id=token_user_id_int,
63
+ email="placeholder@example.com" # This would come from DB in real implementation
64
+ )
65
+
66
+ except JWTError:
67
+ raise HTTPException(
68
+ status_code=status.HTTP_401_UNAUTHORIZED,
69
+ detail="Could not validate credentials",
70
+ headers={"WWW-Authenticate": "Bearer"},
71
+ )
72
+ except ValueError:
73
+ # Handle case where token_user_id is not a valid integer
74
+ raise HTTPException(
75
+ status_code=status.HTTP_401_UNAUTHORIZED,
76
+ detail="Invalid token format",
77
+ headers={"WWW-Authenticate": "Bearer"},
78
+ )
79
+
80
+
81
+ # Global instance
82
+ chat_auth = ChatAuthMiddleware()
src/middleware/security.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Request, Response
2
+ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
3
+ from typing import Union
4
+
5
+ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
6
+ """
7
+ Middleware to add security headers to all responses
8
+ """
9
+
10
+ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
11
+ # Allow static files for documentation without strict CSP
12
+ if request.url.path.startswith('/docs') or request.url.path.startswith('/redoc') or request.url.path.startswith('/openapi.json'):
13
+ response: Response = await call_next(request)
14
+
15
+ # Apply relaxed security headers for documentation endpoints
16
+ response.headers.setdefault("X-Content-Type-Options", "nosniff")
17
+ response.headers.setdefault("X-Frame-Options", "SAMEORIGIN") # Allow framing for Swagger UI
18
+ response.headers.setdefault("X-XSS-Protection", "1; mode=block")
19
+ response.headers.setdefault("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
20
+
21
+ # More permissive CSP for documentation
22
+ response.headers.setdefault(
23
+ "Content-Security-Policy",
24
+ "default-src 'self'; "
25
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; "
26
+ "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; "
27
+ "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.jsdelivr.net; "
28
+ "font-src 'self' https://cdn.jsdelivr.net; "
29
+ "connect-src 'self' https://cdn.jsdelivr.net; "
30
+ "media-src 'self';"
31
+ )
32
+
33
+ response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
34
+ response.headers.setdefault("X-Download-Options", "noopen")
35
+ response.headers.setdefault("X-Permitted-Cross-Domain-Policies", "none")
36
+
37
+ return response
38
+ else:
39
+ # Apply strict security headers for API endpoints
40
+ response: Response = await call_next(request)
41
+
42
+ # Prevent MIME-type sniffing
43
+ response.headers.setdefault("X-Content-Type-Options", "nosniff")
44
+
45
+ # Prevent page from loading in a frame to prevent clickjacking
46
+ response.headers.setdefault("X-Frame-Options", "DENY")
47
+
48
+ # Basic XSS protection
49
+ response.headers.setdefault("X-XSS-Protection", "1; mode=block")
50
+
51
+ # Strict transport security
52
+ response.headers.setdefault("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
53
+
54
+ # Content Security Policy - Allow CDN resources for Swagger UI
55
+ response.headers.setdefault(
56
+ "Content-Security-Policy",
57
+ "default-src 'self'; "
58
+ "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; "
59
+ "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; "
60
+ "img-src 'self' data: https://fastapi.tiangolo.com https://cdn.jsdelivr.net; "
61
+ "font-src 'self' https://cdn.jsdelivr.net; "
62
+ "connect-src 'self';"
63
+ )
64
+
65
+ # Referrer policy
66
+ response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
67
+
68
+ # Prevent IE from opening downloads in the browser
69
+ response.headers.setdefault("X-Download-Options", "noopen")
70
+
71
+ # Disallow embedding in other sites
72
+ response.headers.setdefault("X-Permitted-Cross-Domain-Policies", "none")
73
+
74
+ return response
src/models/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Models package for the Todo Backend API.
3
+
4
+ Contains all the SQLModel database models for the application.
5
+ """
6
+
7
+ from .user import User, UserCreate, UserRead
8
+ from .task import Task, TaskCreate, TaskUpdate, TaskRead
9
+ from .conversation import Conversation, ConversationCreate, ConversationRead
10
+ from .message import Message, MessageCreate, MessageRead, MessageRole
11
+
12
+ __all__ = [
13
+ "User",
14
+ "UserCreate",
15
+ "UserRead",
16
+ "Task",
17
+ "TaskCreate",
18
+ "TaskUpdate",
19
+ "TaskRead",
20
+ "Conversation",
21
+ "ConversationCreate",
22
+ "ConversationRead",
23
+ "Message",
24
+ "MessageCreate",
25
+ "MessageRead",
26
+ "MessageRole",
27
+ ]
src/models/conversation.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, List
2
+ from datetime import datetime
3
+ from sqlmodel import Field, SQLModel, Relationship
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from .message import Message # Avoid circular import for type checking
8
+
9
+
10
+ class ConversationBase(SQLModel):
11
+ """Base model for Conversation with common fields."""
12
+ title: str = Field(default="New Conversation", max_length=255)
13
+ user_id: str = Field(index=True) # String identifier for user (matches database schema)
14
+
15
+
16
+ class Conversation(ConversationBase, table=True):
17
+ """Conversation model for the database table."""
18
+ id: Optional[int] = Field(default=None, primary_key=True)
19
+ created_at: Optional[datetime] = Field(default_factory=datetime.utcnow)
20
+ updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow, sa_column_kwargs={"onupdate": datetime.utcnow})
21
+
22
+ # Relationship
23
+ messages: List["Message"] = Relationship(back_populates="conversation")
24
+
25
+
26
+ class ConversationCreate(ConversationBase):
27
+ """Model for creating a new conversation."""
28
+ pass
29
+
30
+
31
+ class ConversationRead(ConversationBase):
32
+ """Model for reading conversation data."""
33
+ id: int
34
+ created_at: datetime
35
+ updated_at: datetime
36
+ # Note: messages are typically not included in read models to avoid circular references
37
+ # They can be retrieved separately when needed
src/models/error.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from pydantic import BaseModel
3
+
4
+
5
+ class ErrorDetail(BaseModel):
6
+ """Model for error details in API responses."""
7
+ code: str
8
+ message: str
9
+
10
+
11
+ class ErrorResponse(BaseModel):
12
+ """Model for error responses from the API."""
13
+ success: bool = False
14
+ error: ErrorDetail
15
+
16
+
17
+ class SuccessResponse(BaseModel):
18
+ """Model for success responses from the API."""
19
+ success: bool = True
20
+ data: Optional[dict] = None
src/models/error_response.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from enum import Enum
3
+ from typing import Optional
4
+
5
+
6
+ class AuthErrorType(str, Enum):
7
+ """Enumeration of authentication error types."""
8
+ EMAIL_NOT_FOUND = "EMAIL_NOT_FOUND"
9
+ INVALID_PASSWORD = "INVALID_PASSWORD"
10
+ AUTH_FAILED = "AUTH_FAILED"
11
+ INVALID_EMAIL_FORMAT = "INVALID_EMAIL_FORMAT"
12
+ MISSING_FIELDS = "MISSING_FIELDS"
13
+ EMAIL_EXISTS = "EMAIL_EXISTS"
14
+ INVALID_SIGNUP_DATE = "INVALID_SIGNUP_DATE"
15
+ WEAK_PASSWORD = "WEAK_PASSWORD"
16
+
17
+
18
+ class ErrorResponse(BaseModel):
19
+ """Model for authentication error responses."""
20
+ error: AuthErrorType
21
+ message: str
22
+ details: Optional[str] = None
23
+
24
+
25
+ class ValidationErrorResponse(BaseModel):
26
+ """Model for validation error responses."""
27
+ error: str
28
+ message: str
29
+ field: Optional[str] = None
30
+ value: Optional[str] = None
31
+
32
+
33
+ class SuccessResponse(BaseModel):
34
+ """Model for successful responses."""
35
+ success: bool = True
36
+ message: Optional[str] = None
37
+ data: Optional[dict] = None
38
+
39
+
40
+ class AuthSuccessResponse(BaseModel):
41
+ """Model for authentication success responses."""
42
+ success: bool = True
43
+ token: str
44
+ user: dict
45
+ message: Optional[str] = "Authentication successful"
src/models/message.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from datetime import datetime
3
+ from sqlmodel import Field, SQLModel, Relationship
4
+ from enum import Enum
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from .conversation import Conversation # Avoid circular import for type checking
9
+
10
+
11
+ class MessageRole(str, Enum):
12
+ """Enumeration for message roles."""
13
+ USER = "user"
14
+ ASSISTANT = "assistant"
15
+ SYSTEM = "system"
16
+
17
+
18
+ class MessageBase(SQLModel):
19
+ """Base model for Message with common fields."""
20
+ role: MessageRole = Field(sa_column_kwargs={"default": "user"})
21
+ content: str = Field(max_length=5000)
22
+ conversation_id: int = Field(foreign_key="conversation.id")
23
+ user_id: str = Field(index=True) # String identifier for user (matches database schema)
24
+
25
+
26
+ class Message(MessageBase, table=True):
27
+ """Message model for the database table."""
28
+ id: Optional[int] = Field(default=None, primary_key=True)
29
+ timestamp: Optional[datetime] = Field(default_factory=datetime.utcnow)
30
+ created_at: Optional[datetime] = Field(default_factory=datetime.utcnow)
31
+
32
+ # Relationship
33
+ conversation: Optional["Conversation"] = Relationship(back_populates="messages")
34
+
35
+
36
+ class MessageCreate(MessageBase):
37
+ """Model for creating a new message."""
38
+ pass
39
+
40
+
41
+ class MessageRead(MessageBase):
42
+ """Model for reading message data."""
43
+ id: int
44
+ user_id: str # String identifier for user (matches database schema)
45
+ timestamp: datetime
46
+ created_at: datetime
src/models/session.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from datetime import datetime, timezone
3
+ from uuid import UUID, uuid4
4
+
5
+ from sqlmodel import Field, SQLModel, Column
6
+
7
+
8
+ class SessionBase(SQLModel):
9
+ """Base model for Session with common fields."""
10
+ user_id: str = Field(index=True, nullable=False) # Reference to associated user
11
+ expires_at: datetime = Field(nullable=False) # Session expiration time
12
+
13
+
14
+ class Session(SessionBase, table=True):
15
+ """Session model for the database table."""
16
+ id: Optional[UUID] = Field(default_factory=uuid4, primary_key=True, sa_column=Column(UUID(as_uuid=True), primary_key=True, default=uuid4))
17
+ user_id: str = Field(index=True, nullable=False) # Reference to associated user
18
+ expires_at: datetime = Field(nullable=False) # Session expiration time
19
+ created_at: datetime = Field(default_factory=datetime.utcnow, nullable=False)
20
+
21
+
22
+ class SessionCreate(SessionBase):
23
+ """Model for creating a new session."""
24
+ pass
25
+
26
+
27
+ class SessionRead(SessionBase):
28
+ """Model for reading session data."""
29
+ id: UUID
30
+ created_at: datetime
src/models/task.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from datetime import datetime
3
+
4
+ import sqlalchemy as sa
5
+ from sqlmodel import Field, SQLModel, ForeignKey
6
+
7
+
8
+ class TaskBase(SQLModel):
9
+ """Base model for Task with common fields."""
10
+ title: str = Field(min_length=1, max_length=255)
11
+ description: Optional[str] = Field(default=None, max_length=1000)
12
+ completed: bool = Field(default=False)
13
+
14
+
15
+ class TaskCreate(TaskBase):
16
+ """Model for creating a new task."""
17
+ pass # user_id will be set by the service layer
18
+
19
+
20
+ class TaskUpdate(SQLModel):
21
+ """Model for updating task data."""
22
+ title: Optional[str] = Field(default=None, min_length=1, max_length=255)
23
+ description: Optional[str] = Field(default=None, max_length=1000)
24
+ completed: Optional[bool] = None
25
+
26
+
27
+ class Task(TaskBase, table=True):
28
+ """Task model for the database table."""
29
+ id: Optional[int] = Field(default=None, primary_key=True)
30
+ user_id: str = Field(index=True) # String identifier for user (matches database schema)
31
+ created_at: Optional[datetime] = Field(default_factory=datetime.utcnow)
32
+ updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow, sa_column_kwargs={"onupdate": datetime.utcnow})
33
+
34
+
35
+ class TaskRead(TaskBase):
36
+ """Model for reading task data."""
37
+ id: int
38
+ user_id: str # Include user_id in read model as string
39
+ created_at: datetime
40
+ updated_at: datetime
src/models/user.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+ from datetime import datetime, date
3
+ from sqlmodel import Field, SQLModel
4
+
5
+
6
+ class UserBase(SQLModel):
7
+ """Base model for User with common fields."""
8
+ email: str = Field(unique=True, nullable=False, max_length=255)
9
+ username: Optional[str] = Field(default=None, nullable=True, max_length=255) # String identifier for MCP tools
10
+
11
+
12
+ class User(UserBase, table=True):
13
+ """User model for the database table."""
14
+ id: Optional[int] = Field(default=None, primary_key=True)
15
+ username: Optional[str] = Field(default=None, nullable=True, unique=True, max_length=255) # String identifier for MCP tools
16
+ password: str = Field(nullable=False, max_length=255) # Hashed password
17
+ name: Optional[str] = Field(default=None, max_length=255) # Optional name field
18
+ date_of_birth: Optional[date] = Field(default=None, nullable=True) # Date of birth
19
+ signup_date: datetime = Field(default_factory=datetime.utcnow, nullable=False) # Non-nullable signup date
20
+ force_password_change: bool = Field(default=False) # Flag to indicate if user needs to change password
21
+ created_at: Optional[datetime] = Field(default_factory=datetime.utcnow)
22
+ updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow, sa_column_kwargs={"onupdate": datetime.utcnow})
23
+
24
+
25
+ class UserCreate(UserBase):
26
+ """Model for creating a new user."""
27
+ password: str
28
+ name: Optional[str] = None
29
+ date_of_birth: Optional[Union[str, datetime]] = None # Date of birth as string or datetime
30
+ # username is inherited from UserBase
31
+
32
+
33
+ class UserRead(UserBase):
34
+ """Model for reading user data."""
35
+ id: int
36
+ username: str # Include username in read model
37
+ name: Optional[str] = None
38
+ date_of_birth: Optional[date] = None
39
+ signup_date: datetime # Include signup_date in read model
40
+ force_password_change: bool = False
41
+ created_at: datetime
42
+ updated_at: datetime
src/services/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ Services package for the Todo Backend API.
3
+
4
+ Contains business logic services.
5
+ """
src/services/ai_service.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI Service for the Todo Backend API.
3
+
4
+ Implements MCP tools for task operations and integrates with OpenAI Agents SDK.
5
+ """
6
+ from typing import Optional, List, Dict, Any
7
+ from sqlmodel.ext.asyncio.session import AsyncSession
8
+ from ..models.task import Task, TaskCreate, TaskUpdate, TaskRead
9
+ from ..models.user import UserRead
10
+ from ..services.task_service import TaskService
11
+ from ..config import settings
12
+ import openai
13
+ from openai import OpenAI
14
+
15
+
16
+ class AIService:
17
+ """
18
+ Service class to handle AI interactions and MCP tools for task operations.
19
+ """
20
+
21
+ def __init__(self):
22
+ # Initialize OpenAI client lazily (only when needed)
23
+ self._client = None
24
+
25
+ @property
26
+ def client(self):
27
+ if self._client is None:
28
+ self._client = OpenAI(api_key=settings.openai_api_key)
29
+ return self._client
30
+
31
+ async def add_task_tool(
32
+ self,
33
+ title: str,
34
+ user: UserRead,
35
+ session: AsyncSession,
36
+ description: Optional[str] = None
37
+ ) -> Dict[str, Any]:
38
+ """
39
+ MCP tool for adding tasks.
40
+
41
+ Args:
42
+ title: Title of the task
43
+ description: Optional description of the task
44
+ user: User who owns the task
45
+ session: Database session
46
+
47
+ Returns:
48
+ Dictionary with task creation result
49
+ """
50
+ try:
51
+ # Create task data
52
+ task_create = TaskCreate(title=title, description=description)
53
+
54
+ # Use TaskService to create the task
55
+ # Convert user.id to string to match database schema
56
+ user_id_str = str(user.id)
57
+ created_task = await TaskService.create_task(session, task_create, user_id_str)
58
+
59
+ return {
60
+ "success": True,
61
+ "task_id": created_task.id,
62
+ "message": f"Task '{created_task.title}' added successfully"
63
+ }
64
+ except Exception as e:
65
+ return {
66
+ "success": False,
67
+ "error": str(e),
68
+ "message": "Failed to add task"
69
+ }
70
+
71
+ async def list_tasks_tool(
72
+ self,
73
+ user: UserRead,
74
+ session: AsyncSession,
75
+ limit: int = 20,
76
+ offset: int = 0
77
+ ) -> Dict[str, Any]:
78
+ """
79
+ MCP tool for listing tasks.
80
+
81
+ Args:
82
+ user: User whose tasks to list
83
+ session: Database session
84
+ limit: Maximum number of tasks to return
85
+ offset: Number of tasks to skip
86
+
87
+ Returns:
88
+ Dictionary with list of tasks
89
+ """
90
+ try:
91
+ # Use TaskService to get tasks
92
+ # Convert user.id to string to match database schema
93
+ user_id_str = str(user.id)
94
+ tasks = await TaskService.get_tasks_for_user(session, user_id_str, limit, offset)
95
+
96
+ return {
97
+ "success": True,
98
+ "tasks": [task.model_dump() for task in tasks],
99
+ "count": len(tasks)
100
+ }
101
+ except Exception as e:
102
+ return {
103
+ "success": False,
104
+ "error": str(e),
105
+ "message": "Failed to list tasks"
106
+ }
107
+
108
+ async def update_task_tool(
109
+ self,
110
+ task_id: int,
111
+ user: UserRead,
112
+ session: AsyncSession,
113
+ title: Optional[str] = None,
114
+ description: Optional[str] = None,
115
+ completed: Optional[bool] = None
116
+ ) -> Dict[str, Any]:
117
+ """
118
+ MCP tool for updating tasks.
119
+
120
+ Args:
121
+ task_id: ID of the task to update
122
+ title: New title (optional)
123
+ description: New description (optional)
124
+ completed: New completion status (optional)
125
+ user: User who owns the task
126
+ session: Database session
127
+
128
+ Returns:
129
+ Dictionary with task update result
130
+ """
131
+ try:
132
+ # Prepare update data
133
+ update_data = {}
134
+ if title is not None:
135
+ update_data["title"] = title
136
+ if description is not None:
137
+ update_data["description"] = description
138
+ if completed is not None:
139
+ update_data["completed"] = completed
140
+
141
+ task_update = TaskUpdate(**update_data)
142
+
143
+ # Use TaskService to update the task
144
+ # Convert user.id to string to match database schema
145
+ user_id_str = str(user.id)
146
+ updated_task = await TaskService.update_task(session, task_id, task_update, user_id_str)
147
+
148
+ return {
149
+ "success": True,
150
+ "task_id": updated_task.id,
151
+ "message": f"Task '{updated_task.title}' updated successfully"
152
+ }
153
+ except Exception as e:
154
+ return {
155
+ "success": False,
156
+ "error": str(e),
157
+ "message": "Failed to update task"
158
+ }
159
+
160
+ async def delete_task_tool(
161
+ self,
162
+ task_id: int,
163
+ user: UserRead,
164
+ session: AsyncSession
165
+ ) -> Dict[str, Any]:
166
+ """
167
+ MCP tool for deleting tasks.
168
+
169
+ Args:
170
+ task_id: ID of the task to delete
171
+ user: User who owns the task
172
+ session: Database session
173
+
174
+ Returns:
175
+ Dictionary with task deletion result
176
+ """
177
+ try:
178
+ # Use TaskService to delete the task
179
+ # Convert user.id to string to match database schema
180
+ user_id_str = str(user.id)
181
+ await TaskService.delete_task(session, task_id, user_id_str)
182
+
183
+ return {
184
+ "success": True,
185
+ "task_id": task_id,
186
+ "message": "Task deleted successfully"
187
+ }
188
+ except Exception as e:
189
+ return {
190
+ "success": False,
191
+ "error": str(e),
192
+ "message": "Failed to delete task"
193
+ }
194
+
195
+ async def complete_task_tool(
196
+ self,
197
+ task_id: int,
198
+ user: UserRead,
199
+ session: AsyncSession
200
+ ) -> Dict[str, Any]:
201
+ """
202
+ MCP tool for completing tasks.
203
+
204
+ Args:
205
+ task_id: ID of the task to mark as complete
206
+ user: User who owns the task
207
+ session: Database session
208
+
209
+ Returns:
210
+ Dictionary with task completion result
211
+ """
212
+ try:
213
+ # Use TaskService to toggle task completion
214
+ # Convert user.id to string to match database schema
215
+ user_id_str = str(user.id)
216
+ updated_task = await TaskService.toggle_task_completion(session, task_id, user_id_str)
217
+
218
+ status = "completed" if updated_task.completed else "marked as incomplete"
219
+ return {
220
+ "success": True,
221
+ "task_id": updated_task.id,
222
+ "completed": updated_task.completed,
223
+ "message": f"Task '{updated_task.title}' {status} successfully"
224
+ }
225
+ except Exception as e:
226
+ return {
227
+ "success": False,
228
+ "error": str(e),
229
+ "message": "Failed to complete task"
230
+ }
231
+
232
+
233
+ # Global instance
234
+ ai_service = AIService()
src/services/auth_service.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timedelta
2
+ from typing import Optional, Dict, Any
3
+ from sqlmodel import Session, select
4
+ from jose import JWTError, jwt
5
+ import os
6
+ from ..models.user import User
7
+ from ..config import settings
8
+ from ..utils.date_validator import validate_signup_date
9
+
10
+ SECRET_KEY = settings.secret_key
11
+ ALGORITHM = settings.algorithm
12
+
13
+
14
+ class AuthException(Exception):
15
+ """Custom exception for authentication-related errors"""
16
+ def __init__(self, error_type: str, message: str):
17
+ self.error_type = error_type
18
+ self.message = message
19
+ super().__init__(self.message)
20
+
21
+
22
+ class AuthService:
23
+ def __init__(self):
24
+ pass
25
+
26
+ def create_access_token(self, user_id: int, expires_delta: Optional[timedelta] = None):
27
+ """Create a new JWT access token for a user"""
28
+ to_encode = {"sub": str(user_id)}
29
+
30
+ if expires_delta:
31
+ expire = datetime.utcnow() + expires_delta
32
+ else:
33
+ expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes)
34
+
35
+ to_encode.update({"exp": expire, "iat": datetime.utcnow()})
36
+
37
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
38
+ return encoded_jwt
39
+
40
+ def verify_token(self, token: str) -> Optional[int]:
41
+ """Verify JWT token and return user ID if valid"""
42
+ try:
43
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
44
+ user_id: str = payload.get("sub")
45
+ if user_id is None:
46
+ return None
47
+ return int(user_id)
48
+ except JWTError:
49
+ return None
50
+
51
+ def authenticate_user(self, session: Session, email: str, password: str) -> Optional[Dict[str, Any]]:
52
+ """
53
+ Authenticate user with enhanced error handling to differentiate between email and password errors.
54
+
55
+ Args:
56
+ session: Database session
57
+ email: User's email address
58
+ password: User's password
59
+
60
+ Returns:
61
+ Dict with user info and token if authentication successful, None otherwise
62
+ """
63
+ # Find user by email
64
+ statement = select(User).where(User.email == email)
65
+ user = session.exec(statement).first()
66
+
67
+ if user is None:
68
+ # User with this email doesn't exist
69
+ raise AuthException(
70
+ error_type="EMAIL_NOT_FOUND",
71
+ message="Invalid email or password"
72
+ )
73
+
74
+ # At this point, we know the email exists, so we check the password
75
+ # Import here to avoid circular imports
76
+ from passlib.context import CryptContext
77
+
78
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
79
+
80
+ if not pwd_context.verify(password, user.password):
81
+ # Email exists but password is incorrect
82
+ raise AuthException(
83
+ error_type="INVALID_PASSWORD",
84
+ message="Invalid email or password"
85
+ )
86
+
87
+ # Authentication successful
88
+ token = self.create_access_token(user.id)
89
+ return {
90
+ "user": user,
91
+ "token": token
92
+ }
93
+
94
+ def authenticate_user_detailed_errors(self, session: Session, email: str, password: str) -> Optional[Dict[str, Any]]:
95
+ """
96
+ Authenticate user with detailed error messages for different error types.
97
+ This method is used for the enhanced error handling feature.
98
+
99
+ Args:
100
+ session: Database session
101
+ email: User's email address
102
+ password: User's password
103
+
104
+ Returns:
105
+ Dict with user info and token if authentication successful, None otherwise
106
+ """
107
+ # Find user by email
108
+ statement = select(User).where(User.email == email)
109
+ user = session.exec(statement).first()
110
+
111
+ if user is None:
112
+ # User with this email doesn't exist
113
+ raise AuthException(
114
+ error_type="EMAIL_NOT_FOUND",
115
+ message="No account found with this email address"
116
+ )
117
+
118
+ # At this point, we know the email exists, so we check the password
119
+ # Import here to avoid circular imports
120
+ from passlib.context import CryptContext
121
+
122
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
123
+
124
+ if not pwd_context.verify(password, user.password):
125
+ # Email exists but password is incorrect
126
+ raise AuthException(
127
+ error_type="INVALID_PASSWORD",
128
+ message="Incorrect password"
129
+ )
130
+
131
+ # Authentication successful
132
+ token = self.create_access_token(user.id)
133
+ return {
134
+ "user": user,
135
+ "token": token
136
+ }
137
+
138
+ def authenticate_user_secure(self, session: Session, email: str, password: str) -> Optional[Dict[str, Any]]:
139
+ """
140
+ Secure authentication that doesn't reveal whether an email exists in the system.
141
+ This maintains security best practices while still providing helpful feedback.
142
+
143
+ Args:
144
+ session: Database session
145
+ email: User's email address
146
+ password: User's password
147
+
148
+ Returns:
149
+ Dict with user info and token if authentication successful, None otherwise
150
+ """
151
+ # Find user by email
152
+ statement = select(User).where(User.email == email)
153
+ user = session.exec(statement).first()
154
+
155
+ # Always perform password verification to prevent timing attacks
156
+ from passlib.context import CryptContext
157
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
158
+
159
+ # If user doesn't exist, create a fake hash to compare against for timing consistency
160
+ if user is None:
161
+ # Use a fake password to maintain consistent timing
162
+ pwd_context.hash("fake_password_for_timing_attack_prevention")
163
+ raise AuthException(
164
+ error_type="AUTH_FAILED",
165
+ message="Invalid email or password"
166
+ )
167
+
168
+ # If user exists, verify the actual password
169
+ if not pwd_context.verify(password, user.password):
170
+ raise AuthException(
171
+ error_type="AUTH_FAILED",
172
+ message="Invalid email or password"
173
+ )
174
+
175
+ # Authentication successful
176
+ token = self.create_access_token(user.id)
177
+ return {
178
+ "user": user,
179
+ "token": token
180
+ }
181
+
182
+ def register_user(self, session: Session, email: str, password: str, name: Optional[str] = None,
183
+ date_of_birth: Optional[str] = None, signup_date: Optional[datetime] = None) -> Optional[Dict[str, Any]]:
184
+ """
185
+ Register a new user with signup date validation.
186
+
187
+ Args:
188
+ session: Database session
189
+ email: User's email address
190
+ password: User's password
191
+ name: Optional user name
192
+ date_of_birth: Optional date of birth
193
+ signup_date: Signup date (will be set to now if not provided)
194
+
195
+ Returns:
196
+ Dict with user info and token if registration successful, None otherwise
197
+ """
198
+ # Check if user already exists
199
+ statement = select(User).where(User.email == email)
200
+ existing_user = session.exec(statement).first()
201
+
202
+ if existing_user:
203
+ raise AuthException(
204
+ error_type="EMAIL_EXISTS",
205
+ message="A user with this email already exists"
206
+ )
207
+
208
+ # Hash the password
209
+ from passlib.context import CryptContext
210
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
211
+ hashed_password = pwd_context.hash(password)
212
+
213
+ # Validate and set signup date
214
+ validated_signup_date = validate_signup_date(signup_date)
215
+
216
+ # Create new user
217
+ user = User(
218
+ email=email,
219
+ password=hashed_password,
220
+ name=name,
221
+ date_of_birth=date_of_birth,
222
+ signup_date=validated_signup_date # Non-nullable field
223
+ )
224
+
225
+ session.add(user)
226
+ session.commit()
227
+ session.refresh(user)
228
+
229
+ # Create access token
230
+ token = self.create_access_token(user.id)
231
+
232
+ return {
233
+ "user": user,
234
+ "token": token
235
+ }
src/services/conversation_service.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation Service for the Todo Backend API.
3
+
4
+ Handles all conversation-related operations including creation, retrieval, and message management.
5
+ """
6
+ from typing import List, Optional
7
+ from sqlmodel import select
8
+ from sqlmodel.ext.asyncio.session import AsyncSession
9
+
10
+ from ..models.conversation import Conversation, ConversationCreate
11
+ from ..models.message import Message, MessageCreate
12
+
13
+
14
+ class ConversationService:
15
+ """
16
+ Service class to handle conversation operations.
17
+ """
18
+
19
+ @staticmethod
20
+ async def create_conversation(
21
+ session: AsyncSession,
22
+ conversation: ConversationCreate
23
+ ) -> Conversation:
24
+ """
25
+ Create a new conversation.
26
+
27
+ Args:
28
+ session: Database session
29
+ conversation: Conversation data to create
30
+
31
+ Returns:
32
+ Created Conversation object
33
+ """
34
+ # The user_id should already be string due to the updated model
35
+ db_conversation = Conversation.model_validate(conversation)
36
+ session.add(db_conversation)
37
+ await session.commit()
38
+ await session.refresh(db_conversation)
39
+ return db_conversation
40
+
41
+ @staticmethod
42
+ async def get_conversation_by_id(
43
+ session: AsyncSession,
44
+ conversation_id: int,
45
+ user_id: int
46
+ ) -> Optional[Conversation]:
47
+ """
48
+ Get a conversation by its ID for a specific user.
49
+
50
+ Args:
51
+ session: Database session
52
+ conversation_id: ID of the conversation to retrieve
53
+ user_id: ID of the user who owns the conversation
54
+
55
+ Returns:
56
+ Conversation object if found, None otherwise
57
+ """
58
+ statement = select(Conversation).where(
59
+ Conversation.id == conversation_id,
60
+ Conversation.user_id == user_id
61
+ )
62
+ result = await session.execute(statement)
63
+ return result.scalar_one_or_none()
64
+
65
+ @staticmethod
66
+ async def get_conversations_by_user_id(
67
+ session: AsyncSession,
68
+ user_id: int
69
+ ) -> List[Conversation]:
70
+ """
71
+ Get all conversations for a specific user.
72
+
73
+ Args:
74
+ session: Database session
75
+ user_id: ID of the user whose conversations to retrieve
76
+
77
+ Returns:
78
+ List of Conversation objects
79
+ """
80
+ statement = select(Conversation).where(Conversation.user_id == user_id)
81
+ result = await session.execute(statement)
82
+ return result.scalars().all()
83
+
84
+ @staticmethod
85
+ async def add_message_to_conversation(
86
+ session: AsyncSession,
87
+ message: MessageCreate
88
+ ) -> Message:
89
+ """
90
+ Add a message to a conversation.
91
+
92
+ Args:
93
+ session: Database session
94
+ message: Message data to add
95
+
96
+ Returns:
97
+ Created Message object
98
+ """
99
+ db_message = Message.model_validate(message)
100
+ session.add(db_message)
101
+ await session.commit()
102
+ await session.refresh(db_message)
103
+ return db_message
104
+
105
+ @staticmethod
106
+ async def get_messages_by_conversation_id(
107
+ session: AsyncSession,
108
+ conversation_id: int
109
+ ) -> List[Message]:
110
+ """
111
+ Get all messages for a specific conversation.
112
+
113
+ Args:
114
+ session: Database session
115
+ conversation_id: ID of the conversation whose messages to retrieve
116
+
117
+ Returns:
118
+ List of Message objects
119
+ """
120
+ statement = select(Message).where(Message.conversation_id == conversation_id)
121
+ result = await session.execute(statement)
122
+ return result.scalars().all()
123
+
124
+ @staticmethod
125
+ async def delete_conversation(
126
+ session: AsyncSession,
127
+ conversation_id: int,
128
+ user_id: int
129
+ ) -> bool:
130
+ """
131
+ Delete a conversation by its ID for a specific user.
132
+
133
+ Args:
134
+ session: Database session
135
+ conversation_id: ID of the conversation to delete
136
+ user_id: ID of the user who owns the conversation
137
+
138
+ Returns:
139
+ True if conversation was deleted, False otherwise
140
+ """
141
+ conversation = await ConversationService.get_conversation_by_id(
142
+ session, conversation_id, user_id
143
+ )
144
+
145
+ if not conversation:
146
+ return False
147
+
148
+ await session.delete(conversation)
149
+ await session.commit()
150
+ return True
src/services/task_service.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ from datetime import datetime
3
+
4
+ import sqlalchemy as sa
5
+ from sqlmodel import select
6
+ from sqlmodel.ext.asyncio.session import AsyncSession
7
+ from sqlalchemy.exc import IntegrityError
8
+
9
+ from ..models.task import Task, TaskCreate, TaskUpdate, TaskRead
10
+ from ..utils.error_handlers import NotFoundError, ValidationError, UnauthorizedError
11
+
12
+
13
+ class TaskService:
14
+ """Service class for handling task-related business logic."""
15
+
16
+ @staticmethod
17
+ async def create_task(session: AsyncSession, task_create: TaskCreate, user_id: str) -> TaskRead:
18
+ """
19
+ Create a new task for a user.
20
+
21
+ Args:
22
+ session: Database session
23
+ task_create: Task creation data
24
+ user_id: ID of the user creating the task
25
+
26
+ Returns:
27
+ Created task as TaskRead object
28
+ """
29
+ # Create task object with the authenticated user ID
30
+ # We need to create the Task object directly since TaskCreate doesn't include user_id
31
+ db_task = Task(
32
+ title=task_create.title,
33
+ description=task_create.description,
34
+ completed=task_create.completed,
35
+ user_id=str(user_id) # Ensure user_id is explicitly set as string
36
+ )
37
+
38
+ session.add(db_task)
39
+ await session.commit()
40
+ await session.refresh(db_task)
41
+
42
+ # Return as TaskRead object
43
+ return TaskRead.model_validate(db_task)
44
+
45
+ @staticmethod
46
+ async def get_task_by_id(session: AsyncSession, task_id: int, user_id: str) -> TaskRead:
47
+ """
48
+ Get a specific task by ID for a user.
49
+
50
+ Args:
51
+ session: Database session
52
+ task_id: ID of the task to retrieve
53
+ user_id: ID of the requesting user
54
+
55
+ Returns:
56
+ Task as TaskRead object
57
+
58
+ Raises:
59
+ NotFoundError: If task doesn't exist
60
+ UnauthorizedError: If task exists but doesn't belong to the user
61
+ """
62
+ # First, check if the task exists regardless of ownership
63
+ statement_exists = select(Task).where(Task.id == task_id)
64
+ result_exists = await session.execute(statement_exists)
65
+ task_exists = result_exists.scalar_one_or_none()
66
+
67
+ if not task_exists:
68
+ raise NotFoundError(message=f"Task with id {task_id} not found")
69
+
70
+ # Now check if the user owns the task - ensuring both sides are strings for comparison
71
+ statement = select(Task).where(Task.id == task_id, Task.user_id == str(user_id))
72
+ result = await session.execute(statement)
73
+ task = result.scalar_one_or_none()
74
+
75
+ if not task:
76
+ # Task exists but doesn't belong to the user - return 401 Unauthorized
77
+ raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
78
+
79
+ return TaskRead.model_validate(task)
80
+
81
+ @staticmethod
82
+ async def get_tasks_for_user(session: AsyncSession, user_id: str, limit: int = 20, offset: int = 0) -> List[TaskRead]:
83
+ """
84
+ Get all tasks for a specific user.
85
+
86
+ Args:
87
+ session: Database session
88
+ user_id: ID of the user whose tasks to retrieve
89
+ limit: Maximum number of tasks to return
90
+ offset: Number of tasks to skip
91
+
92
+ Returns:
93
+ List of tasks as TaskRead objects
94
+ """
95
+ statement = select(Task).where(Task.user_id == str(user_id)).offset(offset).limit(limit)
96
+ result = await session.execute(statement)
97
+ tasks = result.scalars().all()
98
+
99
+ return [TaskRead.model_validate(task) for task in tasks]
100
+
101
+ @staticmethod
102
+ async def update_task(session: AsyncSession, task_id: int, task_update: TaskUpdate, user_id: str) -> TaskRead:
103
+ """
104
+ Update a specific task for a user.
105
+
106
+ Args:
107
+ session: Database session
108
+ task_id: ID of the task to update
109
+ task_update: Task update data
110
+ user_id: ID of the requesting user
111
+
112
+ Returns:
113
+ Updated task as TaskRead object
114
+
115
+ Raises:
116
+ NotFoundError: If task doesn't exist
117
+ UnauthorizedError: If task exists but doesn't belong to the user
118
+ """
119
+ # First, check if the task exists regardless of ownership
120
+ statement_exists = select(Task).where(Task.id == task_id)
121
+ result_exists = await session.execute(statement_exists)
122
+ task_exists = result_exists.scalar_one_or_none()
123
+
124
+ if not task_exists:
125
+ raise NotFoundError(message=f"Task with id {task_id} not found")
126
+
127
+ # Now check if the user owns the task - ensuring both sides are strings for comparison
128
+ statement = select(Task).where(Task.id == task_id, Task.user_id == str(user_id))
129
+ result = await session.execute(statement)
130
+ task = result.scalar_one_or_none()
131
+
132
+ if not task:
133
+ # Task exists but doesn't belong to the user - return 401 Unauthorized
134
+ raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
135
+
136
+ # Update task fields with provided values
137
+ update_data = task_update.model_dump(exclude_unset=True)
138
+ for field, value in update_data.items():
139
+ setattr(task, field, value)
140
+
141
+ task.updated_at = datetime.utcnow()
142
+
143
+ session.add(task)
144
+ await session.commit()
145
+ await session.refresh(task)
146
+
147
+ return TaskRead.model_validate(task)
148
+
149
+ @staticmethod
150
+ async def delete_task(session: AsyncSession, task_id: int, user_id: str) -> bool:
151
+ """
152
+ Delete a specific task for a user.
153
+
154
+ Args:
155
+ session: Database session
156
+ task_id: ID of the task to delete
157
+ user_id: ID of the requesting user
158
+
159
+ Returns:
160
+ True if task was deleted, False otherwise
161
+
162
+ Raises:
163
+ NotFoundError: If task doesn't exist
164
+ UnauthorizedError: If task exists but doesn't belong to the user
165
+ """
166
+ # First, check if the task exists regardless of ownership
167
+ statement_exists = select(Task).where(Task.id == task_id)
168
+ result_exists = await session.execute(statement_exists)
169
+ task_exists = result_exists.scalar_one_or_none()
170
+
171
+ if not task_exists:
172
+ raise NotFoundError(message=f"Task with id {task_id} not found")
173
+
174
+ # Now check if the user owns the task - ensuring both sides are strings for comparison
175
+ statement = select(Task).where(Task.id == task_id, Task.user_id == str(user_id))
176
+ result = await session.execute(statement)
177
+ task = result.scalar_one_or_none()
178
+
179
+ if not task:
180
+ # Task exists but doesn't belong to the user - return 401 Unauthorized
181
+ raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
182
+
183
+ await session.delete(task)
184
+ await session.commit()
185
+
186
+ return True
187
+
188
+ @staticmethod
189
+ async def toggle_task_completion(session: AsyncSession, task_id: int, user_id: str) -> TaskRead:
190
+ """
191
+ Toggle the completion status of a specific task.
192
+
193
+ Args:
194
+ session: Database session
195
+ task_id: ID of the task to toggle
196
+ user_id: ID of the requesting user
197
+
198
+ Returns:
199
+ Updated task as TaskRead object
200
+
201
+ Raises:
202
+ NotFoundError: If task doesn't exist
203
+ UnauthorizedError: If task exists but doesn't belong to the user
204
+ """
205
+ # First, check if the task exists regardless of ownership
206
+ statement_exists = select(Task).where(Task.id == task_id)
207
+ result_exists = await session.execute(statement_exists)
208
+ task_exists = result_exists.scalar_one_or_none()
209
+
210
+ if not task_exists:
211
+ raise NotFoundError(message=f"Task with id {task_id} not found")
212
+
213
+ # Now check if the user owns the task - ensuring both sides are strings for comparison
214
+ statement = select(Task).where(Task.id == task_id, Task.user_id == str(user_id))
215
+ result = await session.execute(statement)
216
+ task = result.scalar_one_or_none()
217
+
218
+ if not task:
219
+ # Task exists but doesn't belong to the user - return 401 Unauthorized
220
+ raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
221
+
222
+ # Toggle the completion status
223
+ task.completed = not task.completed
224
+ task.updated_at = datetime.utcnow()
225
+
226
+ session.add(task)
227
+ await session.commit()
228
+ await session.refresh(task)
229
+
230
+ return TaskRead.model_validate(task)
231
+
232
+ @staticmethod
233
+ async def verify_task_ownership(session: AsyncSession, task_id: int, user_id: str) -> bool:
234
+ """
235
+ Verify if a user owns a specific task.
236
+
237
+ Args:
238
+ session: Database session
239
+ task_id: ID of the task to check
240
+ user_id: ID of the user to check ownership for
241
+
242
+ Returns:
243
+ True if the user owns the task, False otherwise
244
+ """
245
+ statement = select(Task).where(Task.id == task_id, Task.user_id == str(user_id))
246
+ result = await session.execute(statement)
247
+ task = result.scalar_one_or_none()
248
+
249
+ return task is not None
src/services/user_service.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from sqlmodel import Session, select
3
+ from datetime import datetime
4
+ from ..models.user import User, UserCreate, UserRead
5
+ from ..utils.date_validator import validate_signup_date
6
+
7
+
8
+ class UserService:
9
+ def __init__(self):
10
+ pass
11
+
12
+ def get_user_by_email(self, session: Session, email: str) -> Optional[User]:
13
+ """Retrieve a user by their email address."""
14
+ statement = select(User).where(User.email == email)
15
+ user = session.exec(statement).first()
16
+ return user
17
+
18
+ def get_user_by_id(self, session: Session, user_id: int) -> Optional[User]:
19
+ """Retrieve a user by their ID."""
20
+ user = session.get(User, user_id)
21
+ return user
22
+
23
+ def create_user(self, session: Session, user_data: UserCreate, signup_date: Optional[datetime] = None) -> User:
24
+ """
25
+ Create a new user with proper signup date validation.
26
+
27
+ Args:
28
+ session: Database session
29
+ user_data: User creation data
30
+ signup_date: Signup date (defaults to current time if not provided)
31
+
32
+ Returns:
33
+ User: The created user object
34
+ """
35
+ # Validate and set signup date
36
+ validated_signup_date = validate_signup_date(signup_date)
37
+
38
+ # Create user object with validated signup date
39
+ user = User(
40
+ email=user_data.email,
41
+ password=user_data.password, # Should be hashed before this
42
+ name=user_data.name,
43
+ date_of_birth=getattr(user_data, 'date_of_birth', None),
44
+ signup_date=validated_signup_date # Non-nullable field, enforced here
45
+ )
46
+
47
+ session.add(user)
48
+ session.commit()
49
+ session.refresh(user)
50
+
51
+ return user
52
+
53
+ def update_user(self, session: Session, user_id: int, **kwargs) -> Optional[User]:
54
+ """Update user information."""
55
+ user = session.get(User, user_id)
56
+ if not user:
57
+ return None
58
+
59
+ # Update allowed fields
60
+ for field, value in kwargs.items():
61
+ if hasattr(user, field):
62
+ setattr(user, field, value)
63
+
64
+ session.add(user)
65
+ session.commit()
66
+ session.refresh(user)
67
+
68
+ return user
69
+
70
+ def delete_user(self, session: Session, user_id: int) -> bool:
71
+ """Delete a user by ID."""
72
+ user = session.get(User, user_id)
73
+ if not user:
74
+ return False
75
+
76
+ session.delete(user)
77
+ session.commit()
78
+ return True
79
+
80
+ def validate_user_data(self, user_data: UserCreate) -> dict:
81
+ """
82
+ Validate user data before creating/updating.
83
+
84
+ Args:
85
+ user_data: User data to validate
86
+
87
+ Returns:
88
+ dict: Validation results with 'valid' boolean and 'errors' list
89
+ """
90
+ errors = []
91
+
92
+ # Validate email format (basic check)
93
+ if '@' not in user_data.email or '.' not in user_data.email.split('@')[1]:
94
+ errors.append("Invalid email format")
95
+
96
+ # Validate password strength (basic check)
97
+ if len(user_data.password) < 6:
98
+ errors.append("Password must be at least 6 characters long")
99
+
100
+ # Validate signup date if provided
101
+ if hasattr(user_data, 'signup_date') and user_data.signup_date is not None:
102
+ try:
103
+ validate_signup_date(user_data.signup_date)
104
+ except ValueError as e:
105
+ errors.append(str(e))
106
+
107
+ return {
108
+ "valid": len(errors) == 0,
109
+ "errors": errors
110
+ }
111
+
112
+ def get_all_users(self, session: Session, skip: int = 0, limit: int = 100) -> list[User]:
113
+ """Retrieve all users with pagination."""
114
+ statement = select(User).offset(skip).limit(limit)
115
+ users = session.exec(statement).all()
116
+ return users
src/utils/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ Utilities package for the Todo Backend API.
3
+
4
+ Contains utility functions and classes.
5
+ """
src/utils/date_validator.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Union, Optional
3
+ import re
4
+
5
+
6
+ def validate_signup_date(date_input: Union[str, datetime, None]) -> datetime:
7
+ """
8
+ Validates and normalizes the signup date input.
9
+
10
+ Args:
11
+ date_input: The date input which can be a string, datetime object, or None
12
+
13
+ Returns:
14
+ datetime: A valid datetime object representing the signup date
15
+
16
+ Raises:
17
+ ValueError: If the date input is invalid or cannot be parsed
18
+ """
19
+ if date_input is None:
20
+ return datetime.utcnow()
21
+
22
+ if isinstance(date_input, datetime):
23
+ return date_input
24
+
25
+ if isinstance(date_input, str):
26
+ # Try to parse ISO format first (YYYY-MM-DDTHH:MM:SS.ssssss or YYYY-MM-DDTHH:MM:SS)
27
+ iso_formats = [
28
+ "%Y-%m-%dT%H:%M:%S.%f",
29
+ "%Y-%m-%dT%H:%M:%S",
30
+ "%Y-%m-%d %H:%M:%S.%f",
31
+ "%Y-%m-%d %H:%M:%S",
32
+ "%Y-%m-%d"
33
+ ]
34
+
35
+ for fmt in iso_formats:
36
+ try:
37
+ return datetime.strptime(date_input, fmt)
38
+ except ValueError:
39
+ continue
40
+
41
+ # Try common alternative formats
42
+ alt_formats = [
43
+ "%m/%d/%Y %H:%M:%S",
44
+ "%m/%d/%Y",
45
+ "%d/%m/%Y",
46
+ "%Y.%m.%d"
47
+ ]
48
+
49
+ for fmt in alt_formats:
50
+ try:
51
+ return datetime.strptime(date_input, fmt)
52
+ except ValueError:
53
+ continue
54
+
55
+ # If none of the formats worked, raise an error
56
+ raise ValueError(f"Unable to parse date string: {date_input}")
57
+
58
+ raise ValueError(f"Invalid date input type: {type(date_input)}. Expected str, datetime, or None")
59
+
60
+
61
+ def is_valid_date_format(date_str: str) -> bool:
62
+ """
63
+ Checks if a date string is in a valid format.
64
+
65
+ Args:
66
+ date_str: The date string to validate
67
+
68
+ Returns:
69
+ bool: True if the date string is in a valid format, False otherwise
70
+ """
71
+ try:
72
+ validate_signup_date(date_str)
73
+ return True
74
+ except ValueError:
75
+ return False
76
+
77
+
78
+ def normalize_date_to_utc(date_input: Union[str, datetime]) -> datetime:
79
+ """
80
+ Normalizes a date input to UTC timezone.
81
+
82
+ Args:
83
+ date_input: The date input to normalize
84
+
85
+ Returns:
86
+ datetime: The normalized datetime in UTC
87
+ """
88
+ dt = validate_signup_date(date_input)
89
+ # Assuming naive datetime is in local timezone, convert to UTC
90
+ # For simplicity, if it's naive, treat as local time and convert to UTC
91
+ if dt.tzinfo is None:
92
+ # For this implementation, we'll assume it's already in UTC or convert appropriately
93
+ return dt
94
+ else:
95
+ # If it has timezone info, convert to UTC
96
+ return dt.utctimetuple()
97
+
98
+
99
+ def validate_and_format_signup_date(date_input: Union[str, datetime, None]) -> dict:
100
+ """
101
+ Validates a signup date and returns a formatted response.
102
+
103
+ Args:
104
+ date_input: The date input to validate
105
+
106
+ Returns:
107
+ dict: A dictionary containing the validated date and any validation messages
108
+ """
109
+ try:
110
+ validated_date = validate_signup_date(date_input)
111
+ return {
112
+ "valid": True,
113
+ "date": validated_date,
114
+ "formatted_iso": validated_date.isoformat(),
115
+ "message": "Date is valid"
116
+ }
117
+ except ValueError as e:
118
+ return {
119
+ "valid": False,
120
+ "date": None,
121
+ "formatted_iso": None,
122
+ "message": str(e)
123
+ }
src/utils/error_handlers.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Request, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ from typing import Dict, Any
4
+
5
+
6
+ class APIError(Exception):
7
+ """Base exception class for API errors."""
8
+
9
+ def __init__(self, message: str, code: str, status_code: int = 400):
10
+ self.message = message
11
+ self.code = code
12
+ self.status_code = status_code
13
+ super().__init__(self.message)
14
+
15
+
16
+ class ValidationError(APIError):
17
+ """Exception raised for validation errors."""
18
+
19
+ def __init__(self, message: str = "Invalid request data"):
20
+ super().__init__(message=message, code="VALIDATION_001", status_code=400)
21
+
22
+
23
+ class NotFoundError(APIError):
24
+ """Exception raised when a resource is not found."""
25
+
26
+ def __init__(self, message: str = "Resource not found"):
27
+ super().__init__(message=message, code="RESOURCE_001", status_code=404)
28
+
29
+
30
+ class UnauthorizedError(APIError):
31
+ """Exception raised when authentication fails."""
32
+
33
+ def __init__(self, message: str = "Unauthorized access"):
34
+ super().__init__(message=message, code="AUTH_001", status_code=401)
35
+
36
+
37
+ class ForbiddenError(APIError):
38
+ """Exception raised when authorization fails."""
39
+
40
+ def __init__(self, message: str = "Access forbidden"):
41
+ super().__init__(message=message, code="ACCESS_001", status_code=403)
42
+
43
+
44
+ class InternalServerError(APIError):
45
+ """Exception raised for internal server errors."""
46
+
47
+ def __init__(self, message: str = "Internal server error"):
48
+ super().__init__(message=message, code="SERVER_001", status_code=500)
49
+
50
+
51
+ async def validation_error_handler(request: Request, exc: ValidationError) -> JSONResponse:
52
+ """Handle validation errors."""
53
+ return JSONResponse(
54
+ status_code=exc.status_code,
55
+ content={
56
+ "success": False,
57
+ "error": {
58
+ "code": exc.code,
59
+ "message": exc.message
60
+ }
61
+ }
62
+ )
63
+
64
+
65
+ async def not_found_error_handler(request: Request, exc: NotFoundError) -> JSONResponse:
66
+ """Handle not found errors."""
67
+ return JSONResponse(
68
+ status_code=exc.status_code,
69
+ content={
70
+ "success": False,
71
+ "error": {
72
+ "code": exc.code,
73
+ "message": exc.message
74
+ }
75
+ }
76
+ )
77
+
78
+
79
+ async def unauthorized_error_handler(request: Request, exc: UnauthorizedError) -> JSONResponse:
80
+ """Handle unauthorized errors."""
81
+ return JSONResponse(
82
+ status_code=exc.status_code,
83
+ content={
84
+ "success": False,
85
+ "error": {
86
+ "code": exc.code,
87
+ "message": exc.message
88
+ }
89
+ }
90
+ )
91
+
92
+
93
+ async def forbidden_error_handler(request: Request, exc: ForbiddenError) -> JSONResponse:
94
+ """Handle forbidden errors."""
95
+ return JSONResponse(
96
+ status_code=exc.status_code,
97
+ content={
98
+ "success": False,
99
+ "error": {
100
+ "code": exc.code,
101
+ "message": exc.message
102
+ }
103
+ }
104
+ )
105
+
106
+
107
+ async def internal_server_error_handler(request: Request, exc: InternalServerError) -> JSONResponse:
108
+ """Handle internal server errors."""
109
+ return JSONResponse(
110
+ status_code=exc.status_code,
111
+ content={
112
+ "success": False,
113
+ "error": {
114
+ "code": exc.code,
115
+ "message": exc.message
116
+ }
117
+ }
118
+ )
119
+
120
+
121
+ async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
122
+ """Handle HTTP exceptions."""
123
+ error_code_map = {
124
+ 400: "VALIDATION_001",
125
+ 401: "AUTH_001",
126
+ 403: "ACCESS_001",
127
+ 404: "RESOURCE_001",
128
+ 500: "SERVER_001"
129
+ }
130
+
131
+ error_code = error_code_map.get(exc.status_code, f"HTTP_{exc.status_code}")
132
+
133
+ return JSONResponse(
134
+ status_code=exc.status_code,
135
+ content={
136
+ "success": False,
137
+ "error": {
138
+ "code": error_code,
139
+ "message": str(exc.detail) if hasattr(exc, 'detail') else "An error occurred"
140
+ }
141
+ }
142
+ )
143
+
144
+
145
+ def add_exception_handlers(app):
146
+ """Add all exception handlers to the FastAPI app."""
147
+ app.add_exception_handler(ValidationError, validation_error_handler)
148
+ app.add_exception_handler(NotFoundError, not_found_error_handler)
149
+ app.add_exception_handler(UnauthorizedError, unauthorized_error_handler)
150
+ app.add_exception_handler(ForbiddenError, forbidden_error_handler)
151
+ app.add_exception_handler(InternalServerError, internal_server_error_handler)
152
+ app.add_exception_handler(HTTPException, http_exception_handler)
src/utils/jwt_utils.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timedelta
2
+ from typing import Optional
3
+
4
+ from jose import JWTError, jwt
5
+ from passlib.context import CryptContext
6
+
7
+ from ..config import settings
8
+
9
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
10
+
11
+
12
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
13
+ """Verify a plaintext password against a hashed password."""
14
+ return pwd_context.verify(plain_password, hashed_password)
15
+
16
+
17
+ def get_password_hash(password: str) -> str:
18
+ """Hash a plaintext password."""
19
+ return pwd_context.hash(password)
20
+
21
+
22
+ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
23
+ """
24
+ Create a JWT access token.
25
+
26
+ Args:
27
+ data: Dictionary containing the data to encode in the token
28
+ expires_delta: Optional timedelta for token expiration
29
+
30
+ Returns:
31
+ Encoded JWT token as string
32
+ """
33
+ to_encode = data.copy()
34
+ if expires_delta:
35
+ expire = datetime.utcnow() + expires_delta
36
+ else:
37
+ expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes)
38
+
39
+ to_encode.update({"exp": expire})
40
+ encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
41
+ return encoded_jwt
42
+
43
+
44
+ def decode_access_token(token: str) -> Optional[dict]:
45
+ """
46
+ Decode a JWT access token.
47
+
48
+ Args:
49
+ token: JWT token to decode
50
+
51
+ Returns:
52
+ Decoded token payload as dictionary or None if invalid
53
+ """
54
+ try:
55
+ payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
56
+ return payload
57
+ except JWTError:
58
+ return None
src/utils/logger.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from datetime import datetime
3
+ from typing import Optional
4
+ import json
5
+
6
+ # Configure the root logger
7
+ logging.basicConfig(level=logging.INFO)
8
+
9
+ # Reduce SQLAlchemy logging to reduce noise
10
+ logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
11
+ logging.getLogger('sqlalchemy.dialects').setLevel(logging.WARNING)
12
+ logging.getLogger('sqlalchemy.pool').setLevel(logging.WARNING)
13
+ logging.getLogger('sqlalchemy.orm').setLevel(logging.WARNING)
14
+
15
+ # Create a custom logger for the application
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Create handlers
19
+ console_handler = logging.StreamHandler()
20
+ console_handler.setLevel(logging.INFO)
21
+
22
+ # Create formatters and add them to handlers
23
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
24
+ console_handler.setFormatter(formatter)
25
+
26
+ # Add handlers to the logger
27
+ logger.addHandler(console_handler)
28
+
29
+ class SecurityLogger:
30
+ """Custom logger for security-related events."""
31
+
32
+ @staticmethod
33
+ def log_task_access_attempt(user_id: int, task_id: int, action: str, success: bool, ip_address: Optional[str] = None):
34
+ """Log task access attempts for security monitoring."""
35
+ log_data = {
36
+ "timestamp": datetime.utcnow().isoformat(),
37
+ "event_type": "task_access",
38
+ "user_id": user_id,
39
+ "task_id": task_id,
40
+ "action": action,
41
+ "success": success,
42
+ "ip_address": ip_address
43
+ }
44
+
45
+ log_message = f"Task access attempt: {json.dumps(log_data)}"
46
+
47
+ if success:
48
+ logger.info(log_message)
49
+ else:
50
+ logger.warning(log_message)
51
+
52
+ @staticmethod
53
+ def log_authentication_event(event_type: str, user_id: Optional[int] = None, ip_address: Optional[str] = None, details: Optional[str] = None):
54
+ """Log authentication events for security monitoring."""
55
+ log_data = {
56
+ "timestamp": datetime.utcnow().isoformat(),
57
+ "event_type": event_type,
58
+ "user_id": user_id,
59
+ "ip_address": ip_address,
60
+ "details": details
61
+ }
62
+
63
+ log_message = f"Authentication event: {json.dumps(log_data)}"
64
+
65
+ if event_type in ["login_success", "logout"]:
66
+ logger.info(log_message)
67
+ elif event_type in ["login_failure", "auth_failure", "access_denied"]:
68
+ logger.warning(log_message)
69
+ else:
70
+ logger.info(log_message)
71
+
72
+ @staticmethod
73
+ def log_unauthorized_access(endpoint: str, user_id: Optional[int] = None, ip_address: Optional[str] = None):
74
+ """Log unauthorized access attempts."""
75
+ log_data = {
76
+ "timestamp": datetime.utcnow().isoformat(),
77
+ "event_type": "unauthorized_access",
78
+ "endpoint": endpoint,
79
+ "user_id": user_id,
80
+ "ip_address": ip_address
81
+ }
82
+
83
+ log_message = f"Unauthorized access attempt: {json.dumps(log_data)}"
84
+ logger.warning(log_message)
85
+
86
+ # Convenience functions
87
+ def log_task_access(user_id: int, task_id: int, action: str, success: bool = True, ip_address: Optional[str] = None):
88
+ """Convenience function to log task access."""
89
+ SecurityLogger.log_task_access_attempt(user_id, task_id, action, success, ip_address)
90
+
91
+ def log_auth_event(event_type: str, user_id: Optional[int] = None, ip_address: Optional[str] = None, details: Optional[str] = None):
92
+ """Convenience function to log authentication events."""
93
+ SecurityLogger.log_authentication_event(event_type, user_id, ip_address, details)
94
+
95
+ def log_unauthorized(endpoint: str, user_id: Optional[int] = None, ip_address: Optional[str] = None):
96
+ """Convenience function to log unauthorized access."""
97
+ SecurityLogger.log_unauthorized_access(endpoint, user_id, ip_address)
tests/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """
2
+ Tests package for the Todo Backend API.
3
+
4
+ Contains all test modules.
5
+ """
tests/conftest.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from sqlalchemy import create_engine
3
+ from sqlalchemy.orm import sessionmaker
4
+ from sqlmodel import SQLModel
5
+
6
+ from src.database.database import AsyncSessionLocal, async_engine
7
+ from src.api.main import app
8
+
9
+
10
+ @pytest.fixture(scope="session")
11
+ def event_loop():
12
+ """Create an event loop for async tests."""
13
+ import asyncio
14
+ loop = asyncio.new_event_loop()
15
+ yield loop
16
+ loop.close()
17
+
18
+
19
+ @pytest.fixture
20
+ def client():
21
+ """Create a test client for the API."""
22
+ from fastapi.testclient import TestClient
23
+
24
+ with TestClient(app) as test_client:
25
+ yield test_client
26
+
27
+
28
+ @pytest.fixture
29
+ async def async_session():
30
+ """Create an async database session for testing."""
31
+ async with AsyncSessionLocal() as session:
32
+ yield session
tests/contract/test_api_contracts.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from fastapi.testclient import TestClient
3
+
4
+ from backend.src.api.main import app
5
+
6
+
7
+ @pytest.fixture
8
+ def client():
9
+ """Create a test client for the API."""
10
+ with TestClient(app) as test_client:
11
+ yield test_client
12
+
13
+
14
+ def test_get_tasks_contract(client):
15
+ """Test the contract for GET /api/tasks endpoint."""
16
+ # This would normally require authentication
17
+ headers = {"Authorization": "Bearer fake-token"}
18
+
19
+ response = client.get("/api/tasks/", headers=headers)
20
+
21
+ # The response should follow the contract format
22
+ if response.status_code != 401: # If not unauthorized (due to missing auth)
23
+ # If authorized, should return the expected format
24
+ assert "success" in response.json()
25
+ data = response.json()
26
+ assert isinstance(data["success"], bool)
27
+
28
+ if data["success"]:
29
+ assert "data" in data
30
+ assert "tasks" in data["data"]
31
+ assert isinstance(data["data"]["tasks"], list)
32
+
33
+
34
+ def test_post_tasks_contract(client):
35
+ """Test the contract for POST /api/tasks endpoint."""
36
+ headers = {"Authorization": "Bearer fake-token"}
37
+ task_data = {
38
+ "title": "Test Task",
39
+ "description": "Test Description",
40
+ "completed": False
41
+ }
42
+
43
+ response = client.post("/api/tasks/", json=task_data, headers=headers)
44
+
45
+ # The response should follow the contract format
46
+ if response.status_code not in [401, 422]: # If not unauthorized or validation error
47
+ assert "success" in response.json()
48
+ data = response.json()
49
+ assert isinstance(data["success"], bool)
50
+
51
+ if data["success"]:
52
+ assert "data" in data
53
+ assert "id" in data["data"] or "message" in data["data"]
54
+
55
+
56
+ def test_get_specific_task_contract(client):
57
+ """Test the contract for GET /api/tasks/{task_id} endpoint."""
58
+ headers = {"Authorization": "Bearer fake-token"}
59
+
60
+ response = client.get("/api/tasks/1", headers=headers)
61
+
62
+ # The response should follow the contract format
63
+ if response.status_code not in [401, 404]: # If not unauthorized or not found
64
+ assert "success" in response.json()
65
+ data = response.json()
66
+ assert isinstance(data["success"], bool)
67
+
68
+
69
+ def test_put_task_contract(client):
70
+ """Test the contract for PUT /api/tasks/{task_id} endpoint."""
71
+ headers = {"Authorization": "Bearer fake-token"}
72
+ update_data = {
73
+ "title": "Updated Task",
74
+ "description": "Updated Description",
75
+ "completed": True
76
+ }
77
+
78
+ response = client.put("/api/tasks/1", json=update_data, headers=headers)
79
+
80
+ # The response should follow the contract format
81
+ if response.status_code not in [401, 404, 422]: # If not unauthorized, not found, or validation error
82
+ assert "success" in response.json()
83
+ data = response.json()
84
+ assert isinstance(data["success"], bool)
85
+
86
+
87
+ def test_delete_task_contract(client):
88
+ """Test the contract for DELETE /api/tasks/{task_id} endpoint."""
89
+ headers = {"Authorization": "Bearer fake-token"}
90
+
91
+ response = client.delete("/api/tasks/1", headers=headers)
92
+
93
+ # The response should follow the contract format
94
+ if response.status_code not in [401, 404]: # If not unauthorized or not found
95
+ assert "success" in response.json()
96
+ data = response.json()
97
+ assert isinstance(data["success"], bool)
98
+
99
+
100
+ def test_patch_toggle_task_contract(client):
101
+ """Test the contract for PATCH /api/tasks/{task_id}/toggle endpoint."""
102
+ headers = {"Authorization": "Bearer fake-token"}
103
+
104
+ response = client.patch("/api/tasks/1/toggle", headers=headers)
105
+
106
+ # The response should follow the contract format
107
+ if response.status_code not in [401, 404]: # If not unauthorized or not found
108
+ assert "success" in response.json()
109
+ data = response.json()
110
+ assert isinstance(data["success"], bool)
tests/integration/test_task_endpoints.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from httpx import AsyncClient
3
+ from fastapi.testclient import TestClient
4
+
5
+ from backend.src.api.main import app
6
+ from backend.src.database.database import AsyncSessionLocal
7
+ from backend.src.models.task import Task, TaskCreate
8
+
9
+
10
+ @pytest.fixture
11
+ def client():
12
+ """Create a test client for the API."""
13
+ with TestClient(app) as test_client:
14
+ yield test_client
15
+
16
+
17
+ @pytest.mark.asyncio
18
+ async def test_secure_task_operations():
19
+ """Test that users can only access their own tasks."""
20
+ # This test would require proper authentication setup
21
+ # For now, we'll just verify the endpoints exist and return appropriate responses
22
+ async with AsyncClient(app=app, base_url="http://testserver") as ac:
23
+ # Test that endpoints require authentication
24
+ response = await ac.get("/api/tasks/")
25
+ assert response.status_code in [401, 403] # Unauthorized or Forbidden
26
+
27
+ response = await ac.post("/api/tasks/", json={"title": "Test", "user_id": 1})
28
+ assert response.status_code in [401, 403] # Unauthorized or Forbidden
29
+
30
+
31
+ def test_task_crud_operations(client):
32
+ """Test basic CRUD operations for tasks."""
33
+ # This test would require mocking authentication
34
+ # For now, we'll just check if the routes exist
35
+ headers = {"Authorization": "Bearer fake-token"}
36
+
37
+ # Test GET /api/tasks
38
+ response = client.get("/api/tasks/", headers=headers)
39
+ # This might return 401, 403, or 200 depending on auth implementation
40
+ assert response.status_code in [200, 401, 403]
41
+
42
+ # Test POST /api/tasks
43
+ task_data = {
44
+ "title": "Test Task",
45
+ "description": "Test Description",
46
+ "completed": False
47
+ }
48
+ response = client.post("/api/tasks/", json=task_data, headers=headers)
49
+ assert response.status_code in [200, 201, 401, 403, 422]
50
+
51
+
52
+ def test_task_update_and_delete(client):
53
+ """Test updating and deleting tasks."""
54
+ headers = {"Authorization": "Bearer fake-token"}
55
+
56
+ # These would require a created task first, which needs auth
57
+ # Just testing that endpoints exist
58
+ response = client.put("/api/tasks/1", json={"title": "Updated"}, headers=headers)
59
+ assert response.status_code in [200, 401, 403, 404, 422]
60
+
61
+ response = client.delete("/api/tasks/1", headers=headers)
62
+ assert response.status_code in [200, 204, 401, 403, 404]
tests/test_auth_api.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from fastapi.testclient import TestClient
3
+ from fastapi import HTTPException
4
+ from unittest.mock import Mock, patch, MagicMock
5
+ from datetime import datetime, timedelta
6
+ from sqlmodel import Session, SQLModel, create_engine
7
+ from sqlmodel.pool import StaticPool
8
+ from backend.src.main import app
9
+ from backend.src.models.user import User
10
+ from backend.src.database.database import get_session
11
+ from backend.src.services.auth_service import AuthService
12
+ from backend.src.utils.date_validator import validate_signup_date
13
+
14
+
15
+ @pytest.fixture
16
+ def client():
17
+ # Create an in-memory SQLite database for testing
18
+ engine = create_engine(
19
+ "sqlite:///:memory:",
20
+ connect_args={"check_same_thread": False},
21
+ poolclass=StaticPool,
22
+ )
23
+ SQLModel.metadata.create_all(engine)
24
+
25
+ with Session(engine) as session:
26
+
27
+ def get_test_session():
28
+ yield session
29
+
30
+ app.dependency_overrides[get_session] = get_test_session
31
+ with TestClient(app) as c:
32
+ yield c
33
+
34
+
35
+ class TestAuthAPI:
36
+ def test_signup_endpoint_success(self, client):
37
+ """Test successful user signup."""
38
+ signup_data = {
39
+ "email": "test@example.com",
40
+ "password": "securepassword",
41
+ "name": "Test User",
42
+ "date_of_birth": "1990-01-01",
43
+ "signup_date": datetime.utcnow().isoformat()
44
+ }
45
+
46
+ with patch('backend.src.api.routes.auth.get_password_hash') as mock_hash, \
47
+ patch('backend.src.api.routes.auth.create_access_token') as mock_create_token, \
48
+ patch('backend.src.utils.date_validator.validate_signup_date') as mock_validate_date:
49
+
50
+ mock_hash.return_value = 'hashed_password'
51
+ mock_create_token.return_value = 'mocked_token'
52
+ mock_validate_date.return_value = datetime.utcnow()
53
+
54
+ response = client.post("/auth/signup", json=signup_data)
55
+
56
+ assert response.status_code == 200
57
+ data = response.json()
58
+ assert data["success"] is True
59
+ assert "access_token" in data["data"]
60
+
61
+ def test_signup_endpoint_duplicate_email(self, client):
62
+ """Test signup with duplicate email."""
63
+ signup_data = {
64
+ "email": "duplicate@example.com",
65
+ "password": "securepassword",
66
+ "name": "Test User",
67
+ "date_of_birth": "1990-01-01",
68
+ "signup_date": datetime.utcnow().isoformat()
69
+ }
70
+
71
+ # First signup should succeed
72
+ with patch('backend.src.api.routes.auth.get_password_hash') as mock_hash, \
73
+ patch('backend.src.api.routes.auth.create_access_token') as mock_create_token, \
74
+ patch('backend.src.utils.date_validator.validate_signup_date') as mock_validate_date:
75
+
76
+ mock_hash.return_value = 'hashed_password'
77
+ mock_create_token.return_value = 'mocked_token'
78
+ mock_validate_date.return_value = datetime.utcnow()
79
+
80
+ # First signup
81
+ response1 = client.post("/auth/signup", json=signup_data)
82
+ assert response1.status_code == 200
83
+
84
+ # Second signup with same email should fail
85
+ response2 = client.post("/auth/signup", json=signup_data)
86
+ assert response2.status_code == 400
87
+
88
+ def test_signin_endpoint_success(self, client):
89
+ """Test successful sign in."""
90
+ signin_data = {
91
+ "email": "test@example.com",
92
+ "password": "securepassword"
93
+ }
94
+
95
+ # Mock user object
96
+ mock_user = User(
97
+ id=1,
98
+ email="test@example.com",
99
+ password="hashed_password",
100
+ signup_date=datetime.utcnow()
101
+ )
102
+
103
+ with patch('backend.src.services.auth_service.AuthService.authenticate_user_detailed_errors') as mock_auth, \
104
+ patch('backend.src.api.routes.auth.create_access_token') as mock_create_token:
105
+
106
+ mock_auth.return_value = {
107
+ "user": mock_user,
108
+ "token": "mocked_token"
109
+ }
110
+ mock_create_token.return_value = "mocked_token"
111
+
112
+ response = client.post("/auth/signin", json=signin_data)
113
+
114
+ assert response.status_code == 200
115
+ data = response.json()
116
+ assert data["success"] is True
117
+ assert data["data"]["access_token"] == "mocked_token"
118
+
119
+ def test_signin_endpoint_invalid_email(self, client):
120
+ """Test sign in with invalid email."""
121
+ signin_data = {
122
+ "email": "nonexistent@example.com",
123
+ "password": "any_password"
124
+ }
125
+
126
+ with patch('backend.src.services.auth_service.AuthService.authenticate_user_detailed_errors') as mock_auth:
127
+
128
+ # Mock the auth service to raise an AuthException
129
+ from backend.src.services.auth_service import AuthException
130
+ mock_auth.side_effect = AuthException(
131
+ error_type="EMAIL_NOT_FOUND",
132
+ message="No account found with this email address"
133
+ )
134
+
135
+ response = client.post("/auth/signin", json=signin_data)
136
+
137
+ assert response.status_code == 401
138
+
139
+ def test_signin_endpoint_invalid_password(self, client):
140
+ """Test sign in with invalid password."""
141
+ signin_data = {
142
+ "email": "existing@example.com",
143
+ "password": "wrong_password"
144
+ }
145
+
146
+ with patch('backend.src.services.auth_service.AuthService.authenticate_user_detailed_errors') as mock_auth:
147
+
148
+ # Mock the auth service to raise an AuthException for invalid password
149
+ from backend.src.services.auth_service import AuthException
150
+ mock_auth.side_effect = AuthException(
151
+ error_type="INVALID_PASSWORD",
152
+ message="Incorrect password"
153
+ )
154
+
155
+ response = client.post("/auth/signin", json=signin_data)
156
+
157
+ assert response.status_code == 401
158
+
159
+ def test_forgot_password_endpoint(self, client):
160
+ """Test forgot password endpoint."""
161
+ forgot_data = {
162
+ "email": "user@example.com",
163
+ "date_of_birth": "1990-01-01"
164
+ }
165
+
166
+ # Mock user object
167
+ mock_user = User(
168
+ id=1,
169
+ email="user@example.com",
170
+ password="hashed_password",
171
+ date_of_birth=datetime(1990, 1, 1).date(),
172
+ signup_date=datetime.utcnow()
173
+ )
174
+
175
+ with patch('sqlmodel.select') as mock_select:
176
+ # Mock the database query
177
+ mock_exec = Mock()
178
+ mock_exec.scalar_one_or_none.return_value = mock_user
179
+ mock_select.return_value = Mock()
180
+ mock_select.return_value.execute.return_value = mock_exec
181
+
182
+ response = client.post("/auth/forgot-password", json=forgot_data)
183
+
184
+ # This should succeed if user exists and DOB matches
185
+ assert response.status_code in [200, 400, 404] # Response varies based on implementation details
186
+
187
+ def test_set_new_password_endpoint(self, client):
188
+ """Test setting new password."""
189
+ password_data = {
190
+ "email": "user@example.com",
191
+ "new_password": "new_secure_password"
192
+ }
193
+
194
+ with patch('sqlmodel.select') as mock_select, \
195
+ patch('backend.src.api.routes.auth.get_password_hash') as mock_hash:
196
+
197
+ # Mock user object
198
+ mock_user = Mock()
199
+ mock_user.id = 1
200
+ mock_user.email = "user@example.com"
201
+
202
+ # Mock the database query
203
+ mock_exec = Mock()
204
+ mock_exec.scalar_one_or_none.return_value = mock_user
205
+ mock_select.return_value = Mock()
206
+ mock_select.return_value.execute.return_value = mock_exec
207
+ mock_hash.return_value = "hashed_new_password"
208
+
209
+ response = client.post("/auth/set-new-password", json=password_data)
210
+
211
+ assert response.status_code == 200
212
+ data = response.json()
213
+ assert data["success"] is True
214
+
215
+ def test_login_endpoint_legacy(self, client):
216
+ """Test the legacy login endpoint."""
217
+ login_data = {
218
+ "email": "test@example.com",
219
+ "password": "securepassword"
220
+ }
221
+
222
+ # Mock user object
223
+ mock_user = User(
224
+ id=1,
225
+ email="test@example.com",
226
+ password="hashed_password",
227
+ signup_date=datetime.utcnow()
228
+ )
229
+
230
+ with patch('sqlmodel.select') as mock_select, \
231
+ patch('backend.src.api.routes.auth.verify_password') as mock_verify, \
232
+ patch('backend.src.api.routes.auth.create_access_token') as mock_create_token:
233
+
234
+ # Mock the database query
235
+ mock_exec = Mock()
236
+ mock_exec.scalar_one_or_none.return_value = mock_user
237
+ mock_select.return_value = Mock()
238
+ mock_select.return_value.execute.return_value = mock_exec
239
+ mock_verify.return_value = True
240
+ mock_create_token.return_value = "mocked_token"
241
+
242
+ response = client.post("/auth/login", json=login_data)
243
+
244
+ assert response.status_code == 200
245
+ data = response.json()
246
+ assert data["success"] is True
247
+ assert "access_token" in data["data"]
tests/test_auth_service.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from unittest.mock import Mock, patch, MagicMock
3
+ from datetime import datetime, timedelta
4
+ from sqlmodel import Session
5
+ from backend.src.services.auth_service import AuthService, AuthException
6
+ from backend.src.models.user import User
7
+ from backend.src.utils.date_validator import validate_signup_date
8
+
9
+
10
+ class TestAuthService:
11
+ def setup_method(self):
12
+ self.auth_service = AuthService()
13
+
14
+ def test_create_access_token(self):
15
+ """Test creating an access token."""
16
+ user_id = 123
17
+ expires_delta = timedelta(minutes=30)
18
+
19
+ with patch('backend.src.services.auth_service.jwt.encode') as mock_encode, \
20
+ patch('backend.src.services.auth_service.SECRET_KEY', 'test_secret'), \
21
+ patch('backend.src.services.auth_service.ALGORITHM', 'HS256'):
22
+
23
+ mock_encode.return_value = 'mocked_token'
24
+
25
+ token = self.auth_service.create_access_token(user_id, expires_delta)
26
+
27
+ assert token == 'mocked_token'
28
+ mock_encode.assert_called_once()
29
+
30
+ def test_verify_token_valid(self):
31
+ """Test verifying a valid token."""
32
+ token = 'valid_token'
33
+
34
+ with patch('backend.src.services.auth_service.jwt.decode') as mock_decode, \
35
+ patch('backend.src.services.auth_service.SECRET_KEY', 'test_secret'), \
36
+ patch('backend.src.services.auth_service.ALGORITHM', 'HS256'):
37
+
38
+ mock_decode.return_value = {'sub': '123'}
39
+
40
+ result = self.auth_service.verify_token(token)
41
+
42
+ assert result == 123
43
+ mock_decode.assert_called_once()
44
+
45
+ def test_verify_token_invalid(self):
46
+ """Test verifying an invalid token."""
47
+ token = 'invalid_token'
48
+
49
+ with patch('backend.src.services.auth_service.jwt.decode') as mock_decode, \
50
+ patch('backend.src.services.auth_service.SECRET_KEY', 'test_secret'), \
51
+ patch('backend.src.services.auth_service.ALGORITHM', 'HS256'):
52
+
53
+ mock_decode.side_effect = Exception('Invalid token')
54
+
55
+ result = self.auth_service.verify_token(token)
56
+
57
+ assert result is None
58
+
59
+ @pytest.mark.asyncio
60
+ async def test_authenticate_user_email_not_found(self):
61
+ """Test authenticating a user with non-existent email."""
62
+ session = Mock(spec=Session)
63
+ email = 'nonexistent@example.com'
64
+ password = 'somepassword'
65
+
66
+ with patch('backend.src.services.auth_service.select') as mock_select:
67
+ # Mock the query execution
68
+ mock_exec = Mock()
69
+ mock_exec.first.return_value = None # No user found
70
+
71
+ session.exec.return_value = mock_exec
72
+
73
+ with pytest.raises(AuthException) as exc_info:
74
+ await self.auth_service.authenticate_user(session, email, password)
75
+
76
+ assert exc_info.value.error_type == "EMAIL_NOT_FOUND"
77
+
78
+ @pytest.mark.asyncio
79
+ async def test_authenticate_user_invalid_password(self):
80
+ """Test authenticating a user with invalid password."""
81
+ session = Mock(spec=Session)
82
+ email = 'existing@example.com'
83
+ password = 'wrongpassword'
84
+
85
+ # Create a mock user
86
+ mock_user = Mock(spec=User)
87
+ mock_user.password = 'hashed_correct_password'
88
+ mock_user.id = 1
89
+
90
+ with patch('backend.src.services.auth_service.select') as mock_select, \
91
+ patch('backend.src.services.auth_service.pwd_context') as mock_pwd_context:
92
+
93
+ mock_exec = Mock()
94
+ mock_exec.first.return_value = mock_user
95
+ session.exec.return_value = mock_exec
96
+ mock_pwd_context.verify.return_value = False # Password is wrong
97
+
98
+ with pytest.raises(AuthException) as exc_info:
99
+ await self.auth_service.authenticate_user(session, email, password)
100
+
101
+ assert exc_info.value.error_type == "INVALID_PASSWORD"
102
+
103
+ @pytest.mark.asyncio
104
+ async def test_authenticate_user_success(self):
105
+ """Test successful authentication."""
106
+ session = Mock(spec=Session)
107
+ email = 'existing@example.com'
108
+ password = 'correctpassword'
109
+
110
+ # Create a mock user
111
+ mock_user = Mock(spec=User)
112
+ mock_user.password = 'hashed_correct_password'
113
+ mock_user.id = 1
114
+ mock_user.email = email
115
+
116
+ with patch('backend.src.services.auth_service.select') as mock_select, \
117
+ patch('backend.src.services.auth_service.pwd_context') as mock_pwd_context, \
118
+ patch.object(self.auth_service, 'create_access_token') as mock_create_token:
119
+
120
+ mock_exec = Mock()
121
+ mock_exec.first.return_value = mock_user
122
+ session.exec.return_value = mock_exec
123
+ mock_pwd_context.verify.return_value = True # Password is correct
124
+ mock_create_token.return_value = 'mocked_token'
125
+
126
+ result = await self.auth_service.authenticate_user(session, email, password)
127
+
128
+ assert result['user'] == mock_user
129
+ assert result['token'] == 'mocked_token'
130
+
131
+ def test_register_user_success(self):
132
+ """Test successful user registration."""
133
+ session = Mock(spec=Session)
134
+ email = 'newuser@example.com'
135
+ password = 'newpassword'
136
+ name = 'New User'
137
+
138
+ with patch('backend.src.services.auth_service.select') as mock_select, \
139
+ patch('backend.src.services.auth_service.pwd_context') as mock_pwd_context, \
140
+ patch('backend.src.services.auth_service.validate_signup_date') as mock_validate, \
141
+ patch.object(self.auth_service, 'create_access_token') as mock_create_token:
142
+
143
+ # Mock no existing user found
144
+ mock_exec = Mock()
145
+ mock_exec.first.return_value = None
146
+ session.exec.return_value = mock_exec
147
+
148
+ mock_pwd_context.hash.return_value = 'hashed_newpassword'
149
+ mock_validate.return_value = datetime.utcnow()
150
+ mock_create_token.return_value = 'mocked_token'
151
+
152
+ result = self.auth_service.register_user(session, email, password, name)
153
+
154
+ assert result['token'] == 'mocked_token'
155
+ assert result['user'].email == email
156
+ assert result['user'].name == name
157
+ session.add.assert_called_once()
158
+
159
+ def test_register_user_duplicate_email(self):
160
+ """Test registering a user with duplicate email."""
161
+ session = Mock(spec=Session)
162
+ email = 'existing@example.com'
163
+ password = 'newpassword'
164
+
165
+ # Create a mock existing user
166
+ mock_existing_user = Mock(spec=User)
167
+ mock_existing_user.email = email
168
+
169
+ with patch('backend.src.services.auth_service.select') as mock_select:
170
+ mock_exec = Mock()
171
+ mock_exec.first.return_value = mock_existing_user
172
+ session.exec.return_value = mock_exec
173
+
174
+ with pytest.raises(AuthException) as exc_info:
175
+ self.auth_service.register_user(session, email, password)
176
+
177
+ assert exc_info.value.error_type == "EMAIL_EXISTS"
tests/unit/test_error_handlers.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from fastapi import HTTPException
3
+ from fastapi.responses import JSONResponse
4
+ from fastapi import Request
5
+
6
+ from backend.src.utils.error_handlers import (
7
+ APIError,
8
+ ValidationError,
9
+ NotFoundError,
10
+ UnauthorizedError,
11
+ ForbiddenError,
12
+ InternalServerError,
13
+ validation_error_handler,
14
+ not_found_error_handler,
15
+ unauthorized_error_handler,
16
+ forbidden_error_handler,
17
+ internal_server_error_handler,
18
+ http_exception_handler
19
+ )
20
+
21
+
22
+ @pytest.fixture
23
+ def mock_request():
24
+ """Mock request object for testing."""
25
+ return Request({"type": "http"})
26
+
27
+
28
+ def test_api_error_initialization():
29
+ """Test APIError initialization."""
30
+ error = APIError(message="Test error", code="TEST_ERROR", status_code=400)
31
+ assert error.message == "Test error"
32
+ assert error.code == "TEST_ERROR"
33
+ assert error.status_code == 400
34
+
35
+
36
+ def test_validation_error():
37
+ """Test ValidationError."""
38
+ error = ValidationError()
39
+ assert error.message == "Invalid request data"
40
+ assert error.code == "VALIDATION_001"
41
+ assert error.status_code == 400
42
+
43
+ custom_error = ValidationError("Custom validation error")
44
+ assert custom_error.message == "Custom validation error"
45
+
46
+
47
+ def test_not_found_error():
48
+ """Test NotFoundError."""
49
+ error = NotFoundError()
50
+ assert error.message == "Resource not found"
51
+ assert error.code == "RESOURCE_001"
52
+ assert error.status_code == 404
53
+
54
+ custom_error = NotFoundError("Custom not found error")
55
+ assert custom_error.message == "Custom not found error"
56
+
57
+
58
+ def test_unauthorized_error():
59
+ """Test UnauthorizedError."""
60
+ error = UnauthorizedError()
61
+ assert error.message == "Unauthorized access"
62
+ assert error.code == "AUTH_001"
63
+ assert error.status_code == 401
64
+
65
+ custom_error = UnauthorizedError("Custom unauthorized error")
66
+ assert custom_error.message == "Custom unauthorized error"
67
+
68
+
69
+ def test_forbidden_error():
70
+ """Test ForbiddenError."""
71
+ error = ForbiddenError()
72
+ assert error.message == "Access forbidden"
73
+ assert error.code == "ACCESS_001"
74
+ assert error.status_code == 403
75
+
76
+ custom_error = ForbiddenError("Custom forbidden error")
77
+ assert custom_error.message == "Custom forbidden error"
78
+
79
+
80
+ def test_internal_server_error():
81
+ """Test InternalServerError."""
82
+ error = InternalServerError()
83
+ assert error.message == "Internal server error"
84
+ assert error.code == "SERVER_001"
85
+ assert error.status_code == 500
86
+
87
+ custom_error = InternalServerError("Custom server error")
88
+ assert custom_error.message == "Custom server error"
89
+
90
+
91
+ @pytest.mark.asyncio
92
+ async def test_validation_error_handler(mock_request):
93
+ """Test validation error handler."""
94
+ error = ValidationError("Test validation error")
95
+ response = await validation_error_handler(mock_request, error)
96
+
97
+ assert isinstance(response, JSONResponse)
98
+ assert response.status_code == 400
99
+
100
+ response_body = response.body.decode()
101
+ assert "VALIDATION_001" in response_body
102
+ assert "Test validation error" in response_body
103
+
104
+
105
+ @pytest.mark.asyncio
106
+ async def test_not_found_error_handler(mock_request):
107
+ """Test not found error handler."""
108
+ error = NotFoundError("Test not found error")
109
+ response = await not_found_error_handler(mock_request, error)
110
+
111
+ assert isinstance(response, JSONResponse)
112
+ assert response.status_code == 404
113
+
114
+ response_body = response.body.decode()
115
+ assert "RESOURCE_001" in response_body
116
+ assert "Test not found error" in response_body
117
+
118
+
119
+ @pytest.mark.asyncio
120
+ async def test_unauthorized_error_handler(mock_request):
121
+ """Test unauthorized error handler."""
122
+ error = UnauthorizedError("Test unauthorized error")
123
+ response = await unauthorized_error_handler(mock_request, error)
124
+
125
+ assert isinstance(response, JSONResponse)
126
+ assert response.status_code == 401
127
+
128
+ response_body = response.body.decode()
129
+ assert "AUTH_001" in response_body
130
+ assert "Test unauthorized error" in response_body
131
+
132
+
133
+ @pytest.mark.asyncio
134
+ async def test_forbidden_error_handler(mock_request):
135
+ """Test forbidden error handler."""
136
+ error = ForbiddenError("Test forbidden error")
137
+ response = await forbidden_error_handler(mock_request, error)
138
+
139
+ assert isinstance(response, JSONResponse)
140
+ assert response.status_code == 403
141
+
142
+ response_body = response.body.decode()
143
+ assert "ACCESS_001" in response_body
144
+ assert "Test forbidden error" in response_body
145
+
146
+
147
+ @pytest.mark.asyncio
148
+ async def test_internal_server_error_handler(mock_request):
149
+ """Test internal server error handler."""
150
+ error = InternalServerError("Test server error")
151
+ response = await internal_server_error_handler(mock_request, error)
152
+
153
+ assert isinstance(response, JSONResponse)
154
+ assert response.status_code == 500
155
+
156
+ response_body = response.body.decode()
157
+ assert "SERVER_001" in response_body
158
+ assert "Test server error" in response_body
159
+
160
+
161
+ @pytest.mark.asyncio
162
+ async def test_http_exception_handler(mock_request):
163
+ """Test HTTP exception handler."""
164
+ http_exc = HTTPException(status_code=404, detail="Item not found")
165
+ response = await http_exception_handler(mock_request, http_exc)
166
+
167
+ assert isinstance(response, JSONResponse)
168
+ assert response.status_code == 404
169
+
170
+ response_body = response.body.decode()
171
+ assert "RESOURCE_001" in response_body # Maps 404 to RESOURCE_001
172
+ assert "Item not found" in response_body
tests/unit/test_task_model.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from datetime import datetime
3
+
4
+ from backend.src.models.task import Task, TaskCreate, TaskRead, TaskUpdate
5
+
6
+
7
+ def test_task_creation():
8
+ """Test creating a task with valid data."""
9
+ task_data = {
10
+ "title": "Test Task",
11
+ "description": "This is a test task",
12
+ "completed": False,
13
+ "user_id": 1
14
+ }
15
+
16
+ task_create = TaskCreate(**task_data)
17
+ assert task_create.title == "Test Task"
18
+ assert task_create.description == "This is a test task"
19
+ assert task_create.completed is False
20
+ assert task_create.user_id == 1
21
+
22
+
23
+ def test_task_creation_required_fields():
24
+ """Test that required fields are enforced."""
25
+ with pytest.raises(ValueError):
26
+ TaskCreate(title="", user_id=1) # Empty title should fail
27
+
28
+ with pytest.raises(ValueError):
29
+ TaskCreate(title="Test Task") # Missing user_id should fail
30
+
31
+
32
+ def test_task_creation_title_length_validation():
33
+ """Test title length validation."""
34
+ # Title too long should fail
35
+ long_title = "t" * 256
36
+ with pytest.raises(ValueError):
37
+ TaskCreate(title=long_title, user_id=1)
38
+
39
+ # Title at max length should pass
40
+ max_title = "t" * 255
41
+ task = TaskCreate(title=max_title, user_id=1)
42
+ assert len(task.title) == 255
43
+
44
+
45
+ def test_task_update_partial():
46
+ """Test that TaskUpdate allows partial updates."""
47
+ # All fields should be optional in TaskUpdate
48
+ update_data = {}
49
+ task_update = TaskUpdate(**update_data)
50
+ assert task_update.title is None
51
+ assert task_update.description is None
52
+ assert task_update.completed is None
53
+
54
+
55
+ def test_task_update_with_values():
56
+ """Test updating with specific values."""
57
+ update_data = {
58
+ "title": "Updated Title",
59
+ "completed": True
60
+ }
61
+ task_update = TaskUpdate(**update_data)
62
+ assert task_update.title == "Updated Title"
63
+ assert task_update.completed is True
64
+ assert task_update.description is None
65
+
66
+
67
+ def test_task_read_serialization():
68
+ """Test TaskRead model serialization."""
69
+ task_read = TaskRead(
70
+ id=1,
71
+ title="Test Task",
72
+ description="Description",
73
+ completed=False,
74
+ user_id=1,
75
+ created_at=datetime.now(),
76
+ updated_at=datetime.now()
77
+ )
78
+
79
+ assert task_read.id == 1
80
+ assert task_read.title == "Test Task"
81
+ assert task_read.description == "Description"
82
+ assert task_read.completed is False
83
+ assert task_read.user_id == 1