用戶管理—用戶注冊 重構之路

V1

UserRepository.cs

public async Task<JsonMessage> Register(User entity)
{
    if (await _dbContext.Set<User>().AnyAsync(p => p.UserName == entity.UserName))
    {
    throw new CustomException(-1, "登錄賬號已注冊,不能重復注冊!");
    }

    if (await _dbContext.Set<User>().AnyAsync(p => p.EmailAddress == entity.EmailAddress))
    {
    throw new CustomException(-1, "郵箱已注冊,不能重復注冊!");
    }

    if (await _dbContext.Set<User>().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
{
    /// <summary>
    /// 用戶模型,聚合根
    /// </summary>
    public class User : Entity, IFullAudited<Guid?>
        , 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)
        {
            // 內(nèi)部檢查郵箱、密碼的基本信息,基本業(yè)務規(guī)則在模型內(nèi)部封裝
            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的隨機數(shù)
            Slat = GetRandomStr(5);      // 返回隨機數(shù)
            Password = GetCiphertext(password, (byte)HashType, Slat);  // 獲得密文
            State = (int)UseState.Inuse; // 使用狀態(tài)設置為Inuse
            CreationTime = DateTime.Now;
            DisOrder = 0;
            IsDeleted = false;
            IsEmailConfirmed = false;
            IsActive = false;
        }

        /// <summary>
        /// 生成用戶Id
        /// </summary>
        /// <returns></returns>
        private Guid GenerateUserId()
        {
            return new RegularGuidGenerator().Create();
        }

        /// <summary>
        /// 生成租戶Id
        /// </summary>
        /// <returns></returns>
        private Guid GenerateTenantId()
        {
            return TenantHelper.GenerateTenantId();
        }

        /// <summary>
        /// 獲得0-5的隨機數(shù)
        /// </summary>
        /// <returns></returns>
        private static int GetRandomNum()
        {
            return HashEncryption.GetRandomNum();
        }

        /// <summary>
        /// 獲得指定長度的字符串隨機數(shù)
        /// </summary>
        /// <param name="length">指定長度,默認為5</param>
        /// <returns>返回隨機數(shù)</returns>
        private static string GetRandomStr(int length)
        {
            return HashEncryption.GetRandomStr(5);
        }

        /// <summary>
        /// 根據(jù)密碼、加密方法、隨機數(shù)獲得密文
        /// </summary>
        /// <param name="pwd">密碼</param>
        /// <param name="hashType">加密類型</param>
        /// <param name="slat">隨機數(shù)</param>
        /// <returns>返回密文</returns>
        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
{
    /// <summary>
    /// User Domain Service
    /// </summary>
    public class UserService
    {
        private IUserRepository _userRepository;

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

        /// <summary>
        /// 檢查用戶注冊時是否滿足注冊條件的領域服務,封裝用戶注冊的相關業(yè)務規(guī)則
        /// </summary>
        /// <param name="user"></param>
        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<JsonMessage> 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);

}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,632評論 19 139
  • 飄云隨風四海游, 漂泊流離無居所。 野花深谷自來香, 冬去春來換新顏。 花嘆終生寸難移, 云感一世無定所。 云花對...
    雅寶閱讀 173評論 0 0
  • 月光之下,讓我們再次審視自己的靈魂。這無關于政治,這是來自人性的拷問! 美國當?shù)貢r間2月26號,2017年的奧斯卡...
    騾子看電影閱讀 494評論 0 1
  • 現(xiàn)在想來,覺得弟弟小時候可以算得上一個奇人。只不過隨著年齡的增長,困擾越來越多,挫敗越來越多,漸漸地消磨干凈了。 ...
    liyongthethird閱讀 409評論 0 0
  • 商小痕琢磨著,要在七點半前到地鐵站,就是要七點十分前出門,那意味著六點四十左右就要起床,如果要保證每天六個小時的睡...
    奈何既往閱讀 355評論 0 1

友情鏈接更多精彩內(nèi)容