Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix logging when a login error occurs #386

Merged
merged 1 commit into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 30 additions & 21 deletions backend/app/admin/service/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ async def login(*, request: Request, obj: AuthLoginParam, background_tasks: Back
current_user = await user_dao.get_by_username(db, obj.username)
if not current_user:
raise errors.NotFoundError(msg='用户名或密码有误')
elif not password_verify(obj.password + current_user.salt, current_user.password):
user_uuid = current_user.uuid
username = current_user.username
if not password_verify(obj.password + current_user.salt, current_user.password):
raise errors.AuthorizationError(msg='用户名或密码有误')
elif not current_user.status:
raise errors.AuthorizationError(msg='用户已被锁定, 请联系统管理员')
Expand All @@ -58,42 +60,49 @@ async def login(*, request: Request, obj: AuthLoginParam, background_tasks: Back
raise errors.AuthorizationError(msg='验证码失效,请重新获取')
if captcha_code.lower() != obj.captcha.lower():
raise errors.CustomError(error=CustomErrorCode.CAPTCHA_ERROR)
current_user_id = current_user.id
access_token, access_token_expire_time = await create_access_token(
str(current_user.id), multi_login=current_user.is_multi_login
str(current_user_id), multi_login=current_user.is_multi_login
)
refresh_token, refresh_token_expire_time = await create_refresh_token(
sub=str(current_user.id),
sub=str(current_user_id),
expire_time=access_token_expire_time,
multi_login=current_user.is_multi_login,
)
await user_dao.update_login_time(db, obj.username)
await db.refresh(current_user)
except errors.NotFoundError as e:
raise errors.NotFoundError(msg=e.msg)
except (errors.AuthorizationError, errors.CustomError) as e:
err_log_info = dict(
db=db,
request=request,
user=current_user,
login_time=timezone.now(),
status=LoginLogStatusType.fail.value,
msg=e.msg,
task = BackgroundTask(
LoginLogService.create,
**dict(
db=db,
request=request,
user_uuid=user_uuid,
username=username,
login_time=timezone.now(),
status=LoginLogStatusType.fail.value,
msg=e.msg,
),
)
task = BackgroundTask(LoginLogService.create, **err_log_info)
raise errors.AuthorizationError(msg=e.msg, background=task)
except Exception as e:
raise e
else:
login_log = dict(
db=db,
request=request,
user=current_user,
login_time=timezone.now(),
status=LoginLogStatusType.success.value,
msg='登录成功',
background_tasks.add_task(
LoginLogService.create,
**dict(
db=db,
request=request,
user_uuid=user_uuid,
username=username,
login_time=timezone.now(),
status=LoginLogStatusType.success.value,
msg='登录成功',
),
)
background_tasks.add_task(LoginLogService.create, **login_log)
await redis_client.delete(f'{admin_settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{request.state.ip}')
await user_dao.update_login_time(db, obj.username)
await db.refresh(current_user)
data = GetLoginToken(
access_token=access_token,
refresh_token=refresh_token,
Expand Down
14 changes: 10 additions & 4 deletions backend/app/admin/service/login_log_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from sqlalchemy.ext.asyncio import AsyncSession

from backend.app.admin.crud.crud_login_log import login_log_dao
from backend.app.admin.model import User
from backend.app.admin.schema.login_log import CreateLoginLogParam
from backend.common.log import log
from backend.database.db_mysql import async_db_session
Expand All @@ -20,13 +19,20 @@ async def get_select(*, username: str, status: int, ip: str) -> Select:

@staticmethod
async def create(
*, db: AsyncSession, request: Request, user: User, login_time: datetime, status: int, msg: str
*,
db: AsyncSession,
request: Request,
user_uuid: str,
username: str,
login_time: datetime,
status: int,
msg: str,
) -> None:
try:
# request.state 来自 opera log 中间件定义的扩展参数,详见 opera_log_middleware.py
obj_in = CreateLoginLogParam(
user_uuid=user.uuid,
username=user.username,
user_uuid=user_uuid,
username=username,
status=status,
ip=request.state.ip,
country=request.state.country,
Expand Down