登录过期

This commit is contained in:
wuaho 2021-09-26 11:05:18 +08:00
parent f8c48df43b
commit 55277e5389
3 changed files with 12 additions and 9 deletions

View File

@ -31,6 +31,7 @@ async def login(
# raise HTTPException(status_code=400, detail="Incorrect name or password") # raise HTTPException(status_code=400, detail="Incorrect name or password")
return schemas.Msg(code=-1, msg='密码或用户名错误') return schemas.Msg(code=-1, msg='密码或用户名错误')
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) 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) await crud.user.update_login_time(db, data.username)
return { return {
@ -40,7 +41,6 @@ async def login(
'email': user.email, 'email': user.email,
'tel': user.tel, 'tel': user.tel,
'token': security.create_access_token( 'token': security.create_access_token(
expires_delta=access_token_expires, _id=str(user.id), email=user.email, expires_delta=access_token_expires, _id=str(user.id), email=user.email,
nickname=user.nickname, nickname=user.nickname,

View File

@ -3,6 +3,7 @@ from fastapi.security import OAuth2PasswordBearer
from jose import jwt from jose import jwt
from motor.motor_asyncio import AsyncIOMotorDatabase from motor.motor_asyncio import AsyncIOMotorDatabase
from pydantic import ValidationError from pydantic import ValidationError
from starlette.authentication import AuthenticationError
import crud import crud
import schemas import schemas
@ -43,10 +44,7 @@ def get_current_user2(token: str) -> schemas.UserDB:
) )
user = schemas.UserDB(**payload) user = schemas.UserDB(**payload)
except (jwt.JWTError, ValidationError): except (jwt.JWTError, ValidationError):
raise HTTPException( raise AuthenticationError()
status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials",
)
if not user: if not user:
raise HTTPException(status_code=404, detail="User not found") raise HTTPException(status_code=404, detail="User not found")
return user return user

11
main.py
View File

@ -7,7 +7,8 @@ from fastapi.exceptions import RequestValidationError
from starlette.middleware.cors import CORSMiddleware from starlette.middleware.cors import CORSMiddleware
from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, BaseUser, SimpleUser from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, BaseUser, SimpleUser
from starlette.middleware.authentication import AuthenticationMiddleware 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 crud
import schemas import schemas
@ -63,13 +64,17 @@ class BasicAuth(AuthenticationBackend):
try: try:
user = get_current_user2(auth.split(' ')[1]) user = get_current_user2(auth.split(' ')[1])
except (ValueError, UnicodeDecodeError, binascii.Error): except (ValueError, UnicodeDecodeError, binascii.Error):
raise AuthenticationError("Invalid basic auth credentials") raise AuthenticationError("身份验证失败,请重新登录")
return AuthCredentials(["authenticated"]), CurrentUser(user.name, user.id) 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(CasbinMiddleware, enforcer=casbin_enforcer)
app.add_middleware(AuthenticationMiddleware, backend=BasicAuth()) app.add_middleware(AuthenticationMiddleware, backend=BasicAuth(), on_error=login_expired)
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,