用户管理—用户注册 重构之路

V1

UserRepository.cs

public async Task Register(User entity)
{
    if (await _dbContext.Set().AnyAsync(p => p.UserName == entity.UserName))
    {
    throw new CustomException(-1, "登录账号已注册,不能重复注册!");
    }

    if (await _dbContext.Set().AnyAsync(p => p.EmailAddress == entity.EmailAddress))
    {
    throw new CustomException(-1, "邮箱已注册,不能重复注册!");
    }

    if (await _dbContext.Set().AnyAsync(p => p.MobilePhone == entity.MobilePhone))
    {
    throw new CustomException(-1, "手机号已注册,不能重复注册!");
    }

    entity.Id = new RegularGuidGenerator().Create();
    entity.HashType = HashEncryption.GetRandomNum();
    entity.Slat = HashEncryption.GetRandomStr(5);
    entity.Password = new HashEncryption().GetCiphertext(entity.Password, (byte)entity.HashType, entity.Slat);
    entity.State = 0;

    _dbContext.Users.Add(entity);
    await _dbContext.SaveChangesAsync();

    return ServiceResult.GetErrorMsgByErrCode(0);
}

V2

User.cs

using System;
using Tdf.Domain.Entities;
using Tdf.Domain.Entities.Auditing;
using Tdf.Utils.Encryption;
using Tdf.Utils.GuidHelper;
using Tdf.Utils.Helper;

namespace Tdf.Domain.Act.Entities
{
    /// 
    /// 用户模型,聚合根
    /// 
    public class User : Entity, IFullAudited
        , IMustHaveTenant, IPassivable
    {
        public Guid TenantId { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public int? HashType { get; set; }
        public string Slat { get; set; }
        public string EmailAddress { get; set; }
        public string MobilePhone { get; set; }
        public bool IsEmailConfirmed { get; set; }
        public string EmailConfirmationCode { get; set; }
        public string PasswordResetCode { get; set; }
        public DateTime? LastLoginTime { get; set; }
        public bool IsActive { get; set; }
        public bool IsDeleted { get; set; }
        public Guid? DeleterUserId { get; set; }
        public DateTime? DeletionTime { get; set; }
        public Guid? LastModifierUserId { get; set; }
        public DateTime? LastModificationTime { get; set; }
        public Guid? CreatorUserId { get; set; }
        public DateTime CreationTime { get; set; }
        public int DisOrder { get; set; }
        public int State { get; set; }

        public User(string userName, string emailAddress, string mobilePhone, string password)
        {
            // 内部检查邮箱、密码的基本信息,基本业务规则在模型内部封装
            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new ArgumentNullException("登录账号不能为空!");
            }

            if (string.IsNullOrWhiteSpace(emailAddress))
            {
                throw new ArgumentNullException("邮箱不能为空!");
            }

            if (string.IsNullOrWhiteSpace(mobilePhone))
            {
                throw new ArgumentNullException("手机号不能为空!");
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("密码不能为空!");
            }

            if (password.Trim().Length < 6)
            {
                throw new ArgumentNullException("密码长度应超过6个字符!");
            }

            if (!RegexHelper.IsMobilePhone(mobilePhone))
            {
                throw new ArgumentNullException("请输入正确的手机号!");
            }

            if (!RegexHelper.IsEmail(emailAddress))
            {
                throw new ArgumentNullException("请输入正确的邮箱!");
            }

            Id = GenerateUserId();          // 生成用户Id
            TenantId = GenerateTenantId();  // 生成租户Id
            UserName = userName;
            EmailAddress = emailAddress;
            MobilePhone = mobilePhone;
            HashType = GetRandomNum();   // 获得0-5的随机数
            Slat = GetRandomStr(5);      // 返回随机数
            Password = GetCiphertext(password, (byte)HashType, Slat);  // 获得密文
            State = (int)UseState.Inuse; // 使用状态设置为Inuse
            CreationTime = DateTime.Now;
            DisOrder = 0;
            IsDeleted = false;
            IsEmailConfirmed = false;
            IsActive = false;
        }

        /// 
        /// 生成用户Id
        /// 
        /// 
        private Guid GenerateUserId()
        {
            return new RegularGuidGenerator().Create();
        }

        /// 
        /// 生成租户Id
        /// 
        /// 
        private Guid GenerateTenantId()
        {
            return TenantHelper.GenerateTenantId();
        }

        /// 
        /// 获得0-5的随机数
        /// 
        /// 
        private static int GetRandomNum()
        {
            return HashEncryption.GetRandomNum();
        }

        /// 
        /// 获得指定长度的字符串随机数
        /// 
        /// 指定长度,默认为5
        /// 返回随机数
        private static string GetRandomStr(int length)
        {
            return HashEncryption.GetRandomStr(5);
        }

        /// 
        /// 根据密码、加密方法、随机数获得密文
        /// 
        /// 密码
        /// 加密类型
        /// 随机数
        /// 返回密文
        private string GetCiphertext(string pwd, byte? hashType, string slat)
        {
            return new HashEncryption().GetCiphertext(pwd, (byte)hashType, slat);
        }

    }
}

UserService.cs

using System;
using Tdf.Domain.Act.Entities;
using Tdf.Domain.Act.Repositories;

namespace Tdf.Domain.Act.Services
{
    /// 
    /// User Domain Service
    /// 
    public class UserService
    {
        private IUserRepository _userRepository;

        public UserService(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        /// 
        /// 检查用户注册时是否满足注册条件的领域服务,封装用户注册的相关业务规则
        /// 
        /// 
        public void CheckUserRegistration(User user)
        {
            if ( _userRepository.IsExist(p => p.UserName == user.UserName))
            {
                throw new Exception("登录账号已注册,不能重复注册!");
            }

            if (_userRepository.IsExist(p => p.EmailAddress == user.EmailAddress))
            {
                throw new Exception("邮箱已注册,不能重复注册!");
            }

            if (_userRepository.IsExist(p => p.MobilePhone == user.MobilePhone))
            {
                throw new Exception("手机号已注册,不能重复注册!");
            }


        }
    }
}

UserAppService.cs

public async Task Register()
{
    string userName = "Samba";
    string emailAddress = "emailAddress";
    string mobilePhone = "mobilePhone ";
    string password = "123456";

    var user = new User(userName, emailAddress, mobilePhone, password);
    _userService.CheckUserRegistration(user);
    await _userRepository.InsertAsync(user);
    await _uow.SaveChangesAsync();
    return ServiceResult.GetErrorMsgByErrCode(0);

}

你可能感兴趣的:(用户管理—用户注册 重构之路)