Esempio n. 1
0
        public IActionResult Create(UserCreateViewModel model)
        {
            ResponseModel response = ResponseModelFactory.CreateInstance;

            if (model.LoginName.Trim().Length <= 0)
            {
                response.SetFailed("请输入登录名称");
                return(Ok(response));
            }
            if (_dbContext.DncUser.Count(x => x.LoginName == model.LoginName) > 0)
            {
                response.SetFailed("登录名已存在");
                return(Ok(response));
            }
            DncUser entity = _mapper.Map <UserCreateViewModel, DncUser>(model);

            entity.CreatedOn = DateTime.Now;
            entity.Guid      = Guid.NewGuid();
            entity.Status    = model.Status;
            _dbContext.DncUser.Add(entity);
            _dbContext.SaveChanges();
            response.SetSuccess();
            response.SetData(entity.Guid);
            return(Ok(response));
        }
Esempio n. 2
0
        /// <summary>
        /// 对指定实体的用户签署Bearer Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string TokenBulider(DncUser user)
        {
            if (user == null || user.IsDeleted == IsDeleted.Yes)
            {
                throw new InvalidOperationException("用户不存在");
            }

            if (user.IsLocked == IsLocked.Locked)
            {
                throw new InvalidOperationException("账号已被锁定");
            }

            if (user.Status == UserStatus.Forbidden)
            {
                throw new InvalidOperationException("账号已被禁用");
            }

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, user.LoginName),
                new Claim("guid", user.Guid.ToString()),
                new Claim("avatar", ""),
                new Claim("displayName", user.DisplayName),
                new Claim("loginName", user.LoginName),
                new Claim("emailAddress", ""),
                new Claim("guid", user.Guid.ToString()),
                new Claim("userType", ((int)user.UserType).ToString()),
            });

            return(JwtBearerAuthenticationExtension.GetJwtAccessToken(_appSettings, claimsIdentity));
        }
Esempio n. 3
0
        public IActionResult Edit(UserEditViewModel model)
        {
            ResponseModel response = ResponseModelFactory.CreateInstance;

            if (ConfigurationManager.AppSettings.IsTrialVersion)
            {
                response.SetIsTrial();
                return(Ok(response));
            }
            using (_dbContext)
            {
                DncUser entity = _dbContext.DncUser.FirstOrDefault(x => x.Guid == model.Guid);
                if (entity == null)
                {
                    response.SetFailed("用户不存在");
                    return(Ok(response));
                }
                entity.DisplayName        = model.DisplayName;
                entity.IsDeleted          = model.IsDeleted;
                entity.IsLocked           = model.IsLocked;
                entity.ModifiedByUserGuid = AuthContextService.CurrentUser.Guid;
                entity.ModifiedByUserName = AuthContextService.CurrentUser.DisplayName;
                entity.ModifiedOn         = DateTime.Now;
                entity.Password           = model.Password;
                entity.Status             = model.Status;
                entity.UserType           = model.UserType;
                entity.Description        = model.Description;
                _dbContext.SaveChanges();
                response = ResponseModelFactory.CreateInstance;
                return(Ok(response));
            }
        }
Esempio n. 4
0
 public IActionResult Edit(Guid guid)
 {
     using (_dbContext)
     {
         DncUser       entity   = _dbContext.DncUser.FirstOrDefault(x => x.Guid == guid);
         ResponseModel response = ResponseModelFactory.CreateInstance;
         response.SetData(_mapper.Map <DncUser, UserEditViewModel>(entity));
         return(Ok(response));
     }
 }
        public IActionResult Profile()
        {
            Models.Response.ResponseModel response = ResponseModelFactory.CreateInstance;
            Guid    guid = AuthContextService.CurrentUser.Guid;
            DncUser user = _dbContext.DncUser.FirstOrDefaultAsync(x => x.Guid == guid).Result;

            response.SetData(new
            {
                access      = new string[] { },
                avator      = user.Avatar,
                userGuid    = user.Guid,
                userName    = user.DisplayName,
                userType    = user.UserType,
                permissions = GetPermissionsByGuid(guid)
            });
            return(Ok(response));
        }
Esempio n. 6
0
        public IActionResult ExposeChangePassword([FromBody] ChangePasswordViewModel changePassword)
        {
            ResponseModel response = ResponseModelFactory.CreateInstance;
            DncUser       user     = _dbContext.DncUser.First(x => x.Guid == AuthContextService.CurrentUser.Guid);

            string[] passwordSplit = user.Password.Split("$");
            if (passwordSplit[1] != PasswordCalculator.SaltPassword(passwordSplit[0], changePassword.OldPasswordMD5))
            {
                response.SetFailed("旧密码错误");
                return(Ok(response));
            }
            else
            {
                _dbContext.DncUser.First(x => x.Guid == AuthContextService.CurrentUser.Guid).Password = user.Password = $"{user.LoginName}${PasswordCalculator.SaltPassword(user.LoginName, changePassword.NewPasswordMD5)}";
                _dbContext.SaveChanges();
                response.SetSuccess();
                return(Ok(response));
            }
        }
Esempio n. 7
0
        public IActionResult RefreshToken()
        {
            Guid currentUserGuid = Guid.Parse((from claim in HttpContext.User.Claims
                                               where claim.Type == "guid"
                                               select claim.Value).First());

            Models.Response.ResponseModel response = ResponseModelFactory.CreateInstance;
            DncUser user = _dbContext.DncUser.FirstOrDefault(x => x.Guid == currentUserGuid);

            try
            {
                response.SetData(TokenBulider(user));
                return(Ok(response));
            }
            catch (InvalidOperationException ex)
            {
                response.SetFailed(ex.Message);
                return(Ok(response));
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> Post([FromBody] CreateUserInputModel inputModel)
        {
            if (await _context.Users.AnyAsync(t => t.Account == inputModel.Account))
            {
                return(BadRequest("账号已存在"));
            }

            var dncUser = new DncUser
            {
                Account  = inputModel.Account,
                Password = inputModel.Password,
                NiName   = inputModel.NiName,
                Status   = inputModel.Status,
                Remark   = inputModel.Remark
            };

            await _context.Users.AddAsync(dncUser);

            await _context.SaveChangesAsync();

            return(Ok());
        }
        private Dictionary <string, IGrouping <string, string> > GetPermissionsByGuid(Guid guid)
        {
            DncUser user = _dbContext.DncUser.FirstOrDefaultAsync(x => x.Guid == guid).Result;
            IQueryable <IGrouping <string, string> > pagePermissions;

            if (user.UserType == UserType.SuperAdministrator)
            {
                //如果是超级管理员
                pagePermissions = from urm in _dbContext.DncRole
                                  join rpm in _dbContext.DncRolePermissionMapping on urm.Code equals rpm.RoleCode into rpms
                                  from permission in rpms.DefaultIfEmpty()
                                  group permission.PermissionCode by urm.Code;
            }
            else
            {
                pagePermissions = from urm in _dbContext.DncUserRoleMapping
                                  where urm.UserGuid == guid
                                  join rpm in _dbContext.DncRolePermissionMapping on urm.DncRole equals rpm.DncRole into rpms
                                  from permission in rpms.DefaultIfEmpty()
                                  group permission.PermissionCode by urm.RoleCode;
            }
            return(pagePermissions.ToDictionary(x => x.Key));
        }
Esempio n. 10
0
        public IActionResult AutoCreate([FromBody] AutoCreateUserViewModel model, bool autoPassword = true, bool returnToken = false)
        {
            ResponseModel response = ResponseModelFactory.CreateInstance;

            //查找用户是否已经存在
            DncUser target = _dbContext.DncUser.FirstOrDefault(x => (!string.IsNullOrWhiteSpace(model.WeChatUnionID) && x.WeChatUnionID == model.WeChatUnionID) || x.PhoneNumber == model.PhoneNumber);

            //不存在时自动创建
            if (target == default)
            {
                UserCreateViewModel user = new UserCreateViewModel
                {
                    LoginName   = model.PhoneNumber ?? model.WeChatUnionID,
                    DisplayName = model.PhoneNumber,
                    PhoneNumber = model.PhoneNumber,
                    IsLocked    = IsLocked.UnLocked,
                    Status      = UserStatus.Normal,
                    UserType    = UserType.GeneralUser,
                    IsDeleted   = IsDeleted.No,
                };
                if (autoPassword)
                {
                    string password = model.PhoneNumber ?? DateTime.Now.ToString();
                    user.Password = model.PhoneNumber != null ? $"{user.LoginName}${PasswordCalculator.SaltPassword(user.LoginName, PasswordCalculator.Md5(password))}" : null;
                }
                Create(user);
                target = _dbContext.DncUser.FirstOrDefault(x => (!string.IsNullOrWhiteSpace(model.WeChatUnionID) && x.WeChatUnionID.Trim() == model.WeChatUnionID) || x.PhoneNumber.Trim() == model.PhoneNumber);
            }

            //依然为default则创建失败
            if (target == default)
            {
                response.SetFailed("用户创建失败");
            }
            else
            {
                //如果Permission不为空,则检查是否具有对应的权限位
                if (!string.IsNullOrWhiteSpace(model.Permission))
                {
                    IQueryable <DncUserRoleMapping> targetPermission = from role in _dbContext.DncUserRoleMapping
                                                                       where role.UserGuid == target.Guid
                                                                       join permission in _dbContext.DncRolePermissionMapping on role.RoleCode equals permission.RoleCode
                                                                       where permission.PermissionCode == model.Permission
                                                                       select role;
                    if (targetPermission.FirstOrDefault() == default)
                    {
                        _dbContext.DncUserRoleMapping.Add(new DncUserRoleMapping
                        {
                            CreatedOn = DateTime.Now,
                            UserGuid  = target.Guid,
                            RoleCode  = model.Permission
                        });
                        _dbContext.SaveChanges();
                    }
                }

                //创建返回体
                dynamic result = new ExpandoObject();
                result.Guid = target.Guid;
                if (returnToken)
                {
                    result.Authorization = TokenBulider(target);
                }
                response.SetData(result);
            }
            return(Ok(response));


            string TokenBulider(DncUser user)
            {
                if (user == null || user.IsDeleted == IsDeleted.Yes)
                {
                    throw new InvalidOperationException("用户不存在");
                }

                if (user.IsLocked == IsLocked.Locked)
                {
                    throw new InvalidOperationException("账号已被锁定");
                }

                if (user.Status == UserStatus.Forbidden)
                {
                    throw new InvalidOperationException("账号已被禁用");
                }

                ClaimsIdentity claimsIdentity = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.LoginName),
                    new Claim("guid", user.Guid.ToString()),
                    new Claim("avatar", ""),
                    new Claim("displayName", user.DisplayName),
                    new Claim("loginName", user.LoginName),
                    new Claim("emailAddress", ""),
                    new Claim("guid", user.Guid.ToString()),
                    new Claim("userType", ((int)user.UserType).ToString()),
                });

                return(JwtBearerAuthenticationExtension.GetJwtAccessToken(_appSettings, claimsIdentity));
            }
        }