diff --git a/api/api_v1/endpoints/user.py b/api/api_v1/endpoints/user.py index f8df01e..b38b2f5 100644 --- a/api/api_v1/endpoints/user.py +++ b/api/api_v1/endpoints/user.py @@ -31,6 +31,7 @@ async def login( # raise HTTPException(status_code=400, detail="Incorrect name or password") return schemas.Msg(code=-1, msg='密码或用户名错误') access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + # access_token_expires = timedelta(seconds=5) await crud.user.update_login_time(db, data.username) return { @@ -40,7 +41,6 @@ async def login( 'email': user.email, 'tel': user.tel, - 'token': security.create_access_token( expires_delta=access_token_expires, _id=str(user.id), email=user.email, nickname=user.nickname, @@ -53,7 +53,7 @@ async def login( 'access_token': security.create_access_token( expires_delta=access_token_expires, _id=str(user.id), email=user.email, nickname=user.nickname, - is_superuser=user.is_superuser, name=user.name,data_where= user.data_where + is_superuser=user.is_superuser, name=user.name, data_where=user.data_where ), "token_type": "bearer", diff --git a/api/deps.py b/api/deps.py index 690b03a..560cbc2 100644 --- a/api/deps.py +++ b/api/deps.py @@ -3,6 +3,7 @@ from fastapi.security import OAuth2PasswordBearer from jose import jwt from motor.motor_asyncio import AsyncIOMotorDatabase from pydantic import ValidationError +from starlette.authentication import AuthenticationError import crud import schemas @@ -43,10 +44,7 @@ def get_current_user2(token: str) -> schemas.UserDB: ) user = schemas.UserDB(**payload) except (jwt.JWTError, ValidationError): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Could not validate credentials", - ) + raise AuthenticationError() if not user: raise HTTPException(status_code=404, detail="User not found") return user diff --git a/main.py b/main.py index 6270829..741224b 100644 --- a/main.py +++ b/main.py @@ -7,7 +7,8 @@ from fastapi.exceptions import RequestValidationError from starlette.middleware.cors import CORSMiddleware from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, BaseUser, SimpleUser from starlette.middleware.authentication import AuthenticationMiddleware -from starlette.responses import Response +from starlette.requests import HTTPConnection +from starlette.responses import Response, JSONResponse import crud import schemas @@ -63,13 +64,17 @@ class BasicAuth(AuthenticationBackend): try: user = get_current_user2(auth.split(' ')[1]) except (ValueError, UnicodeDecodeError, binascii.Error): - raise AuthenticationError("Invalid basic auth credentials") + raise AuthenticationError("身份验证失败,请重新登录") return AuthCredentials(["authenticated"]), CurrentUser(user.name, user.id) +def login_expired(conn: HTTPConnection, exc: Exception) -> Response: + return JSONResponse(schemas.Msg(code=-5, msg='请重新登录').dict(), status_code=200) + + app.add_middleware(CasbinMiddleware, enforcer=casbin_enforcer) -app.add_middleware(AuthenticationMiddleware, backend=BasicAuth()) +app.add_middleware(AuthenticationMiddleware, backend=BasicAuth(), on_error=login_expired) app.add_middleware( CORSMiddleware,