| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750 |
- import json
- import uuid
- from datetime import datetime, timedelta
- from typing import NewType
- from fastapi import Request
- from redis.asyncio.client import Redis
- from sqlalchemy.ext.asyncio import AsyncSession
- from user_agents import parse
- from app.api.v1.module_monitor.online.schema import OnlineOutSchema
- from app.api.v1.module_system.user.crud import UserCRUD
- from app.api.v1.module_system.user.model import UserModel
- from app.common.enums import RedisInitKeyConfig
- from app.config.setting import settings
- from app.core.exceptions import CustomException
- from app.core.logger import log
- from app.core.redis_crud import RedisCURD
- from app.core.security import (
- CustomOAuth2PasswordRequestForm,
- create_access_token,
- decode_access_token,
- )
- from app.utils.captcha_util import CaptchaUtil
- from app.utils.common_util import get_random_character, generate_random_code
- from app.utils.hash_bcrpy_util import PwdUtil
- from app.utils.ip_local_util import IpLocalUtil
- from app.utils.sms_util import SendSmsRequest, SmsTemplateEnum, SmsSender
- from .schema import (
- AuthSchema,
- AutoLoginTokenSchema,
- AutoLoginUserSchema,
- CaptchaOutSchema,
- JWTOutSchema,
- JWTPayloadSchema,
- LoginMiniRequestSchema,
- LogoutPayloadSchema,
- RefreshTokenPayloadSchema,
- SmsCodeSchema,
- SmsLoginRequestSchema,
- )
- CaptchaKey = NewType("CaptchaKey", str)
- CaptchaBase64 = NewType("CaptchaBase64", str)
- class LoginService:
- """登录认证服务"""
- @classmethod
- async def authenticate_mini_user_service(
- cls,
- request: Request,
- redis: Redis,
- login_form: LoginMiniRequestSchema,
- db: AsyncSession,
- ) -> JWTOutSchema:
-
- # 小程序用户认证
- auth = AuthSchema(db=db)
- user = await UserCRUD(auth).get_by_username_crud(username=login_form.username)
- if not user:
- raise CustomException(msg="用户不存在")
- if not PwdUtil.verify_password(
- plain_password=login_form.password, password_hash=user.password
- ):
- raise CustomException(msg="账号或密码错误")
- if user.status == "1":
- raise CustomException(msg="用户已被停用")
- # 更新最后登录时间
- user = await UserCRUD(auth).update_last_login_crud(id=user.id)
- if not user:
- raise CustomException(msg="用户不存在")
- if not login_form.login_type:
- raise CustomException(msg="登录类型不能为空")
- # 创建token
- token = await cls.create_token_service(
- request=request,
- redis=redis,
- user=user,
- login_type=login_form.login_type,
- )
- return token
-
- @classmethod
- async def authenticate_user_service(
- cls,
- request: Request,
- redis: Redis,
- login_form: CustomOAuth2PasswordRequestForm,
- db: AsyncSession,
- ) -> JWTOutSchema:
- """
- 用户认证
- 参数:
- - request (Request): FastAPI请求对象
- - login_form (CustomOAuth2PasswordRequestForm): 登录表单数据
- - db (AsyncSession): 数据库会话对象
- 返回:
- - JWTOutSchema: 包含访问令牌和刷新令牌的响应模型
- 异常:
- - CustomException: 认证失败时抛出异常。
- """
- # 判断是否来自API文档
- referer = request.headers.get("referer", "")
- request_from_docs = referer.endswith(("docs", "redoc"))
- # 验证码校验
- if settings.CAPTCHA_ENABLE and not request_from_docs:
- if not login_form.captcha_key or not login_form.captcha:
- raise CustomException(msg="验证码不能为空")
- await CaptchaService.check_captcha_service(
- redis=redis,
- key=login_form.captcha_key,
- captcha=login_form.captcha,
- )
- # 用户认证
- auth = AuthSchema(db=db)
- user = await UserCRUD(auth).get_by_username_crud(username=login_form.username)
- if not user:
- raise CustomException(msg="用户不存在")
- if not PwdUtil.verify_password(
- plain_password=login_form.password, password_hash=user.password
- ):
- raise CustomException(msg="账号或密码错误")
- if user.status == "1":
- raise CustomException(msg="用户已被停用")
- # 更新最后登录时间
- user = await UserCRUD(auth).update_last_login_crud(id=user.id)
- if not user:
- raise CustomException(msg="用户不存在")
- if not login_form.login_type:
- raise CustomException(msg="登录类型不能为空")
- # 创建token
- token = await cls.create_token_service(
- request=request,
- redis=redis,
- user=user,
- login_type=login_form.login_type,
- )
- return token
- @classmethod
- async def authenticate_sms_user_service(
- cls,
- request: Request,
- redis: Redis,
- login_form: SmsLoginRequestSchema,
- db: AsyncSession,
- ) -> JWTOutSchema:
- """
- 短信验证码登录
- 参数:
- - request (Request): FastAPI请求对象
- - redis (Redis): Redis客户端对象
- - login_form (SmsLoginRequestSchema): 短信登录表单数据
- - db (AsyncSession): 数据库会话对象
- 返回:
- - JWTOutSchema: 包含访问令牌和刷新令牌的响应模型
- 异常:
- - CustomException: 认证失败时抛出异常。
- """
- mobile = login_form.mobile
- code = login_form.code
- # 验证验证码
- # verify_result = await SmsCodeService.verify_sms_code_service(login_form, redis)
- # if not verify_result:
- # raise CustomException(msg="验证码已过期或错误")
- pass # 测试阶段跳过短信验证码校验
- # 根据手机号查找用户
- from app.api.v1.module_system.user.model import UserModel
- from sqlalchemy import select
- stmt = select(UserModel).where(UserModel.mobile == mobile)
- result = await db.execute(stmt)
- user = result.scalar_one_or_none()
- if not user:
- log.error(f"短信登录-未找到用户: mobile={mobile}")
- raise CustomException(msg="用户不存在")
- log.info(f"短信登录-找到用户: id={user.id}, mobile={user.mobile}, status={user.status}")
- if user.status == "1":
- raise CustomException(msg="用户已被停用")
- # 检查员工签约:无员工记录放行;有记录需已签约
- from app.plugin.module_payment.employee.model import EmployeeModel
- emp_stmt = select(EmployeeModel).where(EmployeeModel.user_id == user.id)
- emp_result = await db.execute(emp_stmt)
- employee = emp_result.scalar_one_or_none()
- if employee and employee.status != "EMPLOYEE_ACTIVATED":
- raise CustomException(msg="用户不存在")
- # 更新最后登录时间(记录日志即可,不阻塞登录)
- from datetime import datetime
- from sqlalchemy import update as sa_update
- try:
- await db.execute(
- sa_update(UserModel).where(UserModel.id == user.id).values(last_login=datetime.now())
- )
- except Exception as e:
- log.warning(f"短信登录-更新最后登录时间失败: {e}")
- # 创建token
- token = await cls.create_token_service(
- request=request,
- redis=redis,
- user=user,
- login_type="sms",
- )
- return token
- @classmethod
- async def create_token_service(
- cls, request: Request, redis: Redis, user: UserModel, login_type: str
- ) -> JWTOutSchema:
- """
- 创建访问令牌和刷新令牌
- 参数:
- - request (Request): FastAPI请求对象
- - redis (Redis): Redis客户端对象
- - user (UserModel): 用户模型对象
- - login_type (str): 登录类型
- 返回:
- - JWTOutSchema: 包含访问令牌和刷新令牌的响应模型
- 异常:
- - CustomException: 创建令牌失败时抛出异常。
- """
- # 生成会话编号
- session_id = str(uuid.uuid4())
- request.scope["session_id"] = session_id
- user_agent = parse(request.headers.get("user-agent"))
- request_ip = None
- x_forwarded_for = request.headers.get("X-Forwarded-For")
- if x_forwarded_for:
- # 取第一个 IP 地址,通常为客户端真实 IP
- request_ip = x_forwarded_for.split(",")[0].strip()
- else:
- # 若没有 X-Forwarded-For 头,则使用 request.client.host
- request_ip = request.client.host if request.client else "127.0.0.1"
- login_location = await IpLocalUtil.resolve_location_for_log(request_ip)
- request.scope["login_location"] = login_location
- # 确保在请求上下文中设置用户名和会话ID
- request.scope["user_username"] = user.username
- access_expires = timedelta(seconds=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
- refresh_expires = timedelta(seconds=settings.REFRESH_TOKEN_EXPIRE_MINUTES)
- now = datetime.now()
- # 记录租户信息到日志
- log.info(f"用户ID: {user.id}, 用户名: {user.username} 正在生成JWT令牌")
- # 生成会话信息
- session_info = OnlineOutSchema(
- session_id=session_id,
- user_id=user.id,
- name=user.name,
- user_name=user.username,
- ipaddr=request_ip,
- login_location=login_location,
- os=user_agent.os.family,
- browser=user_agent.browser.family,
- login_time=user.last_login,
- login_type=login_type,
- ).model_dump_json()
- access_token = create_access_token(
- payload=JWTPayloadSchema(
- sub=session_info,
- is_refresh=False,
- exp=now + access_expires,
- )
- )
- refresh_token = create_access_token(
- payload=JWTPayloadSchema(
- sub=session_info,
- is_refresh=True,
- exp=now + refresh_expires,
- )
- )
- # 设置新的token
- await RedisCURD(redis).set(
- key=f"{RedisInitKeyConfig.ACCESS_TOKEN.key}:{session_id}",
- value=access_token,
- expire=int(access_expires.total_seconds()),
- )
- await RedisCURD(redis).set(
- key=f"{RedisInitKeyConfig.REFRESH_TOKEN.key}:{session_id}",
- value=refresh_token,
- expire=int(refresh_expires.total_seconds()),
- )
- return JWTOutSchema(
- access_token=access_token,
- refresh_token=refresh_token,
- expires_in=int(access_expires.total_seconds()),
- token_type=settings.TOKEN_TYPE,
- )
- @classmethod
- async def refresh_token_service(
- cls,
- db: AsyncSession,
- redis: Redis,
- request: Request,
- refresh_token: RefreshTokenPayloadSchema,
- ) -> JWTOutSchema:
- """
- 刷新访问令牌
- 参数:
- - db (AsyncSession): 数据库会话对象
- - redis (Redis): Redis客户端对象
- - request (Request): FastAPI请求对象
- - refresh_token (RefreshTokenPayloadSchema): 刷新令牌数据
- 返回:
- - JWTOutSchema: 新的令牌对象
- 异常:
- - CustomException: 刷新令牌无效时抛出异常
- """
- token_payload: JWTPayloadSchema = decode_access_token(token=refresh_token.refresh_token)
- if not token_payload.is_refresh:
- raise CustomException(msg="非法凭证,请传入刷新令牌")
- # 去 Redis 查完整信息
- session_info = json.loads(token_payload.sub)
- session_id = session_info.get("session_id")
- user_id = session_info.get("user_id")
- if not session_id or not user_id:
- raise CustomException(msg="非法凭证,无法获取会话编号或用户ID")
- # 用户认证
- auth = AuthSchema(db=db)
- user = await UserCRUD(auth).get_by_id_crud(id=user_id)
- if not user:
- raise CustomException(msg="刷新token失败,用户不存在")
- # 记录刷新令牌时的租户信息
- log.info(f"用户ID: {user.id}, 用户名: {user.username} 正在刷新JWT令牌")
- # 设置新的 token
- access_expires = timedelta(seconds=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
- refresh_expires = timedelta(seconds=settings.REFRESH_TOKEN_EXPIRE_MINUTES)
- now = datetime.now()
- session_info_json = json.dumps(session_info)
- access_token = create_access_token(
- payload=JWTPayloadSchema(
- sub=session_info_json,
- is_refresh=False,
- exp=now + access_expires,
- )
- )
- refresh_token_new = create_access_token(
- payload=JWTPayloadSchema(
- sub=session_info_json,
- is_refresh=True,
- exp=now + refresh_expires,
- )
- )
- # 覆盖写入 Redis
- await RedisCURD(redis).set(
- key=f"{RedisInitKeyConfig.ACCESS_TOKEN.key}:{session_id}",
- value=access_token,
- expire=int(access_expires.total_seconds()),
- )
- await RedisCURD(redis).set(
- key=f"{RedisInitKeyConfig.REFRESH_TOKEN.key}:{session_id}",
- value=refresh_token_new,
- expire=int(refresh_expires.total_seconds()),
- )
- return JWTOutSchema(
- access_token=access_token,
- refresh_token=refresh_token_new,
- token_type=settings.TOKEN_TYPE,
- expires_in=int(access_expires.total_seconds()),
- )
- @classmethod
- async def logout_service(cls, redis: Redis, token: LogoutPayloadSchema) -> bool:
- """
- 退出登录
- 参数:
- - redis (Redis): Redis客户端对象
- - token (LogoutPayloadSchema): 退出登录令牌数据
- 返回:
- - bool: 退出成功返回True
- 异常:
- - CustomException: 令牌无效时抛出异常
- """
- payload: JWTPayloadSchema = decode_access_token(token=token.token)
- session_info = json.loads(payload.sub)
- session_id = session_info.get("session_id")
- if not session_id:
- raise CustomException(msg="非法凭证,无法获取会话编号")
- # 删除Redis中的在线用户、访问令牌、刷新令牌
- await RedisCURD(redis).delete(f"{RedisInitKeyConfig.ACCESS_TOKEN.key}:{session_id}")
- await RedisCURD(redis).delete(f"{RedisInitKeyConfig.REFRESH_TOKEN.key}:{session_id}")
- log.info(f"用户退出登录成功,会话编号:{session_id}")
- return True
- class CaptchaService:
- """验证码服务"""
- @classmethod
- async def get_captcha_service(cls, redis: Redis) -> dict[str, CaptchaKey | CaptchaBase64]:
- """
- 获取验证码
- 参数:
- - redis (Redis): Redis客户端对象
- 返回:
- - dict[str, CaptchaKey | CaptchaBase64]: 包含验证码key和base64图片的字典
- 异常:
- - CustomException: 验证码服务未启用时抛出异常
- """
- if not settings.CAPTCHA_ENABLE:
- raise CustomException(msg="未开启验证码服务")
- # 生成验证码图片和值
- captcha_base64, captcha_value = CaptchaUtil.captcha_arithmetic()
- captcha_key = get_random_character()
- # 保存到Redis并设置过期时间
- redis_key = f"{RedisInitKeyConfig.CAPTCHA_CODES.key}:{captcha_key}"
- await RedisCURD(redis).set(
- key=redis_key,
- value=captcha_value,
- expire=settings.CAPTCHA_EXPIRE_SECONDS,
- )
- log.info(f"生成验证码成功,验证码:{captcha_value}")
- # 返回验证码信息
- return CaptchaOutSchema(
- enable=settings.CAPTCHA_ENABLE,
- key=CaptchaKey(captcha_key),
- img_base=CaptchaBase64(f"data:image/png;base64,{captcha_base64}"),
- ).model_dump()
- @classmethod
- async def check_captcha_service(cls, redis: Redis, key: str, captcha: str) -> bool:
- """
- 校验验证码
- 参数:
- - redis (Redis): Redis客户端对象
- - key (str): 验证码key
- - captcha (str): 用户输入的验证码
- 返回:
- - bool: 验证通过返回True
- 异常:
- - CustomException: 验证码无效或错误时抛出异常
- """
- if not captcha:
- raise CustomException(msg="验证码不能为空")
- # 获取Redis中存储的验证码
- redis_key = f"{RedisInitKeyConfig.CAPTCHA_CODES.key}:{key}"
- captcha_value = await RedisCURD(redis).get(redis_key)
- if not captcha_value:
- log.error("验证码已过期或不存在")
- raise CustomException(msg="验证码已过期")
- # 验证码不区分大小写比对
- if captcha.lower() != captcha_value.lower():
- log.error(f"验证码错误,用户输入:{captcha},正确值:{captcha_value}")
- raise CustomException(msg="验证码错误")
- # 验证成功后删除验证码,避免重复使用
- await RedisCURD(redis).delete(redis_key)
- log.info(f"验证码校验成功,key:{key}")
- return True
- class AutoLoginService:
- """免登录服务"""
- # 免登录Token前缀
- AUTO_LOGIN_PREFIX = "fastapiadmin:auto_login:"
- # Token有效期(秒) - 5分钟
- TOKEN_EXPIRE = 300
- @classmethod
- async def get_auto_login_users_service(cls, db: AsyncSession) -> list[AutoLoginUserSchema]:
- """
- 获取免登录用户列表
- 参数:
- - db (AsyncSession): 数据库会话对象
- 返回:
- - list[AutoLoginUserSchema]: 用户列表
- """
- from sqlalchemy import select
- from app.api.v1.module_system.user.model import UserModel
- # 查询所有启用的用户
- stmt = select(UserModel).where(UserModel.status == "0").order_by(UserModel.id)
- result = await db.execute(stmt)
- users = result.scalars().all()
- return [
- AutoLoginUserSchema(
- id=user.id,
- username=user.username,
- name=user.name,
- avatar=user.avatar,
- )
- for user in users
- ]
- @classmethod
- async def create_auto_login_token_service(
- cls, redis: Redis, db: AsyncSession, user_id: int
- ) -> AutoLoginTokenSchema:
- """
- 创建免登录Token
- 参数:
- - request (Request): FastAPI请求对象
- - redis (Redis): Redis客户端对象
- - db (AsyncSession): 数据库会话对象
- - user_id (int): 用户ID
- 返回:
- - AutoLoginTokenSchema: 免登录Token和用户信息
- 异常:
- - CustomException: 用户不存在或已停用时抛出异常
- """
- from sqlalchemy import select
- from app.api.v1.module_system.user.model import UserModel
- # 查询用户
- stmt = select(UserModel).where(UserModel.id == user_id)
- result = await db.execute(stmt)
- user = result.scalar_one_or_none()
- if not user:
- raise CustomException(msg="用户不存在")
- if user.status == "1":
- raise CustomException(msg="用户已被停用")
- # 生成免登录Token
- import uuid
- token = str(uuid.uuid4())
- token_key = f"{cls.AUTO_LOGIN_PREFIX}{token}"
- # 存储到Redis,设置5分钟过期
- token_data = {
- "user_id": user.id,
- "username": user.username,
- "created_at": datetime.now().isoformat(),
- }
- await RedisCURD(redis).set(
- key=token_key,
- value=json.dumps(token_data),
- expire=cls.TOKEN_EXPIRE,
- )
- log.info(f"创建免登录Token成功,用户:{user.username}")
- return AutoLoginTokenSchema(
- token=token,
- user=AutoLoginUserSchema(
- id=user.id,
- username=user.username,
- name=user.name,
- avatar=user.avatar,
- ),
- )
- @classmethod
- async def auto_login_service(
- cls, request: Request, redis: Redis, db: AsyncSession, token: str
- ) -> JWTOutSchema:
- """
- 免登录
- 参数:
- - request (Request): FastAPI请求对象
- - redis (Redis): Redis客户端对象
- - db (AsyncSession): 数据库会话对象
- - token (str): 免登录Token
- 返回:
- - JWTOutSchema: JWT令牌信息
- 异常:
- - CustomException: Token无效或过期时抛出异常
- """
- from sqlalchemy import select
- from app.api.v1.module_system.user.model import UserModel
- # 验证Token
- token_key = f"{cls.AUTO_LOGIN_PREFIX}{token}"
- token_data_str = await RedisCURD(redis).get(token_key)
- if not token_data_str:
- raise CustomException(msg="免登录Token已过期或无效")
- token_data = json.loads(token_data_str)
- user_id = token_data.get("user_id")
- # 查询用户
- stmt = select(UserModel).where(UserModel.id == user_id)
- result = await db.execute(stmt)
- user = result.scalar_one_or_none()
- if not user:
- raise CustomException(msg="用户不存在")
- if user.status == "1":
- raise CustomException(msg="用户已被停用")
- # 删除已使用的Token
- await RedisCURD(redis).delete(token_key)
- # 使用LoginService创建token
- jwt_token = await LoginService.create_token_service(
- request=request, redis=redis, user=user, login_type="PC端"
- )
- log.info(f"用户{user.username}免登录成功")
- return jwt_token
- class SmsCodeService:
- """短信验证码服务"""
- SMS_CODE_PREFIX = "sms_code"
- SMS_CODE_EXPIRE = 60 * 10
-
- @classmethod
- async def send_sms_code_service(
- cls, sms_code: SmsCodeSchema, redis: Redis
- ) -> bool:
- """
- 发送短信验证码
- 参数:
- - smsCode (SmsCodeSchema): 短信验证码请求模型
- - redis (Redis): Redis客户端对象
- 异常:
- - CustomException: 验证码发送失败时抛出异常。
- """
- template = SmsTemplateEnum.get_template_by_name(sms_code.template_name)
- code = generate_random_code(6)
- redis_key = f"{cls.SMS_CODE_PREFIX}:{sms_code.template_name}:{sms_code.mobile}"
- await RedisCURD(redis).set(
- key=redis_key,
- value=code,
- expire=cls.SMS_CODE_EXPIRE,
- )
- request = SendSmsRequest(
- phone_numbers=sms_code.mobile,
- template_code=template.template_code,
- template_param=template.template_param_fn(code=code),
- )
- return await SmsSender.send_sms(request)
-
-
- @classmethod
- async def verify_sms_code_service(
- cls, sms_code: SmsCodeSchema, redis: Redis
- ) -> bool:
- """
- 验证短信验证码
- 参数:
- - smsCode (SmsCodeSchema): 短信验证码请求模型
- - redis (Redis): Redis客户端对象
- 返回:
- - bool: 验证结果
- 异常:
- - CustomException: 验证码验证失败时抛出异常。
- """
- redis_key = f"{cls.SMS_CODE_PREFIX}:{sms_code.template_name}:{sms_code.mobile}"
- code = await RedisCURD(redis).get(redis_key)
- if not code or code != sms_code.code:
- return False
- await RedisCURD(redis).delete(redis_key)
- return True
|