Просмотр исходного кода

用户注册接口、用户登录接口

lifa 1 год назад
Родитель
Сommit
f9babd7c25

+ 1 - 1
src/hosts/DiTui.Host/Configs/appconfig.json

@@ -103,7 +103,7 @@
   //最大请求大小
   "maxRequestBodySize": 104857600,
   //健康检查
-  "healthChecks": {
+  "healthChecks": { 
     //启用
     "enable": true,
     //访问路径

+ 15 - 0
src/platform/ZhonTai.Admin/Domain/Platform/IPlatformUserRepository.cs

@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using ZhonTai.Admin.Core.Repositories;
+using ZhonTai.Admin.Domain.Project;
+
+namespace ZhonTai.Admin.Domain.Platform
+{
+    public interface IPlatformUserRepository : IRepositoryBase<PlatformUserEntity>
+    {
+
+    }
+}

+ 59 - 0
src/platform/ZhonTai.Admin/Domain/Platform/PlatformUserEntity.cs

@@ -0,0 +1,59 @@
+using ZhonTai.Admin.Core.Entities;
+using FreeSql.DataAnnotations;
+
+namespace ZhonTai.Admin.Domain.Platform
+{
+    /// <summary>
+    /// 平台用户
+    /// </summary>
+    [Table(Name = "ditui_platform_user")]
+    public class PlatformUserEntity : EntityTenant
+    {
+        /// <summary>
+        /// 用户名
+        /// </summary>
+        public string Name { get; set; }
+        /// <summary>
+        /// 手机号
+        /// </summary>
+        public string Phone { get; set; }
+        /// <summary>
+        /// 密码
+        /// </summary>
+        public string Password { get; set; }
+
+        /// <summary>
+        /// 用户微信号
+        /// </summary>
+        public string WechatAccount { get; set; }
+
+        /// <summary>
+        /// 上级
+        /// </summary>
+        public string ParentId { get; set; }
+
+        ///// <summary>
+        ///// 省
+        ///// </summary>
+        //public string Province { get; set; }
+
+        ///// <summary>
+        ///// 市
+        ///// </summary>
+        //public string City { get; set; }
+
+        /// <summary>
+        /// 备注
+        /// </summary>
+        public string Remark { get; set; }
+
+        /// <summary>
+        /// 角色 
+        /// 通过后台开通的是平台管理员1  注册是下级2
+        /// </summary>
+        public string Role { get; set; }
+
+
+        /// 通过手机号和上级ID 来判断唯一(一个手机号可注册多个不同上级的账号)
+    }
+}

+ 26 - 0
src/platform/ZhonTai.Admin/Repositories/Platform/PlatformUserRepository.cs

@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using ZhonTai.Admin.Core.Db.Transaction;
+using ZhonTai.Admin.Domain.Platform;
+
+namespace ZhonTai.Admin.Repositories.Platform
+{
+    public class PlatformUserRepository : AdminRepositoryBase<PlatformUserEntity>, IPlatformUserRepository
+    {
+        public PlatformUserRepository(UnitOfWorkManagerCloud muowm) : base(muowm)
+        {
+
+        }
+    }
+
+    //public class ProjectRepository : AdminRepositoryBase<ProjectEntity>, IProjectRepository
+    //{
+    //    public ProjectRepository(UnitOfWorkManagerCloud muowm) : base(muowm)
+    //    {
+
+    //    }
+    //}
+}

+ 245 - 7
src/platform/ZhonTai.Admin/Services/DiTuiAPI/DiTuiAPIService.cs

@@ -1,37 +1,275 @@
 using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Identity;
 using Microsoft.AspNetCore.Mvc;
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Diagnostics;
 using System.Threading.Tasks;
 using ZhonTai.Admin.Core.Attributes;
 using ZhonTai.Admin.Core.Consts;
+using ZhonTai.Admin.Core.Dto;
 using ZhonTai.Admin.Domain.User;
+using ZhonTai.Admin.Services.Auth.Dto;
 using ZhonTai.Admin.Services.DiTuiAPI.Dto;
+using ZhonTai.Common.Helpers;
 using ZhonTai.DynamicApi;
 using ZhonTai.DynamicApi.Attributes;
+using ZhonTai.Admin.Domain.Platform;
+using ZhonTai.Admin.Core.Configs;
+using ZhonTai.Admin.Domain.Tenant;
+using System.Security.Claims;
+using ZhonTai.Admin.Core.Auth;
+using ZhonTai.Common.Extensions;
+using System.Linq.Expressions;
+using ZhonTai.Admin.Domain.UserOrg;
+using ZhonTai.Admin.Domain.UserRole;
+using ZhonTai.Admin.Domain.UserStaff;
+using ZhonTai.Admin.Services.User.Dto;
 
 namespace ZhonTai.Admin.Services.DiTuiAPI
 {
+
+
     /// <summary>
     /// 前端接口
     /// </summary>
     [DynamicApi(Area = AdminConsts.DiTuiName)]
     public class DiTuiAPIService : BaseService, IDiTuiAPIService, IDynamicApi
     {
+        private IPasswordHasher<PlatformUserEntity> _passwordHasher => LazyGetRequiredService<IPasswordHasher<PlatformUserEntity>>();
+        private readonly AppConfig _appConfig;
         private readonly IUserRepository _userRepository;
-        public DiTuiAPIService(IUserRepository userRepository)
+        private readonly IPlatformUserRepository _platformUserRepository;
+        private readonly ITenantRepository _tenantRepository;
+        public DiTuiAPIService(
+            IPlatformUserRepository platformUserRepository,
+            AppConfig appConfig,
+            ITenantRepository tenantRepository
+            )
         {
-            _userRepository = userRepository;
+            _platformUserRepository = platformUserRepository;
+            _appConfig = appConfig;
+            _tenantRepository = tenantRepository;
         }
 
         [HttpPost]
         [AllowAnonymous]
         [NoOprationLog]
-        public Task<dynamic> LoginAsync(LoginInput input)
-        {            
+        public async Task<dynamic> LoginAsync(LoginInput input)
+        {
+            using (_platformUserRepository.DataFilter.DisableAll())
+            {
+                var sw = new Stopwatch();
+                sw.Start();
+
+                #region 验证码校验
+
+                //if (_appConfig.VarifyCode.Enable)
+                //{
+                //    if (input.CaptchaId.IsNull() || input.CaptchaData.IsNull())
+                //    {
+                //        throw ResultOutput.Exception("请完成安全验证");
+                //    }
+                //    var validateResult = _captcha.Validate(input.CaptchaId, JsonConvert.DeserializeObject<SlideTrack>(input.CaptchaData));
+                //    if (validateResult.Result != ValidateResultType.Success)
+                //    {
+                //        throw ResultOutput.Exception($"安全{validateResult.Message},请重新登录");
+                //    }
+                //}
+
+                #endregion
+
+                #region 密码解密
+
+                //if (input.PasswordKey.NotNull())
+                //{
+                //    var passwordEncryptKey = CacheKeys.PassWordEncrypt + input.PasswordKey;
+                //    var existsPasswordKey = await Cache.ExistsAsync(passwordEncryptKey);
+                //    if (existsPasswordKey)
+                //    {
+                //        var secretKey = await Cache.GetAsync(passwordEncryptKey);
+                //        if (secretKey.IsNull())
+                //        {
+                //            throw ResultOutput.Exception("解密失败");
+                //        }
+                //        input.Password = DesEncrypt.Decrypt(input.Password, secretKey);
+                //        await Cache.DelAsync(passwordEncryptKey);
+                //    }
+                //    else
+                //    {
+                //        throw ResultOutput.Exception("解密失败");
+                //    }
+                //}
+
+                #endregion
+
+                #region 登录
+                var user = await _platformUserRepository.Select.Where(a => a.Phone == input.mobile).ToOneAsync();
+                var valid = user?.Id > 0;
+                if (valid)
+                {
+                    var password = MD5Encrypt.Encrypt32(input.pwd);
+                    valid = user.Password == password;
+                }
+
+                if (!valid)
+                {
+                    throw ResultOutput.Exception("用户名或密码错误");
+                }
+
+                //if (!user.Enabled)
+                //{
+                //    throw ResultOutput.Exception("账号已停用,禁止登录");
+                //}
+                #endregion
+
+                #region 获得token
+                var authLoginOutput = Mapper.Map<AuthLoginOutput>(user);
+                if (_appConfig.Tenant)
+                {
+                    var tenant = await _tenantRepository.Select.WhereDynamic(user.TenantId).ToOneAsync<AuthLoginTenantDto>();
+                    if (!(tenant != null && tenant.Enabled))
+                    {
+                        throw ResultOutput.Exception("企业已停用,禁止登录");
+                    }
+                    authLoginOutput.Tenant = tenant;
+                }
+                
+                string token = GetToken(authLoginOutput);
+                #endregion
+
+                sw.Stop();
+
+                #region 添加登录日志
+
+                //var loginLogAddInput = new LoginLogAddInput
+                //{
+                //    TenantId = authLoginOutput.TenantId,
+                //    Name = authLoginOutput.Name,
+                //    ElapsedMilliseconds = sw.ElapsedMilliseconds,
+                //    Status = true,
+                //    CreatedUserId = authLoginOutput.Id,
+                //    CreatedUserName = user.UserName,
+                //};
+
+                //await LazyGetRequiredService<ILoginLogService>().AddAsync(loginLogAddInput);
+
+                #endregion 添加登录日志
+
+                return new { token };
+            }
             throw new NotImplementedException();
         }
+
+        /// <summary>
+        /// 新增用户
+        /// </summary>
+        /// <param name="input"></param>
+        /// <returns></returns>
+        [HttpPost]
+        [AllowAnonymous]
+        [NoOprationLog]
+        [AdminTransaction]
+        public virtual async Task<long> RegisterAsync(RegisterInput input)
+        {
+            Expression<Func<PlatformUserEntity, bool>> where = (a => a.Phone == input.Phone);
+            where = where.Or(input.Phone.NotNull(), a => a.Phone == input.Phone)
+                .Or(input.Name.NotNull(), a => a.Name == input.Name);
+
+            var existsUser = await _platformUserRepository.Select.Where(where)
+                .FirstAsync(a => new { a.Name, a.Phone });
+
+            if (existsUser != null)
+            {
+                // 可能会有重名用户
+                //if (existsUser.Name == input.Name)
+                //{
+                //    throw ResultOutput.Exception($"账号已存在");
+                //}
+
+                if (input.Phone.NotNull() && existsUser.Phone == input.Phone)
+                {
+                    throw ResultOutput.Exception($"手机号已存在");
+                }
+
+                //if (input.Name.NotNull() && existsUser.Name == input.Name)
+                //{
+                //    throw ResultOutput.Exception($"姓名已存在");
+                //}
+            }
+
+            // 用户信息
+            if (input.Password.IsNull())
+            {
+                input.Password = _appConfig.DefaultPassword;
+            }
+
+            var entity = Mapper.Map<PlatformUserEntity>(input);
+            //entity.Type = UserType.DefaultUser;
+        
+            entity.Password = MD5Encrypt.Encrypt32(input.Password);
+            // 注册口注册用户皆为下级角色
+            entity.Role = "2";
+            var user = await _platformUserRepository.InsertAsync(entity);
+            var userId = user.Id;
+
+            //用户角色
+            //if (input.RoleIds != null && input.RoleIds.Any())
+            //{
+            //    var roles = input.RoleIds.Select(roleId => new UserRoleEntity
+            //    {
+            //        UserId = userId,
+            //        RoleId = roleId
+            //    }).ToList();
+            //    await _userRoleRepository.InsertAsync(roles);
+            //}
+
+            // 员工信息
+            //var staff = input.Staff == null ? new UserStaffEntity() : Mapper.Map<UserStaffEntity>(input.Staff);
+            //staff.Id = userId;
+            //await _staffRepository.InsertAsync(staff);
+
+            ////所属部门
+            //if (input.OrgIds != null && input.OrgIds.Any())
+            //{
+            //    var orgs = input.OrgIds.Select(orgId => new UserOrgEntity
+            //    {
+            //        UserId = userId,
+            //        OrgId = orgId
+            //    }).ToList();
+            //    await _userOrgRepository.InsertAsync(orgs);
+            //}
+
+            return userId;
+        }
+
+
+
+        /// <summary>
+        /// 获得token
+        /// </summary>
+        /// <param name="user">用户信息</param>
+        /// <returns></returns>
+        private string GetToken(AuthLoginOutput user)
+        {
+            if (user == null)
+            {
+                return string.Empty;
+            }
+
+            var token = LazyGetRequiredService<IUserToken>().Create(new[]
+            {
+            new Claim(ClaimAttributes.UserId, user.Id.ToString(), ClaimValueTypes.Integer64),
+            new Claim(ClaimAttributes.UserName, user.UserName),
+            new Claim(ClaimAttributes.Name, user.Name),
+            new Claim(ClaimAttributes.UserType, user.Type.ToInt().ToString(), ClaimValueTypes.Integer32),
+            new Claim(ClaimAttributes.TenantId, user.TenantId.ToString(), ClaimValueTypes.Integer64),
+            new Claim(ClaimAttributes.TenantType, user.Tenant?.TenantType.ToInt().ToString(), ClaimValueTypes.Integer32),
+            new Claim(ClaimAttributes.DbKey, user.Tenant?.DbKey??"")
+        });
+
+            return token;
+        }
+
+
     }
 }

+ 20 - 0
src/platform/ZhonTai.Admin/Services/DiTuiAPI/Dto/RegisterInput.cs

@@ -0,0 +1,20 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ZhonTai.Admin.Services.DiTuiAPI.Dto
+{
+    public class RegisterInput
+    {
+        public string Name { get; set; }
+
+        public string Phone { get; set; }
+
+        public string Password { get; set; }
+        public string PasswordCheck { get; set; }
+
+        public string InvitCode { get; set; }
+    }
+}

+ 4 - 0
src/platform/ZhonTai.Admin/Services/DiTuiAPI/IDiTuiAPIService.cs

@@ -11,5 +11,9 @@ namespace ZhonTai.Admin.Services.DiTuiAPI
     public interface IDiTuiAPIService
     {
         Task<dynamic> LoginAsync(LoginInput input);
+
+        Task<long> RegisterAsync(RegisterInput input);
     }
+
+    
 }

+ 12 - 0
src/platform/ZhonTai.Admin/Services/Platform/Dto/PlatformUserAddInput.cs

@@ -0,0 +1,12 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ZhonTai.Admin.Services.Platform.Dto
+{
+    internal class PlatformUserAddInput
+    {
+    }
+}

+ 14 - 0
src/platform/ZhonTai.Admin/Services/Platform/IPlatformUserService.cs

@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using ZhonTai.Admin.Services.Auth.Dto;
+
+namespace ZhonTai.Admin.Services.Platform
+{
+    public interface IPlatformUserService
+    {
+        Task<dynamic> LoginAsync(AuthLoginInput input);
+    }
+}

+ 12 - 0
src/platform/ZhonTai.Admin/Services/Platform/PlatformUserService.cs

@@ -0,0 +1,12 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ZhonTai.Admin.Services.Platform
+{
+    internal class PlatformUserService
+    {
+    }
+}

+ 55 - 0
src/platform/ZhonTai.Admin/ZhonTai.Admin.xml

@@ -2903,6 +2903,47 @@
             权限列表
             </summary>
         </member>
+        <member name="T:ZhonTai.Admin.Domain.Platform.PlatformUserEntity">
+            <summary>
+            平台用户
+            </summary>
+        </member>
+        <member name="P:ZhonTai.Admin.Domain.Platform.PlatformUserEntity.Name">
+            <summary>
+            用户名
+            </summary>
+        </member>
+        <member name="P:ZhonTai.Admin.Domain.Platform.PlatformUserEntity.Phone">
+            <summary>
+            手机号
+            </summary>
+        </member>
+        <member name="P:ZhonTai.Admin.Domain.Platform.PlatformUserEntity.Password">
+            <summary>
+            密码
+            </summary>
+        </member>
+        <member name="P:ZhonTai.Admin.Domain.Platform.PlatformUserEntity.WechatAccount">
+            <summary>
+            用户微信号
+            </summary>
+        </member>
+        <member name="P:ZhonTai.Admin.Domain.Platform.PlatformUserEntity.ParentId">
+            <summary>
+            上级
+            </summary>
+        </member>
+        <member name="P:ZhonTai.Admin.Domain.Platform.PlatformUserEntity.Remark">
+            <summary>
+            备注
+            </summary>
+        </member>
+        <member name="P:ZhonTai.Admin.Domain.Platform.PlatformUserEntity.Role">
+            <summary>
+            角色 
+            通过后台开通的是平台管理员1  注册是下级2
+            </summary>
+        </member>
         <member name="T:ZhonTai.Admin.Domain.Project.ProjectEntity">
             <summary>
             拉新项目
@@ -5047,6 +5088,20 @@
             前端接口
             </summary>
         </member>
+        <member name="M:ZhonTai.Admin.Services.DiTuiAPI.DiTuiAPIService.RegisterAsync(ZhonTai.Admin.Services.DiTuiAPI.Dto.RegisterInput)">
+            <summary>
+            新增用户
+            </summary>
+            <param name="input"></param>
+            <returns></returns>
+        </member>
+        <member name="M:ZhonTai.Admin.Services.DiTuiAPI.DiTuiAPIService.GetToken(ZhonTai.Admin.Services.Auth.Dto.AuthLoginOutput)">
+            <summary>
+            获得token
+            </summary>
+            <param name="user">用户信息</param>
+            <returns></returns>
+        </member>
         <member name="T:ZhonTai.Admin.Services.Document.DocumentService">
             <summary>
             文档服务