""" 验证码服务 """ from iti.applications.extensions.cache import cache_redis, cache_simple import random from enum import Enum from iti.applications.common.exceptions.biz_exp import BizException class VerificationCodeUsage(str, Enum): """ 验证码使用场景 """ COMMON = "common" # 通用 LOGIN = "login" # 登录 REGISTER = "register" # 注册 RESET_PASSWORD = "reset_password" # 重置密码 BIND_PHONE = "bind_phone" # 绑定手机号 BIND_EMAIL = "bind_email" # 绑定邮箱 UPDATE_PASSWORD = "update_password" # 修改密码 def get_verification_code( subject: str, usage: VerificationCodeUsage = VerificationCodeUsage.COMMON ) -> str: """ 获取验证码 """ return cache_simple.get(key=f"verification_code:{usage}:{subject}") def set_verification_code( subject: str, code: str = None, usage: VerificationCodeUsage = VerificationCodeUsage.COMMON, ) -> str: """ 设置验证码,并返回验证码 """ if code is None: code = str(random.randint(100000, 999999)) cache_simple.set( key=f"verification_code:{usage}:{subject}", value=code, timeout=60 * 5 ) return code def check_verification_code( subject: str, code: str, usage: VerificationCodeUsage = VerificationCodeUsage.COMMON ) -> bool: """ 检查验证码 """ cached = get_verification_code(subject, usage) if cached is None: raise BizException("验证码过期或未发送") return cached == code