sys_register.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  7. from ruoyi_common.domain.entity import SysUser
  8. from ruoyi_system.service import SysUserService
  9. from ruoyi_admin.ext import redis_cache
  10. # todo
  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 = cls.config_service.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 UserConstants.NOT_UNIQUE == SysUserService.check_user_name_unique(username):
  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(self, 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. verify_key = Constants.CAPTCHA_CODE_KEY + (uuid if uuid is not None else "")
  63. captcha = redis_cache.get_cache_object(verify_key)
  64. # redis_cache.delete_object(verify_key)
  65. if captcha is None:
  66. raise CaptchaExpireException()
  67. if code.lower() != captcha.lower():
  68. raise CaptchaException()