Exemplo n.º 1
0
        public async Task <string> Execute(AddPolicyParameter addPolicyParameter)
        {
            var json = addPolicyParameter == null ? string.Empty : JsonConvert.SerializeObject(addPolicyParameter);

            _umaServerEventSource.StartAddingAuthorizationPolicy(json);
            if (addPolicyParameter == null)
            {
                throw new ArgumentNullException(nameof(addPolicyParameter));
            }

            if (addPolicyParameter.ResourceSetIds == null || !addPolicyParameter.ResourceSetIds.Any())
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode,
                                           string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, Constants.AddPolicyParameterNames.ResourceSetIds));
            }

            foreach (var resourceSetId in addPolicyParameter.ResourceSetIds)
            {
                var resourceSet = await _repositoryExceptionHelper.HandleException(
                    string.Format(ErrorDescriptions.TheResourceSetCannotBeRetrieved, resourceSetId),
                    () => _resourceSetRepository.Get(resourceSetId));

                if (resourceSet == null)
                {
                    throw new BaseUmaException(ErrorCodes.InvalidResourceSetId, string.Format(ErrorDescriptions.TheResourceSetDoesntExist, resourceSetId));
                }

                if (addPolicyParameter.Scopes.Any(r => !resourceSet.Scopes.Contains(r)))
                {
                    throw new BaseUmaException(ErrorCodes.InvalidScope, ErrorDescriptions.OneOrMoreScopesDontBelongToAResourceSet);
                }
            }

            // Insert policy
            var policy = new Policy
            {
                Id             = Guid.NewGuid().ToString(),
                ClientIds      = addPolicyParameter.ClientIdsAllowed,
                ResourceSetIds = addPolicyParameter.ResourceSetIds,
                IsResourceOwnerConsentNeeded = addPolicyParameter.IsResourceOwnerConsentNeeded,
                Script = addPolicyParameter.Script,
                Scopes = addPolicyParameter.Scopes,
                Claims = addPolicyParameter.Claims == null ? new List <Claim>() : addPolicyParameter.Claims.Select(c => new Claim
                {
                    Type  = c.Type,
                    Value = c.Value
                }).ToList()
            };

            await _repositoryExceptionHelper.HandleException(ErrorDescriptions.ThePolicyCannotBeInserted, () => _policyRepository.Add(policy));

            _umaServerEventSource.FinishToAddAuthorizationPolicy(JsonConvert.SerializeObject(policy));
            return(policy.Id);
        }