예제 #1
0
        public override async Task <DeleteRoleResponse> DeleteRole(DeleteRoleRequest request, ServerCallContext context)
        {
            if (!await _roleService.RoleExistsAsync(request.RoleName))
            {
                throw context.NotFoundRpcException($"The role '{request.RoleName}' wasn't found.");
            }

            var role = await _roleService.FindByNameAsync(request.RoleName);

            var result = await _roleService.DeleteAsync(role);

            if (result.Succeeded)
            {
                var detail = $"The role '{role.Name}' as been deleted. (roleId=${role.Id})";

                var response = new DeleteRoleResponse
                {
                    Role = new RoleDto
                    {
                        Id   = role.Id.ToString(),
                        Name = role.Name
                    }
                };

                return(context.Ok(response, detail));
            }

            throw context.FailedPreconditionRpcException(result, $"Failed to delete the role '{role.Name}'. (roleId=${role.Id})");
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            DeleteRoleResponse response = new DeleteRoleResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("DeleteRoleResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
                    }
                }
            }

            return(response);
        }
예제 #3
0
        private static void DeleteRole(String RoleName)
        {
            if (String.IsNullOrEmpty(Token))
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, iamconfig);
            }
            else
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, Token, iamconfig);
            }

            DeleteRoleRequest Req = new DeleteRoleRequest();

            Req.RoleName = RoleName;

            try
            {
                DeleteRoleResponse response = stsClient.DeleteRole(Req);
                Console.WriteLine("Role Deleted");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured while creating user. " + ex.ToString());
            }
        }
        public static DeleteRoleResponse Unmarshall(UnmarshallerContext context)
        {
            DeleteRoleResponse deleteRoleResponse = new DeleteRoleResponse();

            deleteRoleResponse.HttpResponse = context.HttpResponse;
            deleteRoleResponse.RequestId    = context.StringValue("DeleteRole.RequestId");

            return(deleteRoleResponse);
        }
 public DeleteRoleResponse Delete(Guid id)
 {
     ValidationForDeleting(id);
     using (IUnitOfWork uow = new App.Common.Data.UnitOfWork(new App.Context.AppDbContext(IOMode.Write)))
     {
         IRoleRepository    repository     = IoC.Container.Resolve <IRoleRepository>(uow);
         DeleteRoleResponse deleteResponse = repository.GetById <DeleteRoleResponse>(id.ToString());
         repository.Delete(id.ToString());
         uow.Commit();
         return(deleteResponse);
     }
 }
예제 #6
0
 public DeleteRoleResponse Delete(Guid id)
 {
     this.ValidateDeleteRequest(id);
     using (IUnitOfWork uow = new App.Common.Data.UnitOfWork(RepositoryType.MSSQL))
     {
         IRoleRepository    repository     = IoC.Container.Resolve <IRoleRepository>(uow);
         DeleteRoleResponse deleteResponse = repository.GetById <DeleteRoleResponse>(id.ToString());
         repository.Delete(id);
         uow.Commit();
         return(deleteResponse);
     }
 }
        public static DeleteRoleResponse WrapDeleteRole(string roleId, string roleName, int statusCode)
        {
            DeleteRoleResponse responseMessage =
                new DeleteRoleResponse()
            {
                RoleId      = roleId,
                RoleName    = roleName,
                StatusCode  = statusCode,
                Description = "Role successfully deleted",
                Error       = "no_error",
                Code        = "role_successfully_deleted"
            };

            return(responseMessage);
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            DeleteRoleResponse response = new DeleteRoleResponse();

            while (context.Read())
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
                    }
                }
            }


            return(response);
        }
        private static void UnmarshallResult(XmlUnmarshallerContext context, DeleteRoleResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                }
            }

            return;
        }
예제 #10
0
        public ActionResult Delete(Guid id)
        {
            DeleteRoleResponse response = _roleService.DeleteRole(new DeleteRoleRequest()
            {
                Id = id
            });

            if (response.HasError)
            {
                return(HttpNotFound());
            }

            if (response.SystemRole)
            {
                return(RedirectToAction("index")
                       .AndAlert(AlertType.Danger, "Invalid Operation.", "System roles cannot be deleted."));
            }

            return(RedirectToAction("index")
                   .AndAlert(AlertType.Warning, "Deleted.", "The role was deleted successfully."));
        }
예제 #11
0
        public async Task <DeleteRoleResponse> DeleteRole(int roleID)
        {
            var response = new DeleteRoleResponse();

            try
            {
                var role = await _rolesContext.Roles.FirstAsync(x => x.Id == roleID);

                _rolesContext.Roles.Remove(role);
                _rolesContext.Entry(role).State = EntityState.Deleted;
                await _rolesContext.SaveChangesAsync();

                response.OperationSucceded = true;
                response.Message           = "Role removed successfully";
            }
            catch (Exception)
            {
                response.OperationSucceded = false;
            }

            return(response);
        }
예제 #12
0
        public DeleteRoleResponse DeleteRole(DeleteRoleRequest request)
        {
            DeleteRoleResponse response = new DeleteRoleResponse();

            Role role = _roleRepository.Get(request.Id);

            if (role == null)
            {
                response.HasError = true;
                return(response);
            }

            if (role.SystemRole)
            {
                response.SystemRole = true;
                return(response);
            }
            _roleRepository.Delete(role);
            _unitOfWork.Commit();

            return(response);
        }
예제 #13
0
        // DELETE api/gateway/deleterole
        public async Task <IActionResult> DeleteRole(DeleteRoleViewModel model, [FromHeader] string authorization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(model));
            }

            HttpParameters httpParameters = HttpParametersService
                                            .GetHttpParameters(
                model,
                ConfigHelper.AppSetting(Constants.ServerUrls, Constants.DeleteRole),
                HttpMethod.Delete,
                string.Empty,
                authorization
                );

            DeleteRoleResponse deleteRoleResult = await _gWService.PostTo <DeleteRoleResponse>(httpParameters);


            if (deleteRoleResult.StatusCode == 404)
            {
                return(await ResponseService.GetResponse <NotFoundObjectResult, DeleteRoleResponse>(deleteRoleResult, ModelState));
            }
            else if (deleteRoleResult.StatusCode == 409)
            {
                return(await ResponseService.GetResponse <ConflictObjectResult, DeleteRoleResponse>(deleteRoleResult, ModelState));
            }
            else if (deleteRoleResult.StatusCode == 401)
            {
                return(await ResponseService.GetResponse <UnauthorizedObjectResult, DeleteRoleResponse>(deleteRoleResult, ModelState));
            }
            else if (deleteRoleResult.StatusCode != 200)
            {
                return(await ResponseService.GetResponse <BadRequestObjectResult, DeleteRoleResponse>(deleteRoleResult, ModelState));
            }

            return(new OkObjectResult(deleteRoleResult));
        }
예제 #14
0
        public static void Test(string identityProvider)
        {
            // Login with credentials to create the role
            // credentials are defined in app.config
            var    iamClient          = new AmazonIdentityManagementServiceClient();
            string providerURL        = null,
                   providerAppIdName  = null,
                   providerUserIdName = null,
                   providerAppId      = null;


            switch (identityProvider)
            {
            case "Facebook":
                providerURL        = "graph.facebook.com";
                providerAppIdName  = "app_id";
                providerUserIdName = "id";
                break;

            case "Google":
                providerURL        = "accounts.google.com";
                providerAppIdName  = "aud";
                providerUserIdName = "sub";
                break;

            case "Amazon":
                providerURL        = "www.amazon.com";
                providerAppIdName  = "app_id";
                providerUserIdName = "user_id";
                break;
            }

            //identity provider specific AppId is loaded from app.config (e.g)
            //  FacebookProviderAppId. GoogleProviderAppId, AmazonProviderAppId
            providerAppId = ConfigurationManager.AppSettings[identityProvider +
                                                             "ProviderAppId"];

            // Since the string is passed to String.Format, '{' & '}' has to be escaped.
            // Policy document specifies who can invoke AssumeRoleWithWebIdentity
            string trustPolicyTemplate = @"{{
                  ""Version"": ""2012-10-17"",
                  ""Statement"": [
                        {{
                              ""Effect"": ""Allow"",
                              ""Principal"": {{ ""Federated"": ""{1}"" }},
                              ""Action"": ""sts:AssumeRoleWithWebIdentity"",
                              ""Condition"": {{
                                    ""StringEquals"": {{""{1}:{2}"": ""{3}""}}
                              }}
                        }}
                  ]
                }}";

            // Defines what permissions to grant when AssumeRoleWithWebIdentity is called
            string accessPolicyTemplate = @"{{
                    ""Version"": ""2012-10-17"",
                    ""Statement"": [
                    {{
                        ""Effect"":""Allow"",
                        ""Action"":[""s3:GetObject"", ""s3:PutObject"", ""s3:DeleteObject""],
                        ""Resource"": [
                                ""arn:aws:s3:::federationtestbucket/{0}/${{{1}:{4}}}"",
                                ""arn:aws:s3:::federationtestbucket/{0}/${{{1}:{4}}}/*""
                        ]
                    }}
                    ]
                }}";

            // Create Trust policy
            CreateRoleRequest createRoleRequest = new CreateRoleRequest
            {
                RoleName = "federationtestrole",
                AssumeRolePolicyDocument = string.Format(trustPolicyTemplate,
                                                         identityProvider,
                                                         providerURL,
                                                         providerAppIdName,
                                                         providerAppId)
            };

            Console.WriteLine("\nTrust Policy Document:\n{0}\n",
                              createRoleRequest.AssumeRolePolicyDocument);
            CreateRoleResponse createRoleResponse = iamClient.CreateRole(createRoleRequest);

            // Create Access policy (Permissions)
            PutRolePolicyRequest putRolePolicyRequest = new PutRolePolicyRequest
            {
                PolicyName     = "federationtestrole-rolepolicy",
                RoleName       = "federationtestrole",
                PolicyDocument = string.Format(accessPolicyTemplate,
                                               identityProvider,
                                               providerURL,
                                               providerAppIdName,
                                               providerAppId,
                                               providerUserIdName)
            };

            Console.WriteLine("\nAccess Policy Document (Permissions):\n{0}\n",
                              putRolePolicyRequest.PolicyDocument);
            PutRolePolicyResponse putRolePolicyResponse = iamClient.PutRolePolicy(
                putRolePolicyRequest);

            // Sleep for the policy to replicate
            System.Threading.Thread.Sleep(5000);
            AmazonS3Config config = new AmazonS3Config
            {
                ServiceURL     = "s3.amazonaws.com",
                RegionEndpoint = Amazon.RegionEndpoint.USEast1
            };

            Federation federationTest = new Federation();
            AssumeRoleWithWebIdentityResponse assumeRoleWithWebIdentityResponse = null;

            switch (identityProvider)
            {
            case "Facebook":
                assumeRoleWithWebIdentityResponse =
                    federationTest.GetTemporaryCredentialUsingFacebook(
                        providerAppId,
                        createRoleResponse.Role.Arn);
                break;

            case "Google":
                assumeRoleWithWebIdentityResponse =
                    federationTest.GetTemporaryCredentialUsingGoogle(
                        providerAppId,
                        createRoleResponse.Role.Arn);

                //Uncomment to perform two step process
                //assumeRoleWithWebIdentityResponse =
                //    federationTest.GetTemporaryCredentialUsingGoogle(
                //            providerAppId,
                //            ConfigurationManager.AppSettings["GoogleProviderAppIdSecret"],
                //            createRoleResponse.Role.Arn);
                break;

            case "Amazon":
                assumeRoleWithWebIdentityResponse =
                    federationTest.GetTemporaryCredentialUsingAmazon(
                        ConfigurationManager.AppSettings["AmazonProviderClientId"],
                        createRoleResponse.Role.Arn);
                break;
            }

            S3Test s3Test = new S3Test();

            s3Test.CreateS3Bucket("federationtestbucket",
                                  identityProvider + "/" +
                                  assumeRoleWithWebIdentityResponse.SubjectFromWebIdentityToken,
                                  assumeRoleWithWebIdentityResponse.Credentials, config);

            DeleteRolePolicyResponse deleteRolePolicyResponse =
                iamClient.DeleteRolePolicy(new DeleteRolePolicyRequest
            {
                PolicyName = "federationtestrole-rolepolicy",
                RoleName   = "federationtestrole"
            });

            DeleteRoleResponse deleteRoleResponse =
                iamClient.DeleteRole(new DeleteRoleRequest
            {
                RoleName = "federationtestrole"
            });
        }