11
This commit is contained in:
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""aiclient Python 后端。"""
|
||||
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
67
app/api/v1/auth.py
Normal file
67
app/api/v1/auth.py
Normal file
@@ -0,0 +1,67 @@
|
||||
from fastapi import APIRouter, Header
|
||||
|
||||
from app.dependencies import CurrentUser, DbSession, RedisClient
|
||||
from app.schemas.auth import LoginRequest, RegisterRequest, TokenResponse, UserPublic
|
||||
from app.schemas.common import ApiResponse
|
||||
from app.services import auth as auth_service
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["认证"])
|
||||
|
||||
|
||||
@router.post("/register", response_model=ApiResponse[TokenResponse])
|
||||
async def register(
|
||||
body: RegisterRequest,
|
||||
db: DbSession,
|
||||
redis: RedisClient,
|
||||
) -> ApiResponse[TokenResponse]:
|
||||
try:
|
||||
result = await auth_service.register_user(
|
||||
db,
|
||||
username=body.username,
|
||||
password=body.password,
|
||||
)
|
||||
except auth_service.AuthError as exc:
|
||||
return ApiResponse(ok=False, message=exc.message)
|
||||
|
||||
await auth_service.store_session(redis, result.access_token, result.user.id)
|
||||
return ApiResponse(ok=True, message="注册成功", data=result)
|
||||
|
||||
|
||||
@router.post("/login", response_model=ApiResponse[TokenResponse])
|
||||
async def login(
|
||||
body: LoginRequest,
|
||||
db: DbSession,
|
||||
redis: RedisClient,
|
||||
) -> ApiResponse[TokenResponse]:
|
||||
try:
|
||||
result = await auth_service.login_user(
|
||||
db,
|
||||
username=body.username,
|
||||
password=body.password,
|
||||
)
|
||||
except auth_service.AuthError as exc:
|
||||
return ApiResponse(ok=False, message=exc.message)
|
||||
|
||||
await auth_service.store_session(redis, result.access_token, result.user.id)
|
||||
return ApiResponse(ok=True, message="登录成功", data=result)
|
||||
|
||||
|
||||
@router.post("/logout", response_model=ApiResponse[None])
|
||||
async def logout(
|
||||
redis: RedisClient,
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> ApiResponse[None]:
|
||||
if authorization and authorization.lower().startswith("bearer "):
|
||||
token = authorization[7:].strip()
|
||||
if token:
|
||||
await auth_service.revoke_session(redis, token)
|
||||
return ApiResponse(ok=True, message="已退出登录")
|
||||
|
||||
|
||||
@router.get("/me", response_model=ApiResponse[UserPublic])
|
||||
async def me(current_user: CurrentUser) -> ApiResponse[UserPublic]:
|
||||
return ApiResponse(
|
||||
ok=True,
|
||||
message="",
|
||||
data=UserPublic.model_validate(current_user),
|
||||
)
|
||||
6
app/api/v1/router.py
Normal file
6
app/api/v1/router.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1 import auth
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(auth.router)
|
||||
47
app/config.py
Normal file
47
app/config.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
app_name: str = "aiclient-api"
|
||||
debug: bool = False
|
||||
|
||||
mysql_host: str = "127.0.0.1"
|
||||
mysql_port: int = 3306
|
||||
mysql_user: str = "root"
|
||||
mysql_password: str = ""
|
||||
mysql_database: str = "aiclient"
|
||||
|
||||
redis_url: str = "redis://127.0.0.1:6379/0"
|
||||
|
||||
secret_key: str = Field(default="change-me-in-production")
|
||||
access_token_expire_minutes: int = 60 * 24 * 7
|
||||
|
||||
cors_origins: str = "http://localhost:1420"
|
||||
|
||||
@property
|
||||
def database_url(self) -> str:
|
||||
return (
|
||||
f"mysql+aiomysql://{self.mysql_user}:{self.mysql_password}"
|
||||
f"@{self.mysql_host}:{self.mysql_port}/{self.mysql_database}"
|
||||
)
|
||||
|
||||
@property
|
||||
def cors_origin_list(self) -> list[str]:
|
||||
raw = self.cors_origins.strip()
|
||||
if raw == "*":
|
||||
return ["*"]
|
||||
return [o.strip() for o in raw.split(",") if o.strip()]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
0
app/core/__init__.py
Normal file
0
app/core/__init__.py
Normal file
58
app/core/security.py
Normal file
58
app/core/security.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import bcrypt
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
TOKEN_TYPE = "access"
|
||||
SESSION_PREFIX = "session:"
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(
|
||||
password.encode("utf-8"),
|
||||
bcrypt.gensalt(),
|
||||
).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(
|
||||
plain.encode("utf-8"),
|
||||
hashed.encode("utf-8"),
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(subject: str, expires_delta: timedelta | None = None) -> str:
|
||||
expire = datetime.now(UTC) + (
|
||||
expires_delta
|
||||
if expires_delta is not None
|
||||
else timedelta(minutes=settings.access_token_expire_minutes)
|
||||
)
|
||||
payload = {
|
||||
"sub": subject,
|
||||
"exp": expire,
|
||||
"type": TOKEN_TYPE,
|
||||
}
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
if payload.get("type") != TOKEN_TYPE:
|
||||
return None
|
||||
return payload
|
||||
|
||||
|
||||
def session_redis_key(token: str) -> str:
|
||||
return f"{SESSION_PREFIX}{token}"
|
||||
38
app/database.py
Normal file
38
app/database.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
engine = create_async_engine(
|
||||
settings.database_url,
|
||||
echo=settings.debug,
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
async_session_factory = async_sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session_factory() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
54
app/dependencies.py
Normal file
54
app/dependencies.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from typing import Annotated
|
||||
|
||||
import redis.asyncio as redis
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import decode_access_token
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
from app.redis_client import redis_dependency
|
||||
from app.services import auth as auth_service
|
||||
|
||||
DbSession = Annotated[AsyncSession, Depends(get_db)]
|
||||
RedisClient = Annotated[redis.Redis, Depends(redis_dependency)]
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
db: DbSession,
|
||||
redis: RedisClient,
|
||||
authorization: Annotated[str | None, Header()] = None,
|
||||
) -> User:
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="未提供有效的认证令牌",
|
||||
)
|
||||
|
||||
token = authorization[7:].strip()
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="未提供有效的认证令牌",
|
||||
)
|
||||
|
||||
user_id = await auth_service.session_user_id(redis, token)
|
||||
if user_id is None:
|
||||
payload = decode_access_token(token)
|
||||
if payload is None or payload.get("sub") is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="令牌无效或已过期",
|
||||
)
|
||||
user_id = int(payload["sub"])
|
||||
|
||||
user = await auth_service.get_user_by_id(db, user_id)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="用户不存在",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
44
app/main.py
Normal file
44
app/main.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.v1.router import api_router
|
||||
from app.config import get_settings
|
||||
from app.redis_client import close_redis, init_redis
|
||||
from app.schemas.common import ApiResponse
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
await init_redis()
|
||||
yield
|
||||
await close_redis()
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(
|
||||
title=settings.app_name,
|
||||
debug=settings.debug,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origin_list,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@app.get("/health", response_model=ApiResponse[dict])
|
||||
async def health() -> ApiResponse[dict]:
|
||||
return ApiResponse(ok=True, message="服务正常", data={"status": "up"})
|
||||
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
3
app/models/__init__.py
Normal file
3
app/models/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from app.models.user import User
|
||||
|
||||
__all__ = ["User"]
|
||||
23
app/models/user.py
Normal file
23
app/models/user.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
)
|
||||
36
app/redis_client.py
Normal file
36
app/redis_client.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
_settings = get_settings()
|
||||
_redis: redis.Redis | None = None
|
||||
|
||||
|
||||
async def init_redis() -> redis.Redis:
|
||||
global _redis
|
||||
_redis = redis.from_url(
|
||||
_settings.redis_url,
|
||||
encoding="utf-8",
|
||||
decode_responses=True,
|
||||
)
|
||||
await _redis.ping()
|
||||
return _redis
|
||||
|
||||
|
||||
async def close_redis() -> None:
|
||||
global _redis
|
||||
if _redis is not None:
|
||||
await _redis.aclose()
|
||||
_redis = None
|
||||
|
||||
|
||||
def get_redis() -> redis.Redis:
|
||||
if _redis is None:
|
||||
raise RuntimeError("Redis 尚未初始化")
|
||||
return _redis
|
||||
|
||||
|
||||
async def redis_dependency() -> AsyncGenerator[redis.Redis, None]:
|
||||
yield get_redis()
|
||||
15
app/schemas/__init__.py
Normal file
15
app/schemas/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from app.schemas.auth import (
|
||||
LoginRequest,
|
||||
RegisterRequest,
|
||||
TokenResponse,
|
||||
UserPublic,
|
||||
)
|
||||
from app.schemas.common import ApiResponse
|
||||
|
||||
__all__ = [
|
||||
"ApiResponse",
|
||||
"LoginRequest",
|
||||
"RegisterRequest",
|
||||
"TokenResponse",
|
||||
"UserPublic",
|
||||
]
|
||||
45
app/schemas/auth.py
Normal file
45
app/schemas/auth.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
username: str = Field(min_length=1, max_length=64)
|
||||
password: str = Field(min_length=6, max_length=128)
|
||||
confirm_password: str = Field(min_length=6, max_length=128, alias="confirmPassword")
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def strip_username(cls, value: str) -> str:
|
||||
return value.strip()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def passwords_match(self) -> "RegisterRequest":
|
||||
if self.password != self.confirm_password:
|
||||
raise ValueError("两次输入的密码不一致")
|
||||
return self
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str = Field(min_length=1, max_length=64)
|
||||
password: str = Field(min_length=1, max_length=128)
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def strip_username(cls, value: str) -> str:
|
||||
return value.strip()
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
username: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
user: UserPublic
|
||||
15
app/schemas/common.py
Normal file
15
app/schemas/common.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class ApiResponse(BaseModel, Generic[T]):
|
||||
"""与 aiclient 前端约定的统一响应结构。"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
ok: bool
|
||||
message: str = ""
|
||||
data: T | None = None
|
||||
0
app/services/__init__.py
Normal file
0
app/services/__init__.py
Normal file
79
app/services/auth.py
Normal file
79
app/services/auth.py
Normal file
@@ -0,0 +1,79 @@
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import get_settings
|
||||
from app.core.security import (
|
||||
create_access_token,
|
||||
hash_password,
|
||||
session_redis_key,
|
||||
verify_password,
|
||||
)
|
||||
from app.models.user import User
|
||||
from app.schemas.auth import TokenResponse, UserPublic
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
class AuthError(Exception):
|
||||
def __init__(self, message: str) -> None:
|
||||
self.message = message
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
async def register_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
password: str,
|
||||
) -> TokenResponse:
|
||||
existing = await db.scalar(select(User).where(User.username == username))
|
||||
if existing is not None:
|
||||
raise AuthError("用户名已存在")
|
||||
|
||||
user = User(username=username, password_hash=hash_password(password))
|
||||
db.add(user)
|
||||
await db.flush()
|
||||
await db.refresh(user)
|
||||
|
||||
token = create_access_token(str(user.id))
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
user=UserPublic.model_validate(user),
|
||||
)
|
||||
|
||||
|
||||
async def login_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
password: str,
|
||||
) -> TokenResponse:
|
||||
user = await db.scalar(select(User).where(User.username == username))
|
||||
if user is None or not verify_password(password, user.password_hash):
|
||||
raise AuthError("用户名或密码错误")
|
||||
|
||||
token = create_access_token(str(user.id))
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
user=UserPublic.model_validate(user),
|
||||
)
|
||||
|
||||
|
||||
async def store_session(redis_client, token: str, user_id: int) -> None:
|
||||
ttl = settings.access_token_expire_minutes * 60
|
||||
await redis_client.setex(session_redis_key(token), ttl, str(user_id))
|
||||
|
||||
|
||||
async def revoke_session(redis_client, token: str) -> None:
|
||||
await redis_client.delete(session_redis_key(token))
|
||||
|
||||
|
||||
async def session_user_id(redis_client, token: str) -> int | None:
|
||||
raw = await redis_client.get(session_redis_key(token))
|
||||
if raw is None:
|
||||
return None
|
||||
return int(raw)
|
||||
|
||||
|
||||
async def get_user_by_id(db: AsyncSession, user_id: int) -> User | None:
|
||||
return await db.get(User, user_id)
|
||||
Reference in New Issue
Block a user