lingmin_package@163.com b96a6b8137 配置文件目录调整 пре 1 месец
..
config b96a6b8137 配置文件目录调整 пре 1 месец
docker b96a6b8137 配置文件目录调整 пре 1 месец
middleware c8f462c82a 标注平台增加环境变量test пре 1 месец
routers c8f462c82a 标注平台增加环境变量test пре 1 месец
schemas c8f462c82a 标注平台增加环境变量test пре 1 месец
scripts 535ec53254 -dev:新功能 пре 2 месеци
services a2c1291f5e -fix:修复了角色字段的映射 пре 1 месец
test 4858c0c44d -dev:完成了token效验的替换工作 пре 1 месец
.dockerignore 7e2974cc6d -dev:增加了docker与前端编译 пре 2 месеци
.env.example baca142bff -dev:完成mock登录,准备接入oauth пре 2 месеци
DOCKER_DEPLOYMENT.md 7e2974cc6d -dev:增加了docker与前端编译 пре 2 месеци
Dockerfile f7119cf009 -dev:修复数据库问题 пре 2 месеци
EXTERNAL_API_DOCUMENTATION.md 1cd7a51d37 -dev:修改了导出功能 пре 2 месеци
JWT_AUTHENTICATION_GUIDE.md baca142bff -dev:完成mock登录,准备接入oauth пре 2 месеци
README.md c8f462c82a 标注平台增加环境变量test пре 1 месец
SAMPLE_DATA_README.md f4b2447602 stage1 пре 2 месеци
config.py b96a6b8137 配置文件目录调整 пре 1 месец
create_test_user.py baca142bff -dev:完成mock登录,准备接入oauth пре 2 месеци
database.py f7119cf009 -dev:修复数据库问题 пре 2 месеци
main.py 4858c0c44d -dev:完成了token效验的替换工作 пре 1 месец
models.py baca142bff -dev:完成mock登录,准备接入oauth пре 2 месеци
pytest.ini e495e45135 -dev:后端接口开发:任务相关 пре 3 месеци
requirements.txt c9f743e882 -dev:完成数据库的切换 пре 2 месеци
test_oauth_config.py 9d67d5a960 -dev:接入了oauth平台 пре 2 месеци
test_oauth_flow.py 0dd07ce317 -dev:修改了端口号并发布 пре 2 месеци
yarn.lock c8f462c82a 标注平台增加环境变量test пре 1 месец

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

创建虚拟环境

# 使用 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

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]