From 1a3a03dd6f44fe6b06bb4302a935f6271745773b Mon Sep 17 00:00:00 2001 From: Yuerchu Date: Tue, 15 Jul 2025 11:23:03 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=BC=BAJWT=E4=BB=A4=E7=89=8C?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JWT.py | 3 ++- frontend/index.html | 4 ++-- frontend/src/views/Admin.vue | 14 -------------- routes/admin.py | 19 ++++++++++++++++++- routes/session.py | 2 +- 5 files changed, 23 insertions(+), 19 deletions(-) diff --git a/JWT.py b/JWT.py index f0e57da..1a343f5 100644 --- a/JWT.py +++ b/JWT.py @@ -8,4 +8,5 @@ oauth2_scheme = OAuth2PasswordBearer( tokenUrl="/api/token" ) -SECRET_KEY = asyncio.run(database.Database().get_setting('SECRET_KEY')) \ No newline at end of file +SECRET_KEY = asyncio.run(database.Database().get_setting('SECRET_KEY')) +ALGORITHM = "HS256" \ No newline at end of file diff --git a/frontend/index.html b/frontend/index.html index 0a84a1c..275da93 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -1,10 +1,10 @@ - + - Welcome to Vuetify 3 + Findreve
diff --git a/frontend/src/views/Admin.vue b/frontend/src/views/Admin.vue index 5d372fb..f4031a5 100644 --- a/frontend/src/views/Admin.vue +++ b/frontend/src/views/Admin.vue @@ -43,17 +43,9 @@ - - @@ -215,12 +207,6 @@ - - -
-

生成二维码

-

此功能正在开发中...

-

用户设置

diff --git a/routes/admin.py b/routes/admin.py index 9bf006e..9b2b795 100644 --- a/routes/admin.py +++ b/routes/admin.py @@ -3,6 +3,8 @@ from typing import Annotated, Literal, Optional from fastapi import Depends, Query from fastapi import HTTPException import JWT +import jwt +from jwt import InvalidTokenError from model import database from model.response import DefaultResponse from model.items import Item @@ -15,7 +17,22 @@ async def is_admin(token: Annotated[str, Depends(JWT.oauth2_scheme)]) -> Literal 使用方法: >>> APIRouter(dependencies=[Depends(is_admin)]) ''' - return True + credentials_exception = HTTPException( + status_code=401, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + try: + payload = jwt.decode(token, JWT.SECRET_KEY, algorithms=[JWT.ALGORITHM]) + username = payload.get("sub") + if username is None or not await database.Database().get_setting('account') == username: + raise credentials_exception + else: + return True + except InvalidTokenError: + raise credentials_exception + Router = APIRouter( prefix='/api/admin', diff --git a/routes/session.py b/routes/session.py index 7cb52d2..eb6e748 100644 --- a/routes/session.py +++ b/routes/session.py @@ -48,7 +48,7 @@ async def login_for_access_token( user = await authenticate_user(form_data.username, form_data.password) if not user: raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, + status_code=401, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, )