LuoChinWen c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
..
.hypothesis 3408bea816 -dev:完成task和project相关接口 1 lună în urmă
middleware 9d67d5a960 -dev:接入了oauth平台 1 lună în urmă
routers c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
schemas baca142bff -dev:完成mock登录,准备接入oauth 1 lună în urmă
scripts c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
services 9d67d5a960 -dev:接入了oauth平台 1 lună în urmă
test 3408bea816 -dev:完成task和project相关接口 1 lună în urmă
.dockerignore 7e2974cc6d -dev:增加了docker与前端编译 4 săptămâni în urmă
.env.example baca142bff -dev:完成mock登录,准备接入oauth 1 lună în urmă
DOCKER_DEPLOYMENT.md 7e2974cc6d -dev:增加了docker与前端编译 4 săptămâni în urmă
Dockerfile 7e2974cc6d -dev:增加了docker与前端编译 4 săptămâni în urmă
JWT_AUTHENTICATION_GUIDE.md baca142bff -dev:完成mock登录,准备接入oauth 1 lună în urmă
README.md baca142bff -dev:完成mock登录,准备接入oauth 1 lună în urmă
SAMPLE_DATA_README.md f4b2447602 stage1 1 lună în urmă
config.docker.yaml c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
config.py c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
config.yaml c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
create_test_user.py baca142bff -dev:完成mock登录,准备接入oauth 1 lună în urmă
database.py c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
docker-compose.yml 7e2974cc6d -dev:增加了docker与前端编译 4 săptămâni în urmă
main.py 9d67d5a960 -dev:接入了oauth平台 1 lună în urmă
models.py baca142bff -dev:完成mock登录,准备接入oauth 1 lună în urmă
pytest.ini e495e45135 -dev:后端接口开发:任务相关 1 lună în urmă
requirements.txt c9f743e882 -dev:完成数据库的切换 4 săptămâni în urmă
test_oauth_config.py 9d67d5a960 -dev:接入了oauth平台 1 lună în urmă
test_oauth_flow.py 9d67d5a960 -dev:接入了oauth平台 1 lună în urmă

README.md

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:

    pip install -r requirements.txt
    
  2. Configure environment variables:

    cp .env.example .env
    # Edit .env with your configuration
    

Important: Set a secure JWT_SECRET_KEY in production:

# 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:

python main.py

Or with uvicorn directly:

uvicorn main:app --reload --host 0.0.0.0 --port 8000

API Documentation

Once the server is running, visit:

Authentication

User Registration

Register a new user:

curl -X POST "http://localhost:8000/api/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "email": "test@example.com",
    "password": "securepassword123"
  }'

Response:

{
  "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:

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:

curl -X GET "http://localhost:8000/api/projects" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Token Refresh

Refresh your access token using the refresh token:

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:

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:

pytest

Run tests with coverage:

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:

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]