Exemplo n.º 1
0
        public async Task <IActionResult> PatchClaims([FromBody] IEnumerable <CreateClaimRequest> claims)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound());
            }
            var systemClaims = await _configurationDbContext
                               .ClaimTypes
                               .Where(x => claims.Select(x => x.Type).Contains(x.Name))
                               .ToListAsync();

            var userAllowedClaims = systemClaims.Where(x => x.UserEditable).Select(x => x.Name).ToList();
            var isSystemClient    = User.IsSystemClient();

            if (isSystemClient && systemClaims.Count != claims.Count())
            {
                var notAllowedClaims = claims.Select(x => x.Type).Except(systemClaims.Select(x => x.Name));
                ModelState.AddModelError(nameof(claims), $"The following claims are not allowed to add by the client: '{string.Join(", ", notAllowedClaims)}'.");
                return(BadRequest(new ValidationProblemDetails(ModelState)));
            }
            if (!isSystemClient && userAllowedClaims.Count != claims.Count())
            {
                var notAllowedClaims = claims.Select(x => x.Type).Except(userAllowedClaims);
                ModelState.AddModelError(nameof(claims), $"The following claims are not allowed to add: '{string.Join(", ", notAllowedClaims)}'.");
                return(BadRequest(new ValidationProblemDetails(ModelState)));
            }
            var existingUserClaims = await _userManager.GetClaimsAsync(user);

            var claimsToRemove = existingUserClaims.Where(x => systemClaims.Select(x => x.Name).Contains(x.Type));

            if (claimsToRemove.Any())
            {
                await _userManager.RemoveClaimsAsync(user, claimsToRemove);
            }
            var claimsToAdd = claims.Select(x => new IdentityUserClaim <string> {
                UserId     = user.Id,
                ClaimType  = x.Type,
                ClaimValue = x.Value
            })
                              .ToArray();

            _dbContext.UserClaims.AddRange(claimsToAdd);
            await _dbContext.SaveChangesAsync();

            return(Ok(claimsToAdd.Select(x => new ClaimInfo {
                Id = x.Id,
                Type = x.ClaimType,
                Value = x.ClaimValue
            })));
        }