|
|
vor 4 Wochen | |
|---|---|---|
| .. | ||
| config | vor 4 Wochen | |
| docker | vor 1 Monat | |
| middleware | vor 4 Wochen | |
| routers | vor 4 Wochen | |
| schemas | vor 4 Wochen | |
| scripts | vor 4 Wochen | |
| services | vor 1 Monat | |
| test | vor 1 Monat | |
| .dockerignore | vor 2 Monaten | |
| .env.example | vor 2 Monaten | |
| DOCKER_DEPLOYMENT.md | vor 2 Monaten | |
| Dockerfile | vor 1 Monat | |
| EXTERNAL_API_DOCUMENTATION.md | vor 2 Monaten | |
| JWT_AUTHENTICATION_GUIDE.md | vor 2 Monaten | |
| README.md | vor 1 Monat | |
| SAMPLE_DATA_README.md | vor 2 Monaten | |
| config.py | vor 4 Wochen | |
| create_test_user.py | vor 2 Monaten | |
| database.py | vor 2 Monaten | |
| main.py | vor 1 Monat | |
| models.py | vor 2 Monaten | |
| pytest.ini | vor 3 Monaten | |
| requirements.txt | vor 2 Monaten | |
| test_oauth_config.py | vor 2 Monaten | |
| test_oauth_flow.py | vor 2 Monaten | |
| yarn.lock | vor 1 Monat | |
FastAPI-based backend for the annotation platform with JWT authentication.
# 使用 conda
conda create --name lq_label python=3.11
conda activate lq_label
## Setup
1. Install dependencies:
bash pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
2. Configure environment variables:
bash cp .env.example .env
**Important**: Set a secure `JWT_SECRET_KEY` in production:
bash
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 ```
Your user role doesn't have permission for this operation. Contact an admin if you need elevated permissions.
[Your License Here]