登录过期
This commit is contained in:
parent
f8c48df43b
commit
55277e5389
@ -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,
|
||||
|
@ -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
|
||||
|
11
main.py
11
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,
|
||||
|
Loading…
Reference in New Issue
Block a user