Skip to content

Commit

Permalink
Fix cookie expiration time zone (#408)
Browse files Browse the repository at this point in the history
* Fix cookie expiration time zone

* Fix the loss of cross-domain cookies
  • Loading branch information
wu-clan authored Sep 8, 2024
1 parent 4f5c5c2 commit 1d956ca
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 20 deletions.
18 changes: 10 additions & 8 deletions backend/app/admin/service/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,11 @@ async def login(
await redis_client.delete(f'{admin_settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{request.state.ip}')
await user_dao.update_login_time(db, obj.username)
response.set_cookie(
settings.COOKIE_REFRESH_TOKEN_KEY,
refresh_token.refresh_token,
settings.COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS,
refresh_token.refresh_token_expire_time,
key=settings.COOKIE_REFRESH_TOKEN_KEY,
value=refresh_token.refresh_token,
max_age=settings.COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS,
expires=timezone.f_utc(refresh_token.refresh_token_expire_time),
httponly=True,
)
await db.refresh(current_user)
data = GetLoginToken(
Expand Down Expand Up @@ -137,10 +138,11 @@ async def new_token(*, request: Request, response: Response) -> GetNewToken:
multi_login=current_user.is_multi_login,
)
response.set_cookie(
settings.COOKIE_REFRESH_TOKEN_KEY,
new_token.new_refresh_token,
settings.COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS,
new_token.new_refresh_token_expire_time,
key=settings.COOKIE_REFRESH_TOKEN_KEY,
value=new_token.new_refresh_token,
max_age=settings.COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS,
expires=timezone.f_utc(new_token.new_refresh_token_expire_time),
httponly=True,
)
data = GetNewToken(
access_token=new_token.new_access_token,
Expand Down
9 changes: 5 additions & 4 deletions backend/app/admin/service/oauth2_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,11 @@ async def create_with_login(
background_tasks.add_task(LoginLogService.create, **login_log)
await redis_client.delete(f'{admin_settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{request.state.ip}')
response.set_cookie(
settings.COOKIE_REFRESH_TOKEN_KEY,
refresh_token.refresh_token,
settings.COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS,
refresh_token.refresh_token_expire_time,
key=settings.COOKIE_REFRESH_TOKEN_KEY,
value=refresh_token.refresh_token,
max_age=settings.COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS,
expires=timezone.f_utc(refresh_token.refresh_token_expire_time),
httponly=True,
)
data = GetLoginToken(
access_token=access_token.access_token,
Expand Down
7 changes: 4 additions & 3 deletions backend/common/exception/exception_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,12 @@ async def all_exception_handler(request: Request, exc: Exception):
if settings.MIDDLEWARE_CORS:

@app.exception_handler(StandardResponseCode.HTTP_500)
async def cors_status_code_500_exception_handler(request, exc):
async def cors_custom_code_500_exception_handler(request, exc):
"""
跨域 500 异常处理
跨域自定义 500 异常处理
`Related issue <https://github.com/encode/starlette/issues/1175>`_
`Solution <https://github.com/fastapi/fastapi/discussions/7847#discussioncomment-5144709>`_
:param request:
:param exc:
Expand Down Expand Up @@ -244,7 +245,7 @@ async def cors_status_code_500_exception_handler(request, exc):
if origin:
cors = CORSMiddleware(
app=app,
allow_origins=['*'],
allow_origins=settings.CORS_ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
Expand Down
7 changes: 6 additions & 1 deletion backend/core/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def validate_openapi_url(cls, values):
TOKEN_EXPIRE_SECONDS: int = 60 * 60 * 24 * 1 # 过期时间,单位:秒
TOKEN_REFRESH_EXPIRE_SECONDS: int = 60 * 60 * 24 * 7 # refresh token 过期时间,单位:秒
TOKEN_REDIS_PREFIX: str = 'fba:token'
TOKEN_REFRESH_REDIS_PREFIX: str = 'fba:token:refresh'
TOKEN_REFRESH_REDIS_PREFIX: str = 'fba:refresh_token'
TOKEN_EXCLUDE: list[str] = [ # JWT / RBAC 白名单
f'{API_V1_STR}/auth/login',
]
Expand All @@ -109,6 +109,11 @@ def validate_openapi_url(cls, values):
MIDDLEWARE_CORS: bool = True
MIDDLEWARE_ACCESS: bool = True

# CORS
CORS_ALLOWED_ORIGINS: list[str] = [
'http://localhost:5173/', # 前端地址
]

# RBAC Permission
PERMISSION_MODE: Literal['casbin', 'role-menu'] = 'casbin'
PERMISSION_REDIS_PREFIX: str = 'fba:permission'
Expand Down
6 changes: 3 additions & 3 deletions backend/core/registrar.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ def register_middleware(app: FastAPI):
:param app:
:return:
"""
# Opera log
# Opera log (required)
app.add_middleware(OperaLogMiddleware)
# JWT auth, required
# JWT auth (required)
app.add_middleware(
AuthenticationMiddleware, backend=JwtAuthMiddleware(), on_error=JwtAuthMiddleware.auth_exception_handler
)
Expand All @@ -129,7 +129,7 @@ def register_middleware(app: FastAPI):

app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_origins=settings.CORS_ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
Expand Down
1 change: 0 additions & 1 deletion backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ dependencies = [
"pytest==7.2.2",
"pytest-pretty==1.2.0",
"python-jose==3.3.0",
"pytz==2023.3",
"redis[hiredis]==5.0.1",
"SQLAlchemy==2.0.30",
"user-agents==2.2.0",
Expand Down
11 changes: 11 additions & 0 deletions backend/utils/timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import zoneinfo

from datetime import datetime
from datetime import timezone as datetime_timezone

from backend.core.conf import settings

Expand Down Expand Up @@ -38,5 +39,15 @@ def f_str(self, date_str: str, format_str: str = settings.DATETIME_FORMAT) -> da
"""
return datetime.strptime(date_str, format_str).replace(tzinfo=self.tz_info)

@staticmethod
def f_utc(dt: datetime) -> datetime:
"""
时区时间转 UTC(GMT)时区
:param dt:
:return:
"""
return dt.astimezone(datetime_timezone.utc)


timezone = TimeZone()

0 comments on commit 1d956ca

Please sign in to comment.