Beispiel #1
0
        public async Task AddRole()
        {
            var roleName = "NormalName";

            var roles = await _securityData.AddRole(roleName);

            var expected = _dbFaker.Roles.Max(l => l.Id) + 1;

            Assert.AreEqual(ActionStatus.Success, roles.Status);
            Assert.AreEqual(expected, roles.Id);
            _mock.Verify(data => data.AddRole(roleName), () => Times.Exactly(1));
        }
Beispiel #2
0
        public void Given_I_Call_AddRole_Then_The_Correct_Services_Are_Called()
        {
            //arrange
            const string name        = "Admin";
            const string description = "Test";
            var          permissions = new List <string> {
                "Permission1"
            };
            var actionPermissions = new List <ActionPermissionModel> {
                new ActionPermissionModel()
            };

            const int roleId = 1;

            _securityServerMock.Setup(s => s.AddRole(name, description)).Returns(roleId);
            _mapperMock.Setup(m => m.MapToActionPermissionModels(permissions)).Returns(actionPermissions);

            //act
            _sut.AddRole(_connectionModel, name, description, permissions);

            //assert
            _securityServerMock.Verify(v => v.AddRole(name, description));
            _mapperMock.Verify(v => v.MapToActionPermissionModels(permissions));
            _securityServerMock.Verify(v => v.UpdateRolePermissions(roleId, actionPermissions));
        }
        public void AddRole(string name, string description, IEnumerable <string> permissions)
        {
            name.ThrowExceptionIfNullOrEmpty("name");
            description.ThrowExceptionIfNullOrEmpty("description");

            _roleService.AddRole(_connectionModel, name, description, permissions);
        }
Beispiel #4
0
        private BaseActionResult AddRole(string parameters)
        {
            BaseActionResult result = new BaseActionResult();

            try
            {
                string roleName        = CommonGlobalSettings.Utilities.GetParameter("roleName", parameters);
                string roleDescription = CommonGlobalSettings.Utilities.GetParameter("roleDescription", parameters);
                string strDomain       = CommonGlobalSettings.Utilities.GetParameter("Domain", parameters);
                string parentId        = CommonGlobalSettings.Utilities.GetParameter("ParentId", parameters);
                int    iResultValue    = roleService.AddRole(roleName, roleDescription, strDomain, parentId);
                if (iResultValue == 0)
                {
                    result.Result = true;
                }
                else if (iResultValue == 1)
                {
                    result.Result        = false;
                    result.ReturnMessage = "Role name already exists";
                }
                // unhandled exception
                else if (iResultValue == -1)
                {
                    result.Result = false;
                }
            }
            catch (Exception ex)
            {
                result.Result        = false;
                result.ReturnMessage = ex.Message;
            }

            return(result);
        }
Beispiel #5
0
        public async Task <IActionResult> Add(RoleRequest roleDto)
        {
            try
            {
                if (roleDto == null)
                {
                    return(BadRequest());
                }
                var roleModel = new RolePermissionModel()
                {
                    Name        = roleDto.Name,
                    Permissions = roleDto.Permissions,
                    RoleId      = roleDto.RoleId
                };
                var role = await _roleService.AddRole(roleModel);

                if (role != null)
                {
                    var roleResponseDto = new RoleResponse {
                        Name = role.Name, Permissions = role.Permissions, RoleId = role.RoleId
                    };
                    return(CreatedAtAction(nameof(GetRole), new { id = role.RoleId }, roleResponseDto));
                }
                return(StatusCode(StatusCodes.Status404NotFound));
            }
            catch
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Beispiel #6
0
        public async Task Seed()
        {
            var roles = await _roleService.GetAllRoles();

            if (!roles.Any())
            {
                var roleNames = new[]
                {
                    RoleHelper.Administrator,
                    RoleHelper.Moderator,
                    RoleHelper.User
                };

                foreach (var roleName in roleNames)
                {
                    await _roleService.AddRole(roleName);
                }
            }

            var users = await _applicationUserService.GetAllUsers();

            if (!users.Any())
            {
                await _authService.Register("*****@*****.**", "admin", signIn : false, roleName : RoleHelper.Administrator);
            }

            await _unitOfWork.Save();
        }
        public async Task <IdentityResult> CreateAsync(Role role, CancellationToken cancellationToken)
        {
            var added = await _db.AddRole(role).ConfigureAwait(false);

            return(added
                ? IdentityResult.Success
                : IdentityResultError.CannotInsertRole(role.Name));
        }
Beispiel #8
0
 public async Task <IActionResult> AddRole(string name)
 {
     if (name != null)
     {
         await roleService.AddRole(name);
     }
     return(RedirectToAction("GetRoles"));
 }
Beispiel #9
0
 public void AddRole(Role role)
 {
     try {
         _roleService.AddRole(role);
     } catch (Exception ex) {
         Log.Write(ex);
         throw;
     }
 }
Beispiel #10
0
        public override void CreateRole(string roleName)
        {
            var newRole = new Entity.Role()
            {
                RoleName = roleName
            };

            RoleService.AddRole(newRole);
        }
Beispiel #11
0
        public async Task <IActionResult> AddRole(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(BadRequest());
            }
            await roleService.AddRole(name);

            return(RedirectToAction("GetRoles"));
        }
Beispiel #12
0
        public async Task <IActionResult> AddRole([FromBody] RoleViewModel viewModel)
        {
            var result = await _roleService.AddRole(viewModel);

            if (!string.IsNullOrEmpty(result))
            {
                return(this.BadRequestResult(result));
            }
            return(Ok());
        }
Beispiel #13
0
        public ActionResult Create(Role role)
        {
            if (ModelState.IsValid)//testing(role))//
            {
                _roleService.AddRole(role);
                return(Json(new { success = true }));
            }

            ViewBag.UserProfileID = new SelectList(_roleService.GetAllRole(), "RoleID", "RoleID", role.RoleID);
            return(PartialView(BindRoleModel(role)));
        }
Beispiel #14
0
        public JsonResult SaveRole(Role role)
        {
            var result = 0;
            var flag   = (role.ID != 0 ? RoleService.UpdateRole(role) : RoleService.AddRole(role)) > 0;

            if (flag)
            {
                result = 1;
                //RedirectToAction("List");
            }
            return(Json(result));
        }
Beispiel #15
0
        public void AddRoleTest()
        {
            var role = new Role
            {
                RoleName   = "营销111",
                IsAdmin    = false,
                IsValid    = true,
                CreateDate = DateTime.Now
            };

            _roleService.AddRole(role);
        }
Beispiel #16
0
        public ActionResult Add(RolesAddModel model)
        {
            AddRoleRequest request = new AddRoleRequest
            {
                RolesUpdateModel = model,
                Customer         = Customer.OriginalCustomer
            };

            _roleService.AddRole(request);

            return(RedirectToAction("index")
                   .AndAlert(AlertType.Success, "Success.", "Role added successfully."));
        }
 public void AddNewButtonClick()
 {
     try
     {
         _service.AddRole(_viewModel.NewDescription);
         _viewModel.RolesGridDataBind();
         _viewModel.NewDescription = string.Empty;
     }
     catch (Exception ex)
     {
         BaseException.HandleException(ex, false);
         _viewModel.ShowErrorMessage(ex.Message);
     }
 }
        public async Task <IActionResult> AddRole(RoleDto roleDto)
        {
            try
            {
                var role = _mapper.Map <Role>(roleDto);
                _roleService.AddRole(role);
                await _unitOfWork.Save();

                return(Ok(role));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Beispiel #19
0
 public IActionResult AddRole([FromBody] RoleVm r)
 {
     if (r != null)
     {
         Role role = new Role();
         role.RoleName    = r.RoleName;
         role.Description = r.Description;
         _service.AddRole(role);
         return(new OkObjectResult(r));
     }
     else
     {
         return(NotFound());
     }
 }
Beispiel #20
0
        public IActionResult AddRole([FromBody] RoleModel model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                throw new InvalidModelStateException(ModelState);
            }

            _roleService.AddRole(model);
            return(Ok(true));
        }
Beispiel #21
0
        public async Task <ActionResult <Role> > Create([FromBody] Role role)
        {
            try
            {
                var roleSaved = await _service.AddRole(role);

                _log.LogInformation($"Returning {role.Name}");
                return(Ok(role));
            }
            catch (Exception ex)
            {
                _log.LogError($"Something went wrong: {ex}");
                return(StatusCode(500, ex));
            }
        }
Beispiel #22
0
        public ActionResult Create(ViewModels.Role model)
        {
            if (ModelState.IsValid)
            {
                var dbModel = new Domain.Role();
                dbModel.InjectFrom(model);
                //roleRepository.Add(dbModel);
                roleService.AddRole(dbModel);
                //transform the object
                //unitOfWork.Commit();
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Beispiel #23
0
        public IActionResult Add(RoleInput param)
        {
            var response = new ReponseOutPut();

            response.Code    = "role_add_success";
            response.Message = "新增角色成功";
            if (!ModelState.IsValid)
            {
                response.Status = ReutnStatus.Error;
                response.Code   = "param_vaild_error";

                var errorProperty = ModelState.Values.First(m => m.ValidationState == ModelValidationState.Invalid);
                response.Message = errorProperty.Errors.First().ErrorMessage;//验证不通过的 //全局配置一个验证不通过就不在验证了,只存在一个错误信息

                return(new JsonResult(JsonConvert.SerializeObject(response)));
            }

            // 检查用户名是否重复
            var isExistUserName = _roleService.ExistRoleName(param.RoleName);

            if (isExistUserName)
            {
                response.Status  = ReutnStatus.Error;
                response.Code    = "rolename_is_exist";
                response.Message = "角色名称已经存在";
                return(new JsonResult(JsonConvert.SerializeObject(response)));
            }

            SysRole role = _mapper.Map <RoleInput, SysRole>(param);

            role.CreateBy         = _context.Admin.Id;
            role.CreatebyName     = _context.Admin.UserName;
            role.CreateDate       = DateTime.Now;
            role.LastUpdateBy     = role.CreateBy;
            role.LastUpdateByName = role.CreatebyName;
            role.LastUpdateDate   = role.CreateDate;

            var result = _roleService.AddRole(role, param.AdminIds);

            if (result < 0)
            {
                response.Status  = ReutnStatus.Error;
                response.Code    = "role_add_error";
                response.Message = "新增角色失败";
            }

            return(new JsonResult(JsonConvert.SerializeObject(response)));
        }
Beispiel #24
0
        public async Task <IActionResult> AddRole([FromBody] Role role)
        {
            if (role == null)
            {
                return(BadRequest());
            }

            var stg = await _roleService.AddRole(role);

            if (!string.IsNullOrEmpty(stg))
            {
                return(NotFound(stg));
            }

            return(Created("role/add", role));
        }
        public ActionResult AddRole(RoleModel model)
        {
            bool flag = false;

            try
            {
                model.RoleId = Guid.NewGuid();
                _IRoleService.AddRole(model);
                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
            }

            return(Json(flag, JsonRequestBehavior.AllowGet));
        }
Beispiel #26
0
        public RoleVO AddRole(RoleVO roleVO)
        {
            if (!ModelState.IsValid)
            {
                roleVO.Message = "請填寫必填欄位";
            }
            else
            {
                var result = _roleService.AddRole(roleVO);

                if (!string.IsNullOrEmpty(result))
                {
                    roleVO.Message = result;
                }
            }
            return(roleVO);
        }
Beispiel #27
0
        public IHttpActionResult PostRole(RoleDTO roleDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            _roleService.AddRole(new Role
            {
                Name  = roleDto.Name,
                Users = roleDto.UsersId.Select(id => _userService.GetUser(id)).ToList()
            });
            _roleService.Save();

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #28
0
        public async Task <IActionResult> New(NewRoleRequest newRoleRequest)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            Result <string> result = await _roleService.AddRole(newRoleRequest, GetUserId());

            if (result.Failure)
            {
                ModelState.AddErrors(result.Errors);

                return(View(new NewRoleViewModel(StatusAlertViewExtension.Get(result))));
            }

            return(RedirectToAction(nameof(Details), new { id = result.Value }));
        }
        /// <summary>
        /// 添加角色+角色成员
        /// </summary>
        /// <returns></returns>
        public IActionResult AddRole(AddRoleViewModel addRole)
        {
            IBaseService <SysRole, Guid> baseService = _roleService as IBaseService <SysRole, Guid>;
            var isExists = baseService.Exists(x => x.Name == addRole.RoleId.Trim());

            if (isExists)
            {
                return(FailedMsg("该角色名已存在"));
            }
            SysRole sysRole = new SysRole
            {
                Id             = Guid.NewGuid(),
                Name           = addRole.RoleId,
                NormalizedName = addRole.RoleInfo,
                State          = addRole.RoleState,
                CreateUserId   = UserInfoSession.UserId,
                CreationTime   = DateTime.Now
            };
            List <UserRole> userRoles = new List <UserRole>();
            var             userStr   = addRole.RoleUsers;
            var             userArray = userStr.Split(',');
            var             ids       = userArray.Select(x => x.Substring(0, x.IndexOf('(')));
            var             userList  = (_userService.GetUIdList(ids.ToList()));

            foreach (var item in userList)
            {
                userRoles.Add(new UserRole
                {
                    Id     = Guid.NewGuid(),
                    RoleId = sysRole.Id,
                    UserId = item
                });
            }

            var flag = _roleService.AddRole(sysRole, userRoles);

            if (flag)
            {
                return(AddSuccessMsg());
            }
            return(FailedMsg("添加角色失败"));
        }
        public async Task <IActionResult> Create(RoleViewModel newRole)
        {
            var role = new Role
            {
                Name        = newRole.Name,
                Description = newRole.Description,
                CreatedOn   = DateTime.Now,
                UpdatedOn   = DateTime.Now,
                IsActive    = newRole.Active,
            };
            var success = await roleService.AddRole(role, newRole.Menus);

            if (success)
            {
                TempData["SuccessMessage"] = $"Role {newRole.Name} created Succesfully";
                return(RedirectToAction(nameof(Index)));
            }

            TempData["ErrorMessage"] = $"Unable to create Role {newRole.Name}";
            return(RedirectToAction(nameof(Index)));
        }