Beispiel #1
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     if (!this.Validate()) return;
     var role = this.CollectData<FullRoleInfo>();
     role.Authority = new List<AuthorityNodeForCheck>();
     for(int i = 0; i < chkList.Items.Count; i++)
     {
         if (chkList.GetItemChecked(i))
         {
             var auth = chkList.Items[i] as AuthorityNodeForCheck;
             auth.Checked = true;
             role.Authority.Add(auth);
         }
     }
     role.Menus = new List<SDK.Menu>();
     for (int i = 0; i < chkMenu.Items.Count; i++)
     {
         if (chkMenu.GetItemChecked(i))
         {
             var menu = chkMenu.Items[i] as SDK.Menu;
             role.Menus.Add(menu);
         }
     }
     AddRoleRequest request = new AddRoleRequest();
     request.token = Token;
     request.form = role;
     SDKSync<AddModelResponse>.CreateInstance(this).Execute(request, Save_Callback);
 }
Beispiel #2
0
        public async Task <ActionResult <string> > AddRole([FromBody] AddRoleRequest addRoleRequest)
        {
            if (!_addRoleRequestValidator.TryValidateAddRoleRequest(addRoleRequest, out string validationError))
            {
                Log.Warning($"Create role called with invalid input. Validation error: {validationError}");
                return(BadRequest(validationError));
            }

            var updatedMapRolesYaml = string.Empty;

            try
            {
                await _configMapService.AddRole(
                    addRoleRequest.RoleName,
                    addRoleRequest.RoleArn
                    );
            }
            catch (Exception ex)
            {
                Log.Error($"An error occured trying to create the role mapping: {ex.Message}");
                return(StatusCode(StatusCodes.Status500InternalServerError, $"An error occured trying to create the role mapping: {ex.Message}"));
            }

            return(Ok(updatedMapRolesYaml));
        }
Beispiel #3
0
        public IHttpActionResult AddRole([FromBody] AddRoleRequest request)
        {
            try
            {
                request.ValidateNotNull();

                int userTenantId = (int)ActionContext.Request.Properties["UserTenantId"];

                RoleDomain roleDomain = new RoleDomain()
                {
                    Name              = request.Name,
                    IsActive          = request.IsActive,
                    ManipulationLogId = request.ManipulationLogId,
                    TenantId          = userTenantId
                };

                return(Ok(new AddRoleResponse()
                {
                    Data = _roleManipulation.AddRole(roleDomain),
                    Success = Common.Enumerations.ResponseStatus.Succeeded
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Beispiel #4
0
        public ActionResult Add(AddRoleRequest request)
        {
            var flag = false;
            var msg  = string.Empty;

            if (request == null)
            {
                request = new AddRoleRequest();
            }

            using (var factory = new ChannelFactory <IRightsRoleService>("*"))
            {
                var client = factory.CreateChannel();
                var rs     = client.AddRole(request, loginInfo);
                if (rs.ReturnCode == ReturnCodeType.Success && rs.Content == true)
                {
                    flag = true;
                    msg  = "新增成功!";
                }
                else
                {
                    msg = rs.Message.IsNullOrEmpty() ? "新增失败!" : rs.Message;
                }
            }

            return(Json(new { success = flag, msg = msg }, JsonRequestBehavior.AllowGet));
        }
Beispiel #5
0
        public bool TryValidateAddRoleRequest(AddRoleRequest request, out string validationError)
        {
            validationError = string.Empty;

            if (string.IsNullOrWhiteSpace(request.RoleName))
            {
                validationError = "Name is invalid.";
                return(false);
            }

            // Role name 64 char max.
            if (request.RoleName.Length > 63)
            {
                validationError = "Name is invalid. A maximum of 64 characters is allowed.";
                return(false);
            }

            // Only alphanumeric and '+=,.@-_' allowed.
            var allowedCharactersPattern = "^[a-zA-Z0-9!@#$&()\\-`.+,/\"]*$";
            var match = Regex.Match(request.RoleName, allowedCharactersPattern, RegexOptions.IgnoreCase);

            if (!match.Success)
            {
                validationError = "Name is invalid. Only alphanumeric and '+=,.@-_' is allowed.";
                return(false);
            }

            return(true);
        }
        public async Task <IActionResult> AddRole([FromBody] AddRoleRequest model)
        {
            if (!ModelState.IsValid)
            {
                return(Ok(ModelState));
            }
            IdentityResult roleResult;

            if (ModelState.IsValid)
            {
                ApplicationRole applicationRole = new ApplicationRole
                {
                    Name        = model.RoleName,
                    CreatedDate = DateTime.UtcNow,
                    Description = model.Description,
                    IpAddress   = Request.HttpContext.Connection.RemoteIpAddress.ToString()
                };
                roleResult = await _roleservice.CreateAsync(applicationRole);

                if (roleResult.Succeeded)
                {
                    return(Ok("Role SuccessFully Added...."));
                }
            }
            return(Ok("UnExpected Error"));
        }
Beispiel #7
0
        public void AddRole(AddRoleRequest request)
        {
            var role = new Role(request.Customer, request.RolesUpdateModel.Name, userType: request.RolesUpdateModel.UserType);

            _roleRepository.Add(role);
            _unitOfWork.Commit();
        }
Beispiel #8
0
        public BaseResponse AddRole(AddRoleRequest request)
        {
            var roleName  = string.IsNullOrWhiteSpace(request.RoleName) ? string.Empty : request.RoleName;
            var baseRoles = (request.BaseRoles ?? Enumerable.Empty <string>()).ToArray();

            IdentityRepository.AddRoleInRoles(roleName, baseRoles);
            return(BaseResponse.Ok());
        }
Beispiel #9
0
 public ActionResult UpdateRole(AddRoleRequest request)
 {
     try {
         this._roleService.UpdateRole(request);
         return(Content("修改成功!"));
     }
     catch (Exception ex) {
         return(Content("修改失败:" + ex.Message));
     }
 }
Beispiel #10
0
        public async Task <IActionResult> Create(AddRoleRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(View(request));
            }
            var role = new IdentityRole(request.RoleName);
            await _roleManager.CreateAsync(role);

            return(View());
        }
Beispiel #11
0
        public RoleView AddRole(AddRoleRequest request)
        {
            Role model = this._roleRepository.FindBy(request.ParentId);

            if (model == null)
            {
                throw new EntityIsInvalidException <string>(request.ParentId.ToString());
            }
            model.AddChild(request.Name, request.Description);
            this._uow.Commit();
            return(model.ConvertToRoleView());
        }
Beispiel #12
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 async Task <IActionResult> Post([FromBody] RoleDto rol)
        {
            try
            {
                var rolrequest = new AddRoleRequest(rol);
                var result     = await _mediator.Send(rolrequest);

                return(_presenter.GetSingleRol(result));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #14
0
        public async Task <IActionResult> Add([FromBody] AddRoleRequest request)
        {
            try
            {
                var response = await _serviceProvider.HandlerAsync(request);

                return(new JsonResult(response));
            }
            catch (Exception ex)
            {
                return(new JsonResult(new ResponseBase()
                {
                    Result = -1, ResultInfo = ex.Message
                }));
            }
        }
        public void TryValidateAddRoleRequest_GivenInvalidCharacter_DoesNotValidate()
        {
            // Arrange
            var sut     = new AddRoleRequestValidator();
            var request = new AddRoleRequest
            {
                RoleName = "å"
            };
            var validationErrors = string.Empty;

            // Act
            var validRequest = sut.TryValidateAddRoleRequest(request, out validationErrors);

            // Assert
            Assert.False(validRequest);
            Assert.NotEqual(string.Empty, validationErrors);
        }
Beispiel #16
0
        public IActionResult Role(AddRoleRequest request)
        {
            ValidateEntity <AddRoleRequest>(request);

            Entities.Role role = new Entities.Role()
            {
                Id   = Guid.NewGuid(),
                Name = request.Name
            };

            Business.Role.Add(role);

            return(GetOutput(new AddRoleResponse()
            {
                Role = role
            }));
        }
        public void TryValidateAddRoleRequest_GivenValidInput_Validates()
        {
            // Arrange
            var sut     = new AddRoleRequestValidator();
            var request = new AddRoleRequest
            {
                RoleName = "MyRole"
            };
            var validationErrors = string.Empty;

            // Act
            var validRequest = sut.TryValidateAddRoleRequest(request, out validationErrors);

            // Assert
            Assert.True(validRequest);
            Assert.Equal(string.Empty, validationErrors);
        }
        public void TryValidateAddRoleRequest_GivenTooLongRoleName_DoesNotValidate()
        {
            // Arrange
            var sut = new AddRoleRequestValidator();
            var roleNameLongerThan64Characters = new string('*', 65);
            var request = new AddRoleRequest
            {
                RoleName = roleNameLongerThan64Characters
            };
            var validationErrors = string.Empty;

            // Act
            var validRequest = sut.TryValidateAddRoleRequest(request, out validationErrors);

            // Assert
            Assert.False(validRequest);
            Assert.NotEqual(string.Empty, validationErrors);
        }
Beispiel #19
0
        public async Task <IActionResult> CreateAdmin([FromBody] AddRoleRequest request)
        {
            var user = await _dataContext.Users.FirstOrDefaultAsync(x => x.UserName == request.UserName);

            if (user == null)
            {
                return(BadRequest("User not found"));
            }

            var created = await _userManager.AddToRoleAsync(user, request.RoleName);


            if (created != null)
            {
                await _dataContext.SaveChangesAsync();

                return(Ok("Now this user is Admin"));
            }
            return(BadRequest("Something was wrong"));
        }
Beispiel #20
0
        public void T02_RolesModifications()
        {
            var rolesUpdateModel = new RolesUpdateModel
            {
                Name     = "CustomRole",
                UserType = UserType.SystemUser
            };

            var role = new AddRoleRequest
            {
                Customer         = _customer,
                RolesUpdateModel = rolesUpdateModel
            };

            _roleService.AddRole(role);

            var roleSummury = _roleService.RolesList(_customer.Id).Roles.FirstOrDefault(t => t.Name == "CustomRole");

            Assert.IsNotNull(roleSummury, "Can not add role");

            var roleResponse = _roleService.Get(new GetRoleRequest {
                Id = roleSummury.Id
            });

            rolesUpdateModel.Name = "CustomRoleReName";
            _roleService.UpdateRole(new UpdateRoleRequest
            {
                Id = roleResponse.RolesUpdateModel.Id,
                RolesUpdateModel = rolesUpdateModel
            });

            roleSummury = _roleService.RolesList(_customer.Id).Roles.FirstOrDefault(t => t.Name == "CustomRoleReName");
            Assert.IsNotNull(roleSummury, "Can not edit role");

            _roleService.DeleteRole(new DeleteRoleRequest {
                Id = roleSummury.Id
            });
            roleSummury = _roleService.RolesList(_customer.Id).Roles.FirstOrDefault(t => t.Name == "CustomRoleReName");
            Assert.IsNull(roleSummury, "Can not delete role");
        }
Beispiel #21
0
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="loginInfo"></param>
        /// <returns></returns>
        public ServiceResult <bool> AddRole(AddRoleRequest request, TRightsUser loginInfo)
        {
            //需要检查是否已存在相同名称的角色
            var result = new ServiceResult <bool>
            {
                ReturnCode = ReturnCodeType.Error
            };

            var role = _roleDao.GetRoleByName(request.Name);

            if (role != null)
            {
                result.Message = "已存在相同名称的角色!";
                return(result);
            }

            var currentTime = DateTime.Now;
            var item        = new TRightsRole
            {
                Name            = request.Name,
                Description     = request.Description,
                OrganizationId  = request.OrgId,
                CreatedBy       = loginInfo.Id,
                CreatedTime     = currentTime,
                LastUpdatedBy   = loginInfo.Id,
                LastUpdatedTime = currentTime
            };
            var rs = _roleDao.Insert(item);

            if (rs == true)
            {
                result.ReturnCode = ReturnCodeType.Success;
                result.Content    = true;
            }

            return(result);
        }
Beispiel #22
0
        public ActionResult Add(AddRoleRequest request)
        {
            var flag = false;
            var msg  = string.Empty;

            if (request == null)
            {
                request = new AddRoleRequest();
            }

            var rs = _roleService.AddRole(request, loginInfo);

            if (rs.ReturnCode == ReturnCodeType.Success && rs.Content == true)
            {
                flag = true;
                msg  = "新增成功!";
            }
            else
            {
                msg = rs.Message.IsNullOrEmpty() ? "新增失败!" : rs.Message;
            }

            return(Json(new { success = flag, msg = msg }, JsonRequestBehavior.AllowGet));
        }
Beispiel #23
0
 public Task <DeleteInRoomGoodsResponse> AddRoleAsync(AddRoleRequest request)
 {
     return(WeChatMiniProgramApiRequester.RequestAsync <DeleteInRoomGoodsResponse>(AddRoleUrl,
                                                                                   HttpMethod.Post,
                                                                                   request));
 }
        public static bool AddRole(string serviceName, string deploymentName, AddRoleRequest requestObject)
        {
            bool result = false;
            string version = VMOperations.RoleVersionConstants.VER2012;
            string uriFormat = AzureFrameWork.Util.UrlConstants.AddRole;
            //Uri uri = new Uri(String.Format(uriFormat, subscriberID, "testvmdns", "testvmsep12"));
            Uri uri = new Uri(String.Format(uriFormat, subscriberID, serviceName, deploymentName));

            string requestObject1 = @"<PersistentVMRole xmlns=""http://schemas.microsoft.com/windowsazure"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
               <RoleName>test1strole</RoleName>
               <RoleType>PersistentVMRole</RoleType>
            <ConfigurationSets>
            <ConfigurationSet>
                <ConfigurationSetType>WindowsProvisioningConfiguration</ConfigurationSetType>
                     <ComputerName>mytestcomputer</ComputerName>
                     <AdminPassword>CloudTeam1</AdminPassword>
                     <ResetPasswordOnFirstLogon>false</ResetPasswordOnFirstLogon>
                     <EnableAutomaticUpdates>true</EnableAutomaticUpdates>
                     <TimeZone>Pacific Standard Time</TimeZone>
                     <DomainJoin>
                        <Credentials>
                           <Domain>cloudapp.net</Domain>
                           <Username>testuser</Username>
                           <Password>testpassword</Password>
                        </Credentials>
                        <JoinDomain>NULL</JoinDomain>
                        <MachineObjectOU>MyOu</MachineObjectOU>
                     </DomainJoin>
                     <StoredCertificateSettings>
                        <CertificateSetting>
                           <StoreLocation>LocalMachine</StoreLocation>
                           <StoreName>My</StoreName>
                           <Thumbprint>275FE85811F5C40D33B395AC225BFDEBA0CBD7BA</Thumbprint>
                        </CertificateSetting>
                     </StoredCertificateSettings>
             </ConfigurationSet>
            </ConfigurationSets>
                <AvailabilitySetName>NULL</AvailabilitySetName>
               <DataVirtualHardDisks/>
                <OSVirtualHardDisk>
                    <HostCaching>ReadOnly</HostCaching>
                    <DiskLabel/>
                    <DiskName>mydisk</DiskName>
                    <MediaLink></MediaLink>
                    <SourceImageName>MSFT__Win2K8R2SP1-Datacenter-201208.01-en.us-30GB.vhd</SourceImageName>
                </OSVirtualHardDisk>
                <RoleSize>ExtraSmall</RoleSize>
            </PersistentVMRole>";

            //string requestObject1 = Util.CreateXml(requestObject);
            try
            {
                HttpWebRequest request = AzureFrameWork.Util.CreateWebRequest(uri, version, APIVersions.MethodType.POST.ToString(), requestObject1);
                //HttpWebRequest request = AzureFrameWork.Util.CreateWebRequest(uri, version, APIVersions.MethodType.POST.ToString(), requestObject);

                XDocument responseBody = null;

                HttpWebResponse response;
                TrustAllCert trust = new TrustAllCert();
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(trust.OnValidationCallback);
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    //request.BeginGetResponse(new AsyncCallback(FinishWebrequest), request);
                }
                catch (WebException ex)
                {
                    // GetResponse throws a WebException for 400 and 500 status codes
                    response = (HttpWebResponse)ex.Response;
                }
                HttpStatusCode statusCode = response.StatusCode;
                if (response.ContentLength > 0)
                {
                    using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
                    {
                        responseBody = XDocument.Load(reader);
                    }
                }
                response.Close();

                if (response.StatusCode == HttpStatusCode.Created)
                {
                    result = true;
                }
                else
                {
                    //TODO: Need to write the logic
                    // Checking the conflict option in git
                }
            }
            catch (WebException ex)
            {
                throw ex.InnerException;
            }
            finally
            {

            }

            return result;
        }
        public HttpResponseMessage AddRole([FromUri] AddRoleRequest request)
        {
            RoleView model = this._roleService.AddRole(request);

            return(ToJson(model));
        }
Beispiel #26
0
 public Task <HttpResponseMessage> AddRole([FromBody] AddRoleRequest request)
 {
     return(ExecuteAction(request, Repository.AddRole));
 }
 public bool TryValidateAddRoleRequest(AddRoleRequest request, out string validationError)
 {
     validationError = String.Empty;
     return(true);
 }