feat: 用户账户系统

This commit is contained in:
Junyan Qin
2024-11-17 19:11:44 +08:00
parent 036c2182a5
commit 20e3edba8f
23 changed files with 543 additions and 102 deletions

View File

@@ -2,6 +2,7 @@ from __future__ import annotations
import abc
import typing
import enum
import quart
from quart.typing import RouteCallable
@@ -23,6 +24,12 @@ def group_class(name: str, path: str) -> None:
return decorator
class AuthType(enum.Enum):
"""认证类型"""
NONE = 'none'
USER_TOKEN = 'user-token'
class RouterGroup(abc.ABC):
name: str
@@ -41,13 +48,30 @@ class RouterGroup(abc.ABC):
async def initialize(self) -> None:
pass
def route(self, rule: str, **options: typing.Any) -> typing.Callable[[RouteCallable], RouteCallable]: # decorator
def route(self, rule: str, auth_type: AuthType = AuthType.USER_TOKEN, **options: typing.Any) -> typing.Callable[[RouteCallable], RouteCallable]: # decorator
"""注册一个路由"""
def decorator(f: RouteCallable) -> RouteCallable:
nonlocal rule
rule = self.path + rule
async def handler_error(*args, **kwargs):
if auth_type == AuthType.USER_TOKEN:
# 从Authorization头中获取token
token = quart.request.headers.get('Authorization', '').replace('Bearer ', '')
if not token:
return self.http_status(401, -1, '未提供有效的用户令牌')
try:
user_email = await self.ap.user_service.verify_jwt_token(token)
# 检查f是否接受user_email参数
if 'user_email' in f.__code__.co_varnames:
kwargs['user_email'] = user_email
except Exception as e:
return self.http_status(401, -1, str(e))
try:
return await f(*args, **kwargs)
except Exception as e: # 自动 500
@@ -61,25 +85,22 @@ class RouterGroup(abc.ABC):
return f
return decorator
def _cors(self, response: quart.Response) -> quart.Response:
return response
def success(self, data: typing.Any = None) -> quart.Response:
"""返回一个 200 响应"""
return self._cors(quart.jsonify({
return quart.jsonify({
'code': 0,
'msg': 'ok',
'data': data,
}))
})
def fail(self, code: int, msg: str) -> quart.Response:
"""返回一个异常响应"""
return self._cors(quart.jsonify({
return quart.jsonify({
'code': code,
'msg': msg,
}))
})
def http_status(self, status: int, code: int, msg: str) -> quart.Response:
"""返回一个指定状态码的响应"""