sys_register.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # -*- coding: utf-8 -*-
  2. from flask import flash
  3. from ruoyi_common.domain.vo import RegisterBody
  4. from ruoyi_common.utils import security_util as SecurityUtil
  5. from ruoyi_common.constant import Constants, UserConstants
  6. from ruoyi_common.exception import CaptchaException, CaptchaExpireException, NotContentException
  7. from ruoyi_common.domain.entity import SysUser
  8. from ruoyi_system.service import SysUserService, SysConfigService
  9. from ruoyi_system.mapper import SysUserMapper
  10. from ruoyi_admin.ext import redis_cache
  11. class RegisterService:
  12. @classmethod
  13. def register(cls, body: RegisterBody) -> str:
  14. """
  15. 注册用户
  16. Args:
  17. body (RegisterBody): 注册信息
  18. Returns:
  19. str: 注册结果信息
  20. """
  21. msg = ""
  22. username = body.username
  23. password = body.password
  24. captcha_on_off = SysConfigService.select_captcha_on_off()
  25. # Captcha switch
  26. if captcha_on_off:
  27. cls.validate_captcha(username, body.code, body.uuid)
  28. if not username:
  29. msg = "Username cannot be empty"
  30. elif not password:
  31. msg = "User password cannot be empty"
  32. elif len(username) < UserConstants.USERNAME_MIN_LENGTH or len(username) > UserConstants.USERNAME_MAX_LENGTH:
  33. msg = "Account length must be between 2 and 20 characters"
  34. elif len(password) < UserConstants.PASSWORD_MIN_LENGTH or len(password) > UserConstants.PASSWORD_MAX_LENGTH:
  35. msg = "Password length must be between 5 and 20 characters"
  36. elif SysUserMapper.check_user_name_unique(username) > 0:
  37. msg = f"Failed to save user '{username}', registration account already exists"
  38. else:
  39. sys_user = SysUser(
  40. user_name=username,
  41. nick_name=username,
  42. password=SecurityUtil.encrypt_password(body.password.get_secret_value())
  43. )
  44. reg_flag = SysUserService.register_user(sys_user)
  45. if not reg_flag:
  46. msg = "Registration failed, please contact system administrator"
  47. else:
  48. flash("user.register.success")
  49. return msg
  50. @classmethod
  51. def validate_captcha(cls, username: str, code: str, uuid: str):
  52. """
  53. 验证码校验
  54. Args:
  55. username (str): 用户名
  56. code (str): 验证码
  57. uuid (str): 验证码唯一标识
  58. Raises:
  59. CaptchaException: 验证码错误
  60. CaptchaExpireException: 验证码过期
  61. """
  62. if not code:
  63. raise NotContentException()
  64. verify_key = Constants.CAPTCHA_CODE_KEY + (uuid if uuid is not None else "")
  65. captcha: bytes = redis_cache.get(verify_key)
  66. if not captcha:
  67. raise CaptchaExpireException()
  68. redis_cache.delete(verify_key)
  69. if code.lower() != captcha.decode("utf-8").lower():
  70. raise CaptchaException()