web-applicalion-todo
Browse files- .gitignore +55 -0
- Dockerfile +14 -0
- README.md +0 -10
- docs/readme.md +64 -0
- docs/security.md +104 -0
- requirements.txt +11 -0
- src/api/__init__.py +5 -0
- src/api/decorators.py +61 -0
- src/api/deps.py +68 -0
- src/api/main.py +83 -0
- src/api/routes/__init__.py +5 -0
- src/api/routes/auth.py +581 -0
- src/api/routes/tasks.py +224 -0
- src/config.py +30 -0
- src/database/__init__.py +5 -0
- src/database/database.py +64 -0
- src/middleware/auth.py +128 -0
- src/middleware/security.py +74 -0
- src/models/__init__.py +5 -0
- src/models/error.py +20 -0
- src/models/error_response.py +45 -0
- src/models/session.py +32 -0
- src/models/task.py +39 -0
- src/models/user.py +38 -0
- src/services/__init__.py +5 -0
- src/services/auth_service.py +235 -0
- src/services/task_service.py +245 -0
- src/services/user_service.py +116 -0
- src/utils/__init__.py +5 -0
- src/utils/date_validator.py +123 -0
- src/utils/error_handlers.py +152 -0
- src/utils/jwt_utils.py +58 -0
- src/utils/logger.py +91 -0
- tests/__init__.py +5 -0
- tests/conftest.py +32 -0
- tests/contract/test_api_contracts.py +110 -0
- tests/integration/test_task_endpoints.py +62 -0
- tests/test_auth_api.py +247 -0
- tests/test_auth_service.py +177 -0
- tests/unit/test_error_handlers.py +172 -0
- 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,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
EXPOSE 8000
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
CMD ["uvicorn", "src.api.main:app", "--host", "127.0.0.1", "--port", "8000"]
|
README.md
DELETED
|
@@ -1,10 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Web App
|
| 3 |
-
emoji: 💻
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: gray
|
| 6 |
-
sdk: docker
|
| 7 |
-
pinned: false
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
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,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
return UserRead(
|
| 60 |
+
id=user.id,
|
| 61 |
+
email=user.email,
|
| 62 |
+
name=user.name,
|
| 63 |
+
date_of_birth=user.date_of_birth,
|
| 64 |
+
signup_date=user.signup_date,
|
| 65 |
+
force_password_change=user.force_password_change,
|
| 66 |
+
created_at=created_at,
|
| 67 |
+
updated_at=updated_at
|
| 68 |
+
)
|
src/api/main.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import asynccontextmanager
|
| 2 |
+
from typing import AsyncGenerator
|
| 3 |
+
|
| 4 |
+
from fastapi import FastAPI
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
|
| 7 |
+
from .routes.tasks import router as tasks_router
|
| 8 |
+
from .routes.auth import router as auth_router
|
| 9 |
+
from ..config import settings
|
| 10 |
+
from ..utils.error_handlers import add_exception_handlers
|
| 11 |
+
from ..middleware.security import SecurityHeadersMiddleware
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@asynccontextmanager
|
| 15 |
+
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
| 16 |
+
"""
|
| 17 |
+
Lifespan event handler for FastAPI application.
|
| 18 |
+
|
| 19 |
+
Handles startup and shutdown events.
|
| 20 |
+
"""
|
| 21 |
+
# Startup
|
| 22 |
+
print("Starting up Todo Backend API...")
|
| 23 |
+
|
| 24 |
+
# Add exception handlers
|
| 25 |
+
add_exception_handlers(app)
|
| 26 |
+
|
| 27 |
+
yield
|
| 28 |
+
|
| 29 |
+
# Shutdown
|
| 30 |
+
print("Shutting down Todo Backend API...")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def create_app() -> FastAPI:
|
| 34 |
+
"""
|
| 35 |
+
Create and configure the FastAPI application.
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
Configured FastAPI application instance
|
| 39 |
+
"""
|
| 40 |
+
app = FastAPI(
|
| 41 |
+
title=settings.app_name,
|
| 42 |
+
debug=settings.debug,
|
| 43 |
+
lifespan=lifespan
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Add security headers middleware first
|
| 47 |
+
app.add_middleware(SecurityHeadersMiddleware)
|
| 48 |
+
|
| 49 |
+
# Add CORS middleware
|
| 50 |
+
app.add_middleware(
|
| 51 |
+
CORSMiddleware,
|
| 52 |
+
allow_origins=["*"], # In production, configure specific origins
|
| 53 |
+
allow_credentials=True,
|
| 54 |
+
allow_methods=["*"],
|
| 55 |
+
allow_headers=["*"],
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Include API routes
|
| 59 |
+
app.include_router(tasks_router, prefix=settings.api_prefix)
|
| 60 |
+
app.include_router(auth_router, prefix=settings.api_prefix)
|
| 61 |
+
|
| 62 |
+
@app.get("/")
|
| 63 |
+
async def root():
|
| 64 |
+
"""Root endpoint for the API."""
|
| 65 |
+
return {
|
| 66 |
+
"message": "Welcome to the Todo Backend API",
|
| 67 |
+
"app_name": settings.app_name,
|
| 68 |
+
"version": "1.0.0"
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
return app
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
app = create_app()
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
import uvicorn
|
| 78 |
+
uvicorn.run(
|
| 79 |
+
"backend.src.api.main:app",
|
| 80 |
+
host="0.0.0.0",
|
| 81 |
+
port=8000,
|
| 82 |
+
reload=True
|
| 83 |
+
)
|
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,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Create new user with signup date validation
|
| 56 |
+
db_user = User(
|
| 57 |
+
email=signup_request.email,
|
| 58 |
+
password=hashed_password,
|
| 59 |
+
name=signup_request.name,
|
| 60 |
+
date_of_birth=signup_request.date_of_birth,
|
| 61 |
+
signup_date=validated_signup_date # Non-nullable field, enforced here
|
| 62 |
+
)
|
| 63 |
+
session.add(db_user)
|
| 64 |
+
await session.commit()
|
| 65 |
+
await session.refresh(db_user)
|
| 66 |
+
|
| 67 |
+
# Create access token
|
| 68 |
+
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
|
| 69 |
+
access_token = create_access_token(
|
| 70 |
+
data={"sub": str(db_user.id)}, expires_delta=access_token_expires
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
"success": True,
|
| 75 |
+
"data": {
|
| 76 |
+
"user": UserRead.model_validate(db_user),
|
| 77 |
+
"access_token": access_token,
|
| 78 |
+
"token_type": "bearer"
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
except HTTPException:
|
| 82 |
+
raise
|
| 83 |
+
except Exception as e:
|
| 84 |
+
raise HTTPException(
|
| 85 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 86 |
+
detail=f"Signup failed: {str(e)}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
@router.post("/signin", response_model=dict, responses={
|
| 90 |
+
400: {"model": ErrorResponse, "description": "Invalid request format"},
|
| 91 |
+
401: {"model": ErrorResponse, "description": "Authentication failed"}
|
| 92 |
+
})
|
| 93 |
+
async def signin_user(
|
| 94 |
+
signin_request: SigninRequest,
|
| 95 |
+
session: AsyncSession = Depends(get_async_session)
|
| 96 |
+
):
|
| 97 |
+
"""
|
| 98 |
+
Authenticate user with enhanced error handling to differentiate between email and password errors.
|
| 99 |
+
"""
|
| 100 |
+
try:
|
| 101 |
+
# Use the enhanced authentication service that provides detailed error messages
|
| 102 |
+
auth_result = auth_service.authenticate_user_detailed_errors(
|
| 103 |
+
session=session,
|
| 104 |
+
email=signin_request.email,
|
| 105 |
+
password=signin_request.password
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
return {
|
| 109 |
+
"success": True,
|
| 110 |
+
"data": {
|
| 111 |
+
"user": UserRead.model_validate(auth_result["user"]),
|
| 112 |
+
"access_token": auth_result["token"],
|
| 113 |
+
"token_type": "bearer"
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
except AuthException as e:
|
| 117 |
+
# Map our custom exceptions to appropriate HTTP responses
|
| 118 |
+
status_code = status.HTTP_401_UNAUTHORIZED
|
| 119 |
+
if e.error_type == "EMAIL_NOT_FOUND":
|
| 120 |
+
status_code = status.HTTP_401_UNAUTHORIZED
|
| 121 |
+
elif e.error_type == "INVALID_PASSWORD":
|
| 122 |
+
status_code = status.HTTP_401_UNAUTHORIZED
|
| 123 |
+
|
| 124 |
+
raise HTTPException(
|
| 125 |
+
status_code=status_code,
|
| 126 |
+
detail=e.message
|
| 127 |
+
)
|
| 128 |
+
except HTTPException:
|
| 129 |
+
raise
|
| 130 |
+
except Exception as e:
|
| 131 |
+
raise HTTPException(
|
| 132 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 133 |
+
detail=f"Signin failed: {str(e)}"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class LoginRequest(BaseModel):
|
| 138 |
+
email: str
|
| 139 |
+
password: str
|
| 140 |
+
|
| 141 |
+
class ForgotPasswordRequest(BaseModel):
|
| 142 |
+
email: str
|
| 143 |
+
date_of_birth: str # Format: YYYY-MM-DD
|
| 144 |
+
|
| 145 |
+
@router.post("/forgot-password", response_model=dict)
|
| 146 |
+
async def forgot_password(
|
| 147 |
+
request_data: ForgotPasswordRequest,
|
| 148 |
+
session: AsyncSession = Depends(get_async_session)
|
| 149 |
+
):
|
| 150 |
+
"""
|
| 151 |
+
Verify user identity using email and date of birth for password reset.
|
| 152 |
+
"""
|
| 153 |
+
try:
|
| 154 |
+
# Find user by email
|
| 155 |
+
statement = select(User).where(User.email == request_data.email)
|
| 156 |
+
result = await session.execute(statement)
|
| 157 |
+
user = result.scalar_one_or_none()
|
| 158 |
+
|
| 159 |
+
if not user:
|
| 160 |
+
# Return the same error message even if email doesn't exist to prevent email enumeration
|
| 161 |
+
raise HTTPException(
|
| 162 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 163 |
+
detail="If an account with that email exists, a password reset link has been sent."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# Verify the date of birth matches
|
| 167 |
+
print(f"DEBUG: Looking up user by email: {request_data.email}")
|
| 168 |
+
print(f"DEBUG: Found user date_of_birth: {user.date_of_birth} (type: {type(user.date_of_birth)})")
|
| 169 |
+
|
| 170 |
+
if not user.date_of_birth:
|
| 171 |
+
print(f"DEBUG: User has no date of birth set in database")
|
| 172 |
+
raise HTTPException(
|
| 173 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 174 |
+
detail="Date of birth verification failed. Please contact support."
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# Parse the provided date of birth
|
| 178 |
+
from datetime import datetime
|
| 179 |
+
try:
|
| 180 |
+
provided_dob = datetime.strptime(request_data.date_of_birth, '%Y-%m-%d')
|
| 181 |
+
except ValueError:
|
| 182 |
+
raise HTTPException(
|
| 183 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 184 |
+
detail="Invalid date format. Please use YYYY-MM-DD format."
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# Compare dates (ignoring time component)
|
| 188 |
+
print(f"DEBUG: Comparing user.date_of_birth: {user.date_of_birth} with provided: {provided_dob.date()}")
|
| 189 |
+
|
| 190 |
+
if user.date_of_birth != provided_dob.date(): # Both should be date objects now
|
| 191 |
+
raise HTTPException(
|
| 192 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 193 |
+
detail="Date of birth verification failed. Please check your date of birth and try again."
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
# In a real app, you'd send a password reset link to the user's email
|
| 197 |
+
# For demo purposes, we'll just return success
|
| 198 |
+
|
| 199 |
+
return {
|
| 200 |
+
"success": True,
|
| 201 |
+
"data": {
|
| 202 |
+
"message": "Identity verified successfully. Please set your new password.",
|
| 203 |
+
"email": request_data.email
|
| 204 |
+
}
|
| 205 |
+
}
|
| 206 |
+
except HTTPException:
|
| 207 |
+
raise
|
| 208 |
+
except Exception as e:
|
| 209 |
+
raise HTTPException(
|
| 210 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 211 |
+
detail=f"Forgot password request failed: {str(e)}"
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class SetNewPasswordRequest(BaseModel):
|
| 216 |
+
email: str
|
| 217 |
+
new_password: str
|
| 218 |
+
|
| 219 |
+
@router.post("/set-new-password", response_model=dict)
|
| 220 |
+
async def set_new_password(
|
| 221 |
+
request_data: SetNewPasswordRequest,
|
| 222 |
+
session: AsyncSession = Depends(get_async_session)
|
| 223 |
+
):
|
| 224 |
+
"""
|
| 225 |
+
Set new password after successful verification.
|
| 226 |
+
"""
|
| 227 |
+
try:
|
| 228 |
+
# Find user by email
|
| 229 |
+
statement = select(User).where(User.email == request_data.email)
|
| 230 |
+
result = await session.execute(statement)
|
| 231 |
+
user = result.scalar_one_or_none()
|
| 232 |
+
|
| 233 |
+
if not user:
|
| 234 |
+
raise HTTPException(
|
| 235 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 236 |
+
detail="User not found"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# Hash the new password before storing
|
| 240 |
+
hashed_new_password = get_password_hash(request_data.new_password)
|
| 241 |
+
user.password = hashed_new_password
|
| 242 |
+
user.updated_at = datetime.utcnow()
|
| 243 |
+
|
| 244 |
+
session.add(user)
|
| 245 |
+
await session.commit()
|
| 246 |
+
|
| 247 |
+
return {
|
| 248 |
+
"success": True,
|
| 249 |
+
"data": {
|
| 250 |
+
"message": "Password changed successfully"
|
| 251 |
+
}
|
| 252 |
+
}
|
| 253 |
+
except HTTPException:
|
| 254 |
+
raise
|
| 255 |
+
except Exception as e:
|
| 256 |
+
raise HTTPException(
|
| 257 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 258 |
+
detail=f"Password change failed: {str(e)}"
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class ResetPasswordRequest(BaseModel):
|
| 263 |
+
email: str
|
| 264 |
+
new_password: str
|
| 265 |
+
|
| 266 |
+
@router.post("/reset-password", response_model=dict)
|
| 267 |
+
async def reset_password(
|
| 268 |
+
request_data: ResetPasswordRequest,
|
| 269 |
+
session: AsyncSession = Depends(get_async_session)
|
| 270 |
+
):
|
| 271 |
+
"""
|
| 272 |
+
Reset user password directly (for admin or special cases).
|
| 273 |
+
"""
|
| 274 |
+
try:
|
| 275 |
+
# Find user by email
|
| 276 |
+
statement = select(User).where(User.email == request_data.email)
|
| 277 |
+
result = await session.execute(statement)
|
| 278 |
+
user = result.scalar_one_or_none()
|
| 279 |
+
|
| 280 |
+
if not user:
|
| 281 |
+
raise HTTPException(
|
| 282 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 283 |
+
detail="User not found"
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# Hash the new password before storing
|
| 287 |
+
hashed_new_password = get_password_hash(request_data.new_password)
|
| 288 |
+
user.password = hashed_new_password
|
| 289 |
+
user.updated_at = datetime.utcnow()
|
| 290 |
+
|
| 291 |
+
session.add(user)
|
| 292 |
+
await session.commit()
|
| 293 |
+
|
| 294 |
+
return {
|
| 295 |
+
"success": True,
|
| 296 |
+
"data": {
|
| 297 |
+
"message": "Password reset successfully"
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
except HTTPException:
|
| 301 |
+
raise
|
| 302 |
+
except Exception as e:
|
| 303 |
+
raise HTTPException(
|
| 304 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 305 |
+
detail=f"Password reset failed: {str(e)}"
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class ChangePasswordRequest(BaseModel):
|
| 310 |
+
current_password: str
|
| 311 |
+
new_password: str
|
| 312 |
+
|
| 313 |
+
@router.post("/change-password", response_model=dict)
|
| 314 |
+
async def change_password(
|
| 315 |
+
request_data: ChangePasswordRequest,
|
| 316 |
+
current_user: UserRead = Depends(get_current_user),
|
| 317 |
+
session: AsyncSession = Depends(get_async_session)
|
| 318 |
+
):
|
| 319 |
+
"""
|
| 320 |
+
Change user's current password after verifying the current password.
|
| 321 |
+
"""
|
| 322 |
+
try:
|
| 323 |
+
# Verify the current password
|
| 324 |
+
statement = select(User).where(User.id == current_user.id)
|
| 325 |
+
result = await session.execute(statement)
|
| 326 |
+
user = result.scalar_one_or_none()
|
| 327 |
+
|
| 328 |
+
if not user:
|
| 329 |
+
raise HTTPException(
|
| 330 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 331 |
+
detail="User not found"
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
# Verify the provided current password against the stored hash
|
| 335 |
+
if not verify_password(request_data.current_password, user.password):
|
| 336 |
+
raise HTTPException(
|
| 337 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 338 |
+
detail="Current password is incorrect"
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
# Hash the new password before storing
|
| 342 |
+
hashed_new_password = get_password_hash(request_data.new_password)
|
| 343 |
+
user.password = hashed_new_password
|
| 344 |
+
user.updated_at = datetime.utcnow()
|
| 345 |
+
|
| 346 |
+
# Reset the force_password_change flag if set
|
| 347 |
+
user.force_password_change = False
|
| 348 |
+
|
| 349 |
+
session.add(user)
|
| 350 |
+
await session.commit()
|
| 351 |
+
|
| 352 |
+
return {
|
| 353 |
+
"success": True,
|
| 354 |
+
"data": {
|
| 355 |
+
"message": "Password changed successfully"
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
except HTTPException:
|
| 359 |
+
raise
|
| 360 |
+
except Exception as e:
|
| 361 |
+
raise HTTPException(
|
| 362 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 363 |
+
detail=f"Password change failed: {str(e)}"
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@router.post("/token", response_model=dict)
|
| 368 |
+
async def login_for_access_token(
|
| 369 |
+
login_request: LoginRequest,
|
| 370 |
+
session: AsyncSession = Depends(get_async_session)
|
| 371 |
+
):
|
| 372 |
+
"""
|
| 373 |
+
OAuth2 compatible token login, get an access token for future requests.
|
| 374 |
+
"""
|
| 375 |
+
try:
|
| 376 |
+
# Find user by email
|
| 377 |
+
statement = select(User).where(User.email == login_request.email)
|
| 378 |
+
result = await session.execute(statement)
|
| 379 |
+
user = result.scalar_one_or_none()
|
| 380 |
+
|
| 381 |
+
if not user:
|
| 382 |
+
raise HTTPException(
|
| 383 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 384 |
+
detail="Incorrect email or password",
|
| 385 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
# Verify the provided password against the stored hash
|
| 389 |
+
if not verify_password(login_request.password, user.password):
|
| 390 |
+
raise HTTPException(
|
| 391 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 392 |
+
detail="Incorrect email or password",
|
| 393 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
# Create access token
|
| 397 |
+
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
|
| 398 |
+
access_token = create_access_token(
|
| 399 |
+
data={"sub": str(user.id)}, expires_delta=access_token_expires
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
return {
|
| 403 |
+
"access_token": access_token,
|
| 404 |
+
"token_type": "bearer",
|
| 405 |
+
"user": UserRead.model_validate(user)
|
| 406 |
+
}
|
| 407 |
+
except HTTPException:
|
| 408 |
+
raise
|
| 409 |
+
except Exception as e:
|
| 410 |
+
raise HTTPException(
|
| 411 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 412 |
+
detail=f"Token creation failed: {str(e)}"
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
# Also add a test endpoint that doesn't require auth to verify the token works
|
| 417 |
+
@router.get("/test-token", response_model=dict)
|
| 418 |
+
async def test_token():
|
| 419 |
+
"""
|
| 420 |
+
Test endpoint to verify authentication is working.
|
| 421 |
+
"""
|
| 422 |
+
return {
|
| 423 |
+
"message": "Token is valid!",
|
| 424 |
+
"success": True
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@router.post("/register", response_model=dict)
|
| 429 |
+
async def register_user(
|
| 430 |
+
user_create: UserCreate,
|
| 431 |
+
session: AsyncSession = Depends(get_async_session)
|
| 432 |
+
):
|
| 433 |
+
"""
|
| 434 |
+
Register a new user.
|
| 435 |
+
"""
|
| 436 |
+
try:
|
| 437 |
+
# Check if user already exists
|
| 438 |
+
existing_user_statement = select(User).where(User.email == user_create.email)
|
| 439 |
+
existing_user_result = await session.execute(existing_user_statement)
|
| 440 |
+
existing_user = existing_user_result.scalar_one_or_none()
|
| 441 |
+
|
| 442 |
+
if existing_user:
|
| 443 |
+
raise HTTPException(
|
| 444 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 445 |
+
detail="User with this email already exists"
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
# Hash the password before storing
|
| 449 |
+
hashed_password = get_password_hash(user_create.password)
|
| 450 |
+
|
| 451 |
+
# Create new user with hashed password, optional name and date of birth
|
| 452 |
+
from datetime import datetime, date
|
| 453 |
+
date_of_birth_obj = None
|
| 454 |
+
|
| 455 |
+
# Debug: Print incoming date of birth for troubleshooting
|
| 456 |
+
print(f"DEBUG: Incoming date_of_birth value: {user_create.date_of_birth}, type: {type(user_create.date_of_birth)}")
|
| 457 |
+
|
| 458 |
+
# Handle date of birth conversion - supports string, date, or datetime objects
|
| 459 |
+
if user_create.date_of_birth is not None:
|
| 460 |
+
dob_input = user_create.date_of_birth
|
| 461 |
+
|
| 462 |
+
print(f"DEBUG: Processing date of birth input: {dob_input}, type: {type(dob_input)}")
|
| 463 |
+
|
| 464 |
+
if isinstance(dob_input, str):
|
| 465 |
+
# Handle string input - strip whitespace and parse
|
| 466 |
+
dob_str = dob_input.strip()
|
| 467 |
+
print(f"DEBUG: String date stripped: '{dob_str}'")
|
| 468 |
+
if dob_str: # Only process if not empty after stripping
|
| 469 |
+
try:
|
| 470 |
+
# Parse string to date object (to match database schema)
|
| 471 |
+
date_of_birth_obj = datetime.strptime(dob_str, '%Y-%m-%d').date()
|
| 472 |
+
print(f"DEBUG: Successfully parsed date: {date_of_birth_obj}")
|
| 473 |
+
except ValueError as e:
|
| 474 |
+
# Handle invalid date format
|
| 475 |
+
print(f"Date of birth parsing error: {e}")
|
| 476 |
+
raise HTTPException(
|
| 477 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 478 |
+
detail="Invalid date of birth format. Please use YYYY-MM-DD format."
|
| 479 |
+
)
|
| 480 |
+
elif isinstance(dob_input, date):
|
| 481 |
+
# If it's already a date object, use it as is
|
| 482 |
+
date_of_birth_obj = dob_input
|
| 483 |
+
print(f"DEBUG: Using date object directly: {date_of_birth_obj}")
|
| 484 |
+
elif isinstance(dob_input, datetime):
|
| 485 |
+
# If it's a datetime object, convert to date to match database schema
|
| 486 |
+
date_of_birth_obj = dob_input.date()
|
| 487 |
+
print(f"DEBUG: Converted datetime to date: {date_of_birth_obj}")
|
| 488 |
+
else:
|
| 489 |
+
print("DEBUG: No date of birth provided in request")
|
| 490 |
+
|
| 491 |
+
print(f"DEBUG: Final date_of_birth_obj value: {date_of_birth_obj}")
|
| 492 |
+
|
| 493 |
+
# Use current time as signup_date if not provided in the request
|
| 494 |
+
current_time = datetime.utcnow()
|
| 495 |
+
|
| 496 |
+
db_user = User(
|
| 497 |
+
email=user_create.email,
|
| 498 |
+
password=hashed_password,
|
| 499 |
+
name=user_create.name,
|
| 500 |
+
date_of_birth=date_of_birth_obj,
|
| 501 |
+
signup_date=current_time, # Non-nullable field, enforced here
|
| 502 |
+
force_password_change=False # New users don't need to change password immediately
|
| 503 |
+
)
|
| 504 |
+
session.add(db_user)
|
| 505 |
+
await session.commit()
|
| 506 |
+
await session.refresh(db_user)
|
| 507 |
+
|
| 508 |
+
# Additional debug: Check what was actually saved
|
| 509 |
+
print(f"DEBUG: User saved with date_of_birth: {db_user.date_of_birth}, signup_date: {db_user.signup_date}")
|
| 510 |
+
|
| 511 |
+
# Create access token
|
| 512 |
+
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
|
| 513 |
+
access_token = create_access_token(
|
| 514 |
+
data={"sub": str(db_user.id)}, expires_delta=access_token_expires
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
return {
|
| 518 |
+
"success": True,
|
| 519 |
+
"data": {
|
| 520 |
+
"user": UserRead.model_validate(db_user),
|
| 521 |
+
"access_token": access_token,
|
| 522 |
+
"token_type": "bearer"
|
| 523 |
+
}
|
| 524 |
+
}
|
| 525 |
+
except HTTPException:
|
| 526 |
+
raise
|
| 527 |
+
except Exception as e:
|
| 528 |
+
raise HTTPException(
|
| 529 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 530 |
+
detail=f"Registration failed: {str(e)}"
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@router.post("/login", response_model=dict)
|
| 535 |
+
async def login_user(
|
| 536 |
+
login_request: LoginRequest,
|
| 537 |
+
session: AsyncSession = Depends(get_async_session)
|
| 538 |
+
):
|
| 539 |
+
"""
|
| 540 |
+
Authenticate user and return access token.
|
| 541 |
+
"""
|
| 542 |
+
try:
|
| 543 |
+
# Find user by email
|
| 544 |
+
statement = select(User).where(User.email == login_request.email)
|
| 545 |
+
result = await session.execute(statement)
|
| 546 |
+
user = result.scalar_one_or_none()
|
| 547 |
+
|
| 548 |
+
if not user:
|
| 549 |
+
raise HTTPException(
|
| 550 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 551 |
+
detail="Invalid email or password"
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
# Verify the provided password against the stored hash
|
| 555 |
+
if not verify_password(login_request.password, user.password):
|
| 556 |
+
raise HTTPException(
|
| 557 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 558 |
+
detail="Invalid email or password"
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
# Create access token
|
| 562 |
+
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
|
| 563 |
+
access_token = create_access_token(
|
| 564 |
+
data={"sub": str(user.id)}, expires_delta=access_token_expires
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
return {
|
| 568 |
+
"success": True,
|
| 569 |
+
"data": {
|
| 570 |
+
"user": UserRead.model_validate(user),
|
| 571 |
+
"access_token": access_token,
|
| 572 |
+
"token_type": "bearer"
|
| 573 |
+
}
|
| 574 |
+
}
|
| 575 |
+
except HTTPException:
|
| 576 |
+
raise
|
| 577 |
+
except Exception as e:
|
| 578 |
+
raise HTTPException(
|
| 579 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 580 |
+
detail=f"Login failed: {str(e)}"
|
| 581 |
+
)
|
src/api/routes/tasks.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
tasks = await TaskService.get_tasks_for_user(session, current_user.id, limit, offset)
|
| 36 |
+
|
| 37 |
+
return {
|
| 38 |
+
"success": True,
|
| 39 |
+
"data": {
|
| 40 |
+
"tasks": tasks,
|
| 41 |
+
"total": len(tasks) # In a real implementation, this would come from a count query
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
except Exception as e:
|
| 45 |
+
raise HTTPException(
|
| 46 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 47 |
+
detail=f"Unable to retrieve tasks: {str(e)}"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@router.post("/", response_model=dict)
|
| 52 |
+
async def create_task(
|
| 53 |
+
task_create: TaskCreate,
|
| 54 |
+
current_user: UserRead = Depends(get_current_user),
|
| 55 |
+
session: AsyncSession = Depends(get_async_session)
|
| 56 |
+
):
|
| 57 |
+
"""
|
| 58 |
+
Create a new task for the authenticated user.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
task_create: Task creation data
|
| 62 |
+
current_user: The authenticated user
|
| 63 |
+
session: Async database session
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
Dictionary containing the created task
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
# Create the task with the authenticated user's ID
|
| 70 |
+
created_task = await TaskService.create_task(session, task_create, current_user.id)
|
| 71 |
+
|
| 72 |
+
return {
|
| 73 |
+
"success": True,
|
| 74 |
+
"data": created_task
|
| 75 |
+
}
|
| 76 |
+
except Exception as e:
|
| 77 |
+
raise HTTPException(
|
| 78 |
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
| 79 |
+
detail=f"Unable to create task: {str(e)}"
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@router.get("/{task_id}", response_model=dict)
|
| 84 |
+
async def get_task(
|
| 85 |
+
task_id: int,
|
| 86 |
+
current_user: UserRead = Depends(get_current_user),
|
| 87 |
+
session: AsyncSession = Depends(get_async_session)
|
| 88 |
+
):
|
| 89 |
+
"""
|
| 90 |
+
Retrieve a specific task by ID for the authenticated user.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
task_id: ID of the task to retrieve
|
| 94 |
+
current_user: The authenticated user
|
| 95 |
+
session: Async database session
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
Dictionary containing the task data
|
| 99 |
+
"""
|
| 100 |
+
try:
|
| 101 |
+
task = await TaskService.get_task_by_id(session, task_id, current_user.id)
|
| 102 |
+
|
| 103 |
+
return {
|
| 104 |
+
"success": True,
|
| 105 |
+
"data": task
|
| 106 |
+
}
|
| 107 |
+
except HTTPException:
|
| 108 |
+
# Re-raise HTTP exceptions as-is
|
| 109 |
+
raise
|
| 110 |
+
except Exception as e:
|
| 111 |
+
raise HTTPException(
|
| 112 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 113 |
+
detail=f"Unable to retrieve task: {str(e)}"
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@router.put("/{task_id}", response_model=dict)
|
| 118 |
+
async def update_task(
|
| 119 |
+
task_id: int,
|
| 120 |
+
task_update: TaskUpdate,
|
| 121 |
+
current_user: UserRead = Depends(get_current_user),
|
| 122 |
+
session: AsyncSession = Depends(get_async_session)
|
| 123 |
+
):
|
| 124 |
+
"""
|
| 125 |
+
Update a specific task by ID for the authenticated user.
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
task_id: ID of the task to update
|
| 129 |
+
task_update: Task update data
|
| 130 |
+
current_user: The authenticated user
|
| 131 |
+
session: Async database session
|
| 132 |
+
|
| 133 |
+
Returns:
|
| 134 |
+
Dictionary containing the updated task
|
| 135 |
+
"""
|
| 136 |
+
try:
|
| 137 |
+
updated_task = await TaskService.update_task(session, task_id, task_update, current_user.id)
|
| 138 |
+
|
| 139 |
+
return {
|
| 140 |
+
"success": True,
|
| 141 |
+
"data": updated_task
|
| 142 |
+
}
|
| 143 |
+
except HTTPException:
|
| 144 |
+
# Re-raise HTTP exceptions as-is
|
| 145 |
+
raise
|
| 146 |
+
except Exception as e:
|
| 147 |
+
raise HTTPException(
|
| 148 |
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
| 149 |
+
detail=f"Unable to update task: {str(e)}"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@router.delete("/{task_id}", response_model=dict)
|
| 154 |
+
async def delete_task(
|
| 155 |
+
task_id: int,
|
| 156 |
+
current_user: UserRead = Depends(get_current_user),
|
| 157 |
+
session: AsyncSession = Depends(get_async_session)
|
| 158 |
+
):
|
| 159 |
+
"""
|
| 160 |
+
Delete a specific task by ID for the authenticated user.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
task_id: ID of the task to delete
|
| 164 |
+
current_user: The authenticated user
|
| 165 |
+
session: Async database session
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
Dictionary containing success message
|
| 169 |
+
"""
|
| 170 |
+
try:
|
| 171 |
+
await TaskService.delete_task(session, task_id, current_user.id)
|
| 172 |
+
|
| 173 |
+
return {
|
| 174 |
+
"success": True,
|
| 175 |
+
"data": {
|
| 176 |
+
"message": "Task deleted successfully"
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
except HTTPException:
|
| 180 |
+
# Re-raise HTTP exceptions as-is
|
| 181 |
+
raise
|
| 182 |
+
except Exception as e:
|
| 183 |
+
raise HTTPException(
|
| 184 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 185 |
+
detail=f"Unable to delete task: {str(e)}"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@router.patch("/{task_id}/toggle", response_model=dict)
|
| 190 |
+
async def toggle_task_completion(
|
| 191 |
+
task_id: int,
|
| 192 |
+
current_user: UserRead = Depends(get_current_user),
|
| 193 |
+
session: AsyncSession = Depends(get_async_session)
|
| 194 |
+
):
|
| 195 |
+
"""
|
| 196 |
+
Toggle the completion status of a specific task.
|
| 197 |
+
|
| 198 |
+
Args:
|
| 199 |
+
task_id: ID of the task to toggle
|
| 200 |
+
current_user: The authenticated user
|
| 201 |
+
session: Async database session
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
Dictionary containing the updated task
|
| 205 |
+
"""
|
| 206 |
+
try:
|
| 207 |
+
updated_task = await TaskService.toggle_task_completion(session, task_id, current_user.id)
|
| 208 |
+
|
| 209 |
+
return {
|
| 210 |
+
"success": True,
|
| 211 |
+
"data": {
|
| 212 |
+
"id": updated_task.id,
|
| 213 |
+
"completed": updated_task.completed,
|
| 214 |
+
"updated_at": updated_task.updated_at
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
except HTTPException:
|
| 218 |
+
# Re-raise HTTP exceptions as-is
|
| 219 |
+
raise
|
| 220 |
+
except Exception as e:
|
| 221 |
+
raise HTTPException(
|
| 222 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 223 |
+
detail=f"Unable to toggle task completion: {str(e)}"
|
| 224 |
+
)
|
src/config.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from pydantic_settings import BaseSettings
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Settings(BaseSettings):
|
| 8 |
+
# Database settings
|
| 9 |
+
database_url: str = os.getenv("DATABASE_URL", "postgresql+asyncpg://user:password@localhost/todo_db")
|
| 10 |
+
async_database_url: str = os.getenv(
|
| 11 |
+
"ASYNC_DATABASE_URL",
|
| 12 |
+
"postgresql+asyncpg://user:password@localhost/todo_db"
|
| 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 |
+
# Application settings
|
| 22 |
+
app_name: str = "Todo Backend API"
|
| 23 |
+
debug: bool = os.getenv("DEBUG", "False").lower() == "true"
|
| 24 |
+
api_prefix: str = "/api"
|
| 25 |
+
|
| 26 |
+
class Config:
|
| 27 |
+
env_file = ".env"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
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,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlmodel import create_engine, Session
|
| 2 |
+
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
| 3 |
+
from sqlalchemy.orm import sessionmaker
|
| 4 |
+
|
| 5 |
+
from ..config import settings
|
| 6 |
+
|
| 7 |
+
# Synchronous engine for general use
|
| 8 |
+
sync_engine = create_engine(
|
| 9 |
+
settings.database_url,
|
| 10 |
+
echo=settings.database_echo, # Set to True for SQL query logging
|
| 11 |
+
pool_pre_ping=True, # Verify connections before use
|
| 12 |
+
pool_recycle=300, # Recycle connections every 5 minutes
|
| 13 |
+
pool_size=5, # Number of connections to maintain
|
| 14 |
+
max_overflow=10, # Additional connections beyond pool_size
|
| 15 |
+
pool_timeout=30, # Timeout for getting connection from pool
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# Async engine for async operations (recommended for Neon Serverless PostgreSQL)
|
| 19 |
+
async_engine = create_async_engine(
|
| 20 |
+
settings.async_database_url,
|
| 21 |
+
echo=settings.database_echo, # Set to True for SQL query logging
|
| 22 |
+
pool_pre_ping=True, # Verify connections before use
|
| 23 |
+
pool_recycle=300, # Recycle connections every 5 minutes
|
| 24 |
+
pool_size=5, # Number of connections to maintain
|
| 25 |
+
max_overflow=10, # Additional connections beyond pool_size
|
| 26 |
+
pool_timeout=30, # Timeout for getting connection from pool
|
| 27 |
+
connect_args={
|
| 28 |
+
"server_settings": {
|
| 29 |
+
"application_name": "todo-backend",
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Session makers
|
| 35 |
+
AsyncSessionLocal = sessionmaker(
|
| 36 |
+
autocommit=False,
|
| 37 |
+
autoflush=False,
|
| 38 |
+
bind=async_engine,
|
| 39 |
+
class_=AsyncSession,
|
| 40 |
+
expire_on_commit=False
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
SyncSessionLocal = sessionmaker(
|
| 44 |
+
autocommit=False,
|
| 45 |
+
autoflush=False,
|
| 46 |
+
bind=sync_engine,
|
| 47 |
+
expire_on_commit=False
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_sync_session():
|
| 52 |
+
"""Get a synchronous database session."""
|
| 53 |
+
session = SyncSessionLocal()
|
| 54 |
+
try:
|
| 55 |
+
yield session
|
| 56 |
+
finally:
|
| 57 |
+
session.close()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def get_async_session():
|
| 61 |
+
"""Get an asynchronous database session."""
|
| 62 |
+
async with AsyncSessionLocal() as session:
|
| 63 |
+
yield session
|
| 64 |
+
await session.close()
|
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/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,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Models package for the Todo Backend API.
|
| 3 |
+
|
| 4 |
+
Contains all the SQLModel database models for the application.
|
| 5 |
+
"""
|
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/session.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from sqlmodel import Field, SQLModel
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class AuthenticationSessionBase(SQLModel):
|
| 7 |
+
"""Base model for Authentication Session with common fields."""
|
| 8 |
+
user_id: str = Field(nullable=False) # Reference to associated user
|
| 9 |
+
expires_at: datetime = Field(nullable=False) # Session expiration time
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class AuthenticationSession(AuthenticationSessionBase, table=True):
|
| 13 |
+
"""Authentication Session model for the database table."""
|
| 14 |
+
session_id: Optional[str] = Field(default=None, primary_key=True)
|
| 15 |
+
user_id: str = Field(nullable=False) # Reference to associated user
|
| 16 |
+
jwt_token: str = Field(nullable=False, max_length=500) # JWT token for session management
|
| 17 |
+
expires_at: datetime = Field(nullable=False) # Session expiration time
|
| 18 |
+
created_at: datetime = Field(default_factory=datetime.now, nullable=False)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class AuthenticationSessionCreate(AuthenticationSessionBase):
|
| 22 |
+
"""Model for creating a new authentication session."""
|
| 23 |
+
jwt_token: str
|
| 24 |
+
user_id: str
|
| 25 |
+
expires_at: datetime
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class AuthenticationSessionRead(AuthenticationSessionBase):
|
| 29 |
+
"""Model for reading authentication session data."""
|
| 30 |
+
session_id: str
|
| 31 |
+
jwt_token: str
|
| 32 |
+
created_at: datetime
|
src/models/task.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
from sqlmodel import Field, SQLModel
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TaskBase(SQLModel):
|
| 8 |
+
"""Base model for Task with common fields."""
|
| 9 |
+
title: str = Field(min_length=1, max_length=255)
|
| 10 |
+
description: Optional[str] = Field(default=None, max_length=1000)
|
| 11 |
+
completed: bool = Field(default=False)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TaskCreate(TaskBase):
|
| 15 |
+
"""Model for creating a new task."""
|
| 16 |
+
pass # user_id will be set by the service layer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TaskUpdate(SQLModel):
|
| 20 |
+
"""Model for updating task data."""
|
| 21 |
+
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
| 22 |
+
description: Optional[str] = Field(default=None, max_length=1000)
|
| 23 |
+
completed: Optional[bool] = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Task(TaskBase, table=True):
|
| 27 |
+
"""Task model for the database table."""
|
| 28 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 29 |
+
user_id: int = Field(foreign_key="user.id") # Foreign key for user relationship
|
| 30 |
+
created_at: Optional[datetime] = Field(default_factory=datetime.utcnow)
|
| 31 |
+
updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow, sa_column_kwargs={"onupdate": datetime.utcnow})
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TaskRead(TaskBase):
|
| 35 |
+
"""Model for reading task data."""
|
| 36 |
+
id: int
|
| 37 |
+
user_id: int # Include user_id in read model
|
| 38 |
+
created_at: datetime
|
| 39 |
+
updated_at: datetime
|
src/models/user.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 10 |
+
|
| 11 |
+
class User(UserBase, table=True):
|
| 12 |
+
"""User model for the database table."""
|
| 13 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 14 |
+
password: str = Field(nullable=False, max_length=255) # Hashed password
|
| 15 |
+
name: Optional[str] = Field(default=None, max_length=255) # Optional name field
|
| 16 |
+
date_of_birth: Optional[date] = Field(default=None, nullable=True) # Date of birth
|
| 17 |
+
signup_date: datetime = Field(default_factory=datetime.utcnow, nullable=False) # Non-nullable signup date
|
| 18 |
+
force_password_change: bool = Field(default=False) # Flag to indicate if user needs to change password
|
| 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 |
+
|
| 23 |
+
class UserCreate(UserBase):
|
| 24 |
+
"""Model for creating a new user."""
|
| 25 |
+
password: str
|
| 26 |
+
name: Optional[str] = None
|
| 27 |
+
date_of_birth: Optional[Union[str, datetime]] = None # Date of birth as string or datetime
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class UserRead(UserBase):
|
| 31 |
+
"""Model for reading user data."""
|
| 32 |
+
id: int
|
| 33 |
+
name: Optional[str] = None
|
| 34 |
+
date_of_birth: Optional[date] = None
|
| 35 |
+
signup_date: datetime # Include signup_date in read model
|
| 36 |
+
force_password_change: bool = False
|
| 37 |
+
created_at: datetime
|
| 38 |
+
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/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/task_service.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
from sqlmodel import select
|
| 5 |
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
| 6 |
+
from sqlalchemy.exc import IntegrityError
|
| 7 |
+
|
| 8 |
+
from ..models.task import Task, TaskCreate, TaskUpdate, TaskRead
|
| 9 |
+
from ..utils.error_handlers import NotFoundError, ValidationError, UnauthorizedError
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TaskService:
|
| 13 |
+
"""Service class for handling task-related business logic."""
|
| 14 |
+
|
| 15 |
+
@staticmethod
|
| 16 |
+
async def create_task(session: AsyncSession, task_create: TaskCreate, user_id: int) -> TaskRead:
|
| 17 |
+
"""
|
| 18 |
+
Create a new task for a user.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
session: Database session
|
| 22 |
+
task_create: Task creation data
|
| 23 |
+
user_id: ID of the user creating the task
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
Created task as TaskRead object
|
| 27 |
+
"""
|
| 28 |
+
# Create task object with the authenticated user ID
|
| 29 |
+
# We need to create the Task object directly since TaskCreate doesn't include user_id
|
| 30 |
+
task_data = task_create.model_dump()
|
| 31 |
+
task_data['user_id'] = user_id # Add the user_id to the data
|
| 32 |
+
db_task = Task.model_validate(task_data)
|
| 33 |
+
|
| 34 |
+
session.add(db_task)
|
| 35 |
+
await session.commit()
|
| 36 |
+
await session.refresh(db_task)
|
| 37 |
+
|
| 38 |
+
# Return as TaskRead object
|
| 39 |
+
return TaskRead.model_validate(db_task)
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
async def get_task_by_id(session: AsyncSession, task_id: int, user_id: int) -> TaskRead:
|
| 43 |
+
"""
|
| 44 |
+
Get a specific task by ID for a user.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
session: Database session
|
| 48 |
+
task_id: ID of the task to retrieve
|
| 49 |
+
user_id: ID of the requesting user
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
Task as TaskRead object
|
| 53 |
+
|
| 54 |
+
Raises:
|
| 55 |
+
NotFoundError: If task doesn't exist
|
| 56 |
+
UnauthorizedError: If task exists but doesn't belong to the user
|
| 57 |
+
"""
|
| 58 |
+
# First, check if the task exists regardless of ownership
|
| 59 |
+
statement_exists = select(Task).where(Task.id == task_id)
|
| 60 |
+
result_exists = await session.execute(statement_exists)
|
| 61 |
+
task_exists = result_exists.scalar_one_or_none()
|
| 62 |
+
|
| 63 |
+
if not task_exists:
|
| 64 |
+
raise NotFoundError(message=f"Task with id {task_id} not found")
|
| 65 |
+
|
| 66 |
+
# Now check if the user owns the task
|
| 67 |
+
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
|
| 68 |
+
result = await session.execute(statement)
|
| 69 |
+
task = result.scalar_one_or_none()
|
| 70 |
+
|
| 71 |
+
if not task:
|
| 72 |
+
# Task exists but doesn't belong to the user - return 401 Unauthorized
|
| 73 |
+
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
|
| 74 |
+
|
| 75 |
+
return TaskRead.model_validate(task)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
async def get_tasks_for_user(session: AsyncSession, user_id: int, limit: int = 20, offset: int = 0) -> List[TaskRead]:
|
| 79 |
+
"""
|
| 80 |
+
Get all tasks for a specific user.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
session: Database session
|
| 84 |
+
user_id: ID of the user whose tasks to retrieve
|
| 85 |
+
limit: Maximum number of tasks to return
|
| 86 |
+
offset: Number of tasks to skip
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
List of tasks as TaskRead objects
|
| 90 |
+
"""
|
| 91 |
+
statement = select(Task).where(Task.user_id == user_id).offset(offset).limit(limit)
|
| 92 |
+
result = await session.execute(statement)
|
| 93 |
+
tasks = result.scalars().all()
|
| 94 |
+
|
| 95 |
+
return [TaskRead.model_validate(task) for task in tasks]
|
| 96 |
+
|
| 97 |
+
@staticmethod
|
| 98 |
+
async def update_task(session: AsyncSession, task_id: int, task_update: TaskUpdate, user_id: int) -> TaskRead:
|
| 99 |
+
"""
|
| 100 |
+
Update a specific task for a user.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
session: Database session
|
| 104 |
+
task_id: ID of the task to update
|
| 105 |
+
task_update: Task update data
|
| 106 |
+
user_id: ID of the requesting user
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
Updated task as TaskRead object
|
| 110 |
+
|
| 111 |
+
Raises:
|
| 112 |
+
NotFoundError: If task doesn't exist
|
| 113 |
+
UnauthorizedError: If task exists but doesn't belong to the user
|
| 114 |
+
"""
|
| 115 |
+
# First, check if the task exists regardless of ownership
|
| 116 |
+
statement_exists = select(Task).where(Task.id == task_id)
|
| 117 |
+
result_exists = await session.execute(statement_exists)
|
| 118 |
+
task_exists = result_exists.scalar_one_or_none()
|
| 119 |
+
|
| 120 |
+
if not task_exists:
|
| 121 |
+
raise NotFoundError(message=f"Task with id {task_id} not found")
|
| 122 |
+
|
| 123 |
+
# Now check if the user owns the task
|
| 124 |
+
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
|
| 125 |
+
result = await session.execute(statement)
|
| 126 |
+
task = result.scalar_one_or_none()
|
| 127 |
+
|
| 128 |
+
if not task:
|
| 129 |
+
# Task exists but doesn't belong to the user - return 401 Unauthorized
|
| 130 |
+
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
|
| 131 |
+
|
| 132 |
+
# Update task fields with provided values
|
| 133 |
+
update_data = task_update.model_dump(exclude_unset=True)
|
| 134 |
+
for field, value in update_data.items():
|
| 135 |
+
setattr(task, field, value)
|
| 136 |
+
|
| 137 |
+
task.updated_at = datetime.utcnow()
|
| 138 |
+
|
| 139 |
+
session.add(task)
|
| 140 |
+
await session.commit()
|
| 141 |
+
await session.refresh(task)
|
| 142 |
+
|
| 143 |
+
return TaskRead.model_validate(task)
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
async def delete_task(session: AsyncSession, task_id: int, user_id: int) -> bool:
|
| 147 |
+
"""
|
| 148 |
+
Delete a specific task for a user.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
session: Database session
|
| 152 |
+
task_id: ID of the task to delete
|
| 153 |
+
user_id: ID of the requesting user
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
True if task was deleted, False otherwise
|
| 157 |
+
|
| 158 |
+
Raises:
|
| 159 |
+
NotFoundError: If task doesn't exist
|
| 160 |
+
UnauthorizedError: If task exists but doesn't belong to the user
|
| 161 |
+
"""
|
| 162 |
+
# First, check if the task exists regardless of ownership
|
| 163 |
+
statement_exists = select(Task).where(Task.id == task_id)
|
| 164 |
+
result_exists = await session.execute(statement_exists)
|
| 165 |
+
task_exists = result_exists.scalar_one_or_none()
|
| 166 |
+
|
| 167 |
+
if not task_exists:
|
| 168 |
+
raise NotFoundError(message=f"Task with id {task_id} not found")
|
| 169 |
+
|
| 170 |
+
# Now check if the user owns the task
|
| 171 |
+
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
|
| 172 |
+
result = await session.execute(statement)
|
| 173 |
+
task = result.scalar_one_or_none()
|
| 174 |
+
|
| 175 |
+
if not task:
|
| 176 |
+
# Task exists but doesn't belong to the user - return 401 Unauthorized
|
| 177 |
+
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
|
| 178 |
+
|
| 179 |
+
await session.delete(task)
|
| 180 |
+
await session.commit()
|
| 181 |
+
|
| 182 |
+
return True
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
async def toggle_task_completion(session: AsyncSession, task_id: int, user_id: int) -> TaskRead:
|
| 186 |
+
"""
|
| 187 |
+
Toggle the completion status of a specific task.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
session: Database session
|
| 191 |
+
task_id: ID of the task to toggle
|
| 192 |
+
user_id: ID of the requesting user
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
Updated task as TaskRead object
|
| 196 |
+
|
| 197 |
+
Raises:
|
| 198 |
+
NotFoundError: If task doesn't exist
|
| 199 |
+
UnauthorizedError: If task exists but doesn't belong to the user
|
| 200 |
+
"""
|
| 201 |
+
# First, check if the task exists regardless of ownership
|
| 202 |
+
statement_exists = select(Task).where(Task.id == task_id)
|
| 203 |
+
result_exists = await session.execute(statement_exists)
|
| 204 |
+
task_exists = result_exists.scalar_one_or_none()
|
| 205 |
+
|
| 206 |
+
if not task_exists:
|
| 207 |
+
raise NotFoundError(message=f"Task with id {task_id} not found")
|
| 208 |
+
|
| 209 |
+
# Now check if the user owns the task
|
| 210 |
+
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
|
| 211 |
+
result = await session.execute(statement)
|
| 212 |
+
task = result.scalar_one_or_none()
|
| 213 |
+
|
| 214 |
+
if not task:
|
| 215 |
+
# Task exists but doesn't belong to the user - return 401 Unauthorized
|
| 216 |
+
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
|
| 217 |
+
|
| 218 |
+
# Toggle the completion status
|
| 219 |
+
task.completed = not task.completed
|
| 220 |
+
task.updated_at = datetime.utcnow()
|
| 221 |
+
|
| 222 |
+
session.add(task)
|
| 223 |
+
await session.commit()
|
| 224 |
+
await session.refresh(task)
|
| 225 |
+
|
| 226 |
+
return TaskRead.model_validate(task)
|
| 227 |
+
|
| 228 |
+
@staticmethod
|
| 229 |
+
async def verify_task_ownership(session: AsyncSession, task_id: int, user_id: int) -> bool:
|
| 230 |
+
"""
|
| 231 |
+
Verify if a user owns a specific task.
|
| 232 |
+
|
| 233 |
+
Args:
|
| 234 |
+
session: Database session
|
| 235 |
+
task_id: ID of the task to check
|
| 236 |
+
user_id: ID of the user to check ownership for
|
| 237 |
+
|
| 238 |
+
Returns:
|
| 239 |
+
True if the user owns the task, False otherwise
|
| 240 |
+
"""
|
| 241 |
+
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
|
| 242 |
+
result = await session.execute(statement)
|
| 243 |
+
task = result.scalar_one_or_none()
|
| 244 |
+
|
| 245 |
+
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,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Create a custom logger for the application
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
# Create handlers
|
| 13 |
+
console_handler = logging.StreamHandler()
|
| 14 |
+
console_handler.setLevel(logging.INFO)
|
| 15 |
+
|
| 16 |
+
# Create formatters and add them to handlers
|
| 17 |
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 18 |
+
console_handler.setFormatter(formatter)
|
| 19 |
+
|
| 20 |
+
# Add handlers to the logger
|
| 21 |
+
logger.addHandler(console_handler)
|
| 22 |
+
|
| 23 |
+
class SecurityLogger:
|
| 24 |
+
"""Custom logger for security-related events."""
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def log_task_access_attempt(user_id: int, task_id: int, action: str, success: bool, ip_address: Optional[str] = None):
|
| 28 |
+
"""Log task access attempts for security monitoring."""
|
| 29 |
+
log_data = {
|
| 30 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 31 |
+
"event_type": "task_access",
|
| 32 |
+
"user_id": user_id,
|
| 33 |
+
"task_id": task_id,
|
| 34 |
+
"action": action,
|
| 35 |
+
"success": success,
|
| 36 |
+
"ip_address": ip_address
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
log_message = f"Task access attempt: {json.dumps(log_data)}"
|
| 40 |
+
|
| 41 |
+
if success:
|
| 42 |
+
logger.info(log_message)
|
| 43 |
+
else:
|
| 44 |
+
logger.warning(log_message)
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
def log_authentication_event(event_type: str, user_id: Optional[int] = None, ip_address: Optional[str] = None, details: Optional[str] = None):
|
| 48 |
+
"""Log authentication events for security monitoring."""
|
| 49 |
+
log_data = {
|
| 50 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 51 |
+
"event_type": event_type,
|
| 52 |
+
"user_id": user_id,
|
| 53 |
+
"ip_address": ip_address,
|
| 54 |
+
"details": details
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
log_message = f"Authentication event: {json.dumps(log_data)}"
|
| 58 |
+
|
| 59 |
+
if event_type in ["login_success", "logout"]:
|
| 60 |
+
logger.info(log_message)
|
| 61 |
+
elif event_type in ["login_failure", "auth_failure", "access_denied"]:
|
| 62 |
+
logger.warning(log_message)
|
| 63 |
+
else:
|
| 64 |
+
logger.info(log_message)
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def log_unauthorized_access(endpoint: str, user_id: Optional[int] = None, ip_address: Optional[str] = None):
|
| 68 |
+
"""Log unauthorized access attempts."""
|
| 69 |
+
log_data = {
|
| 70 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 71 |
+
"event_type": "unauthorized_access",
|
| 72 |
+
"endpoint": endpoint,
|
| 73 |
+
"user_id": user_id,
|
| 74 |
+
"ip_address": ip_address
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
log_message = f"Unauthorized access attempt: {json.dumps(log_data)}"
|
| 78 |
+
logger.warning(log_message)
|
| 79 |
+
|
| 80 |
+
# Convenience functions
|
| 81 |
+
def log_task_access(user_id: int, task_id: int, action: str, success: bool = True, ip_address: Optional[str] = None):
|
| 82 |
+
"""Convenience function to log task access."""
|
| 83 |
+
SecurityLogger.log_task_access_attempt(user_id, task_id, action, success, ip_address)
|
| 84 |
+
|
| 85 |
+
def log_auth_event(event_type: str, user_id: Optional[int] = None, ip_address: Optional[str] = None, details: Optional[str] = None):
|
| 86 |
+
"""Convenience function to log authentication events."""
|
| 87 |
+
SecurityLogger.log_authentication_event(event_type, user_id, ip_address, details)
|
| 88 |
+
|
| 89 |
+
def log_unauthorized(endpoint: str, user_id: Optional[int] = None, ip_address: Optional[str] = None):
|
| 90 |
+
"""Convenience function to log unauthorized access."""
|
| 91 |
+
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
|