import uuid from Context.common import ctx from enum import Enum from captcha.image import ImageCaptcha from Utils.EmailUtils import send_email from Utils.RandomUtils import get_random_num_code, get_random_letter_and_num_code class EmailVerifyType(Enum): login = 1 register = 2 reset_password = 3 class ImageCaptchaVerify: @classmethod def make_captcha_image(cls, code=None, expire_time_s: int = 120): captcha_id = str(uuid.uuid4()) image = ImageCaptcha() if not code: code = get_random_letter_and_num_code(4) image_bytes = image.generate(code).getvalue() ctx.redis_pool.conn.set(captcha_id, code, expire_time_s) return captcha_id, image_bytes @classmethod def check_code(cls, captcha_id, code: str) -> bytes: captcha_code = ctx.redis_pool.conn.get(captcha_id) print("captcha_code", captcha_code) ctx.redis_pool.conn.delete(captcha_id) if captcha_code and captcha_code.lower() != code.lower(): return False return True class EmailVerifyCode: @classmethod def get_email_id(cls, email, verify_type: EmailVerifyType = EmailVerifyType.login): """ :param email: :param verify_type: 不同业务验证类型对应不同的id :return:str """ return f"{email}_EmailVerifyCodeId_{verify_type.name}" @classmethod def make_code(cls, email, expire_time_s=60 * 5, verify_type: EmailVerifyType = EmailVerifyType.login): client = ctx.redis_pool.get_redis_client() email_id = cls.get_email_id(email, verify_type) code = get_random_num_code(8) client.set(email_id, code) if expire_time_s: client.expire(email_id, expire_time_s) return code @classmethod def send_login_code(cls, email): send_email("", email, "") pass @classmethod def send_register_code(cls, email): code = cls.make_code(email) send_email("注册验证码", email, code) pass @classmethod def send_rest_code(cls, email): send_email("", email, "") pass @classmethod def check_code(cls, email, code, verify_type: EmailVerifyType = EmailVerifyType.login): email_id = cls.get_email_id(email, verify_type) client = ctx.redis_pool.get_redis_client() email_code = client.get(email_id) return code and code == email_code @classmethod def remove_code(cls, email, verify_type: EmailVerifyType = EmailVerifyType.login): client = ctx.redis_pool.get_redis_client() email_id = cls.get_email_id(email) client.delete(email_id)