# Annotation Platform Backend FastAPI-based backend for the annotation platform with JWT authentication. ## Features - ๐Ÿ” JWT-based authentication and authorization - ๐Ÿ‘ฅ Role-based access control (Admin, Annotator) - ๐Ÿ“ Project, Task, and Annotation management - ๐Ÿ”„ Token refresh mechanism - ๐Ÿš€ RESTful API with automatic documentation - ๐Ÿ—„๏ธ SQLite database with automatic initialization ## Setup 1. Install dependencies: ```bash pip install -r requirements.txt ``` 2. Configure environment variables: ```bash cp .env.example .env # Edit .env with your configuration ``` **Important**: Set a secure `JWT_SECRET_KEY` in production: ```bash # Generate a secure random key python -c "import secrets; print(secrets.token_urlsafe(32))" ``` ### Environment Variables | Variable | Description | Default | |----------|-------------|---------| | `JWT_SECRET_KEY` | Secret key for JWT token signing | Auto-generated (dev only) | | `JWT_ALGORITHM` | JWT signing algorithm | `HS256` | | `ACCESS_TOKEN_EXPIRE_MINUTES` | Access token expiration time | `15` minutes | | `REFRESH_TOKEN_EXPIRE_DAYS` | Refresh token expiration time | `7` days | | `DATABASE_PATH` | SQLite database file path | `annotation_platform.db` | ## Running the Server Development mode: ```bash python main.py ``` Or with uvicorn directly: ```bash uvicorn main:app --reload --host 0.0.0.0 --port 8000 ``` ## API Documentation Once the server is running, visit: - Swagger UI: http://localhost:8000/docs - ReDoc: http://localhost:8000/redoc ## Authentication ### User Registration Register a new user: ```bash curl -X POST "http://localhost:8000/api/auth/register" \ -H "Content-Type: application/json" \ -d '{ "username": "testuser", "email": "test@example.com", "password": "securepassword123" }' ``` Response: ```json { "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "token_type": "bearer", "user": { "id": "user_abc123", "username": "testuser", "email": "test@example.com", "role": "annotator", "created_at": "2024-01-01T00:00:00" } } ``` ### User Login Login with existing credentials: ```bash curl -X POST "http://localhost:8000/api/auth/login" \ -H "Content-Type: application/json" \ -d '{ "username": "testuser", "password": "securepassword123" }' ``` ### Using Access Tokens Include the access token in the `Authorization` header for protected endpoints: ```bash curl -X GET "http://localhost:8000/api/projects" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Token Refresh Refresh your access token using the refresh token: ```bash curl -X POST "http://localhost:8000/api/auth/refresh" \ -H "Content-Type: application/json" \ -d '{ "refresh_token": "YOUR_REFRESH_TOKEN" }' ``` ### Get Current User Get information about the currently authenticated user: ```bash curl -X GET "http://localhost:8000/api/auth/me" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ## Authorization ### User Roles - **annotator** (default): Can create and manage their own annotations - **admin**: Full access to all resources, including deletion ### Protected Endpoints All API endpoints except authentication endpoints require a valid JWT token. #### Public Endpoints (No Authentication Required) - `POST /api/auth/register` - User registration - `POST /api/auth/login` - User login - `POST /api/auth/refresh` - Token refresh - `GET /` - Health check - `GET /health` - Health check - `GET /docs` - API documentation - `GET /redoc` - API documentation #### Protected Endpoints (Authentication Required) - `GET /api/auth/me` - Get current user info - All `/api/projects/*` endpoints - All `/api/tasks/*` endpoints - All `/api/annotations/*` endpoints #### Admin-Only Endpoints - `DELETE /api/projects/{project_id}` - Delete project - `DELETE /api/tasks/{task_id}` - Delete task ### Permission Rules 1. **Annotations**: - Users can only create annotations with their own user ID - Users can only view and update their own annotations - Admins can view and update all annotations 2. **Tasks**: - If `assigned_to` is not provided when creating a task, it defaults to the current user - All authenticated users can view and update tasks - Only admins can delete tasks 3. **Projects**: - All authenticated users can create, view, and update projects - Only admins can delete projects ## Project Structure ``` backend/ โ”œโ”€โ”€ main.py # FastAPI application entry point โ”œโ”€โ”€ config.py # Configuration management โ”œโ”€โ”€ database.py # Database connection and initialization โ”œโ”€โ”€ models.py # Database models (User, Project, Task, Annotation) โ”œโ”€โ”€ requirements.txt # Python dependencies โ”œโ”€โ”€ .env.example # Environment variables template โ”œโ”€โ”€ middleware/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ auth_middleware.py # JWT authentication middleware โ”œโ”€โ”€ routers/ # API route handlers โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”œโ”€โ”€ auth.py # Authentication endpoints โ”‚ โ”œโ”€โ”€ project.py # Project management โ”‚ โ”œโ”€โ”€ task.py # Task management โ”‚ โ””โ”€โ”€ annotation.py # Annotation management โ”œโ”€โ”€ services/ # Business logic โ”‚ โ”œโ”€โ”€ jwt_service.py # JWT token operations โ”‚ โ””โ”€โ”€ auth_service.py # Authentication logic โ”œโ”€โ”€ schemas/ # Pydantic schemas for validation โ”‚ โ”œโ”€โ”€ auth.py # Authentication schemas โ”‚ โ”œโ”€โ”€ project.py # Project schemas โ”‚ โ”œโ”€โ”€ task.py # Task schemas โ”‚ โ””โ”€โ”€ annotation.py # Annotation schemas โ””โ”€โ”€ test/ # Test files โ””โ”€โ”€ ... ``` ## Database The application uses SQLite for data storage. The database file is created automatically on first run. Default location: `annotation_platform.db` To use a custom location, set the `DATABASE_PATH` environment variable. ### Database Schema - **users**: User accounts with authentication info - `id`, `username`, `email`, `password_hash`, `role`, `oauth_provider`, `oauth_id`, `created_at` - **projects**: Annotation projects - `id`, `name`, `description`, `config`, `created_at` - **tasks**: Annotation tasks within projects - `id`, `project_id`, `name`, `data`, `status`, `assigned_to`, `created_at` - **annotations**: User annotations for tasks - `id`, `task_id`, `user_id`, `result`, `created_at`, `updated_at` ## Testing Run tests with pytest: ```bash pytest ``` Run tests with coverage: ```bash pytest --cov=. --cov-report=html ``` ## Security Considerations 1. **JWT Secret Key**: Always use a strong, randomly generated secret key in production 2. **HTTPS**: Use HTTPS in production to protect tokens in transit 3. **Token Storage**: Store tokens securely on the client side (e.g., httpOnly cookies or secure storage) 4. **Token Expiration**: Access tokens expire after 15 minutes, refresh tokens after 7 days 5. **Password Hashing**: Passwords are hashed using bcrypt with automatic salt generation 6. **CORS**: Configure CORS settings in `main.py` to match your frontend domain ## Future Enhancements - [ ] OAuth 2.0 integration (Google, GitHub, etc.) - [ ] Email verification - [ ] Password reset functionality - [ ] User profile management - [ ] Audit logging - [ ] Rate limiting - [ ] Two-factor authentication (2FA) ## Troubleshooting ### "็ผบๅฐ‘่ฎค่ฏไปค็‰Œ" Error Make sure you include the `Authorization` header with a valid Bearer token: ``` Authorization: Bearer YOUR_ACCESS_TOKEN ``` ### "่ฎค่ฏไปค็‰Œๅทฒ่ฟ‡ๆœŸ" Error Your access token has expired. Use the refresh token to get a new access token: ```bash POST /api/auth/refresh ``` ### "ๆƒ้™ไธ่ถณ" Error Your user role doesn't have permission for this operation. Contact an admin if you need elevated permissions. ## License [Your License Here]