增加API鉴权

This commit is contained in:
jeremygan2021
2025-11-16 18:00:28 +08:00
parent bb04bd8fa5
commit b7a8a86e53
23 changed files with 343 additions and 52 deletions

View File

@@ -1,4 +1,4 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException, status, Security
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
@@ -7,13 +7,13 @@ from database import get_db
from schemas import Todo as TodoSchema, TodoCreate, TodoUpdate
from models import Todo as TodoModel
from database import Device as DeviceModel
from auth import get_api_key
router = APIRouter(
prefix="/api/todos",
tags=["todos"]
)
@router.post("/", response_model=TodoSchema, status_code=status.HTTP_201_CREATED)
@router.post("/", response_model=TodoSchema, status_code=status.HTTP_201_CREATED, dependencies=[Depends(get_api_key)])
async def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
创建新的待办事项
@@ -40,7 +40,7 @@ async def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
return db_todo
@router.get("/", response_model=List[TodoSchema])
@router.get("/", response_model=List[TodoSchema], dependencies=[Depends(get_api_key)])
async def list_todos(
skip: int = 0,
limit: int = 100,
@@ -62,7 +62,7 @@ async def list_todos(
todos = query.order_by(TodoModel.created_at.desc()).offset(skip).limit(limit).all()
return todos
@router.get("/{todo_id}", response_model=TodoSchema)
@router.get("/{todo_id}", response_model=TodoSchema, dependencies=[Depends(get_api_key)])
async def get_todo(todo_id: int, db: Session = Depends(get_db)):
"""
获取待办事项详情
@@ -75,7 +75,7 @@ async def get_todo(todo_id: int, db: Session = Depends(get_db)):
)
return todo
@router.put("/{todo_id}", response_model=TodoSchema)
@router.put("/{todo_id}", response_model=TodoSchema, dependencies=[Depends(get_api_key)])
async def update_todo(
todo_id: int,
todo_update: TodoUpdate,
@@ -110,7 +110,7 @@ async def update_todo(
return todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(get_api_key)])
async def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
删除待办事项
@@ -125,7 +125,7 @@ async def delete_todo(todo_id: int, db: Session = Depends(get_db)):
db.delete(todo)
db.commit()
@router.post("/{todo_id}/complete", response_model=TodoSchema)
@router.post("/{todo_id}/complete", response_model=TodoSchema, dependencies=[Depends(get_api_key)])
async def complete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
标记待办事项为完成
@@ -146,7 +146,7 @@ async def complete_todo(todo_id: int, db: Session = Depends(get_db)):
return todo
@router.post("/{todo_id}/incomplete", response_model=TodoSchema)
@router.post("/{todo_id}/incomplete", response_model=TodoSchema, dependencies=[Depends(get_api_key)])
async def incomplete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
标记待办事项为未完成