public async Task <Tuple <bool, string[]> > UpdateRoleAsync(ApplicationRole role, IEnumerable <string> claims) { if (claims != null) { string[] invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray(); if (invalidClaims.Any()) { return(Tuple.Create(false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) })); } } var result = await _roleManager.UpdateAsync(role); if (!result.Succeeded) { return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray())); } if (claims != null) { var roleClaims = (await _roleManager.GetClaimsAsync(role)).Where(c => c.Type == ClaimConstants.Permission); var roleClaimValues = roleClaims.Select(c => c.Value).ToArray(); var claimsToRemove = roleClaimValues.Except(claims).ToArray(); var claimsToAdd = claims.Except(roleClaimValues).Distinct().ToArray(); if (claimsToRemove.Any()) { foreach (string claim in claimsToRemove) { result = await _roleManager.RemoveClaimAsync(role, roleClaims.Where(c => c.Value == claim).FirstOrDefault()); if (!result.Succeeded) { return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray())); } } } if (claimsToAdd.Any()) { foreach (string claim in claimsToAdd) { result = await _roleManager.AddClaimAsync(role, new Claim(ClaimConstants.Permission, ApplicationPermissions.GetPermissionByValue(claim))); if (!result.Succeeded) { return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray())); } } } } return(Tuple.Create(true, new string[] { })); }
public async Task <Tuple <bool, string[]> > CreateRoleAsync(ApplicationRole role, IEnumerable <string> claims) { if (claims == null) { claims = new string[] { } } ; string[] invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray(); if (invalidClaims.Any()) { return(Tuple.Create(false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) })); } var result = await _roleManager.CreateAsync(role); if (!result.Succeeded) { return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray())); } role = await _roleManager.FindByNameAsync(role.Name); foreach (string claim in claims.Distinct()) { result = await this._roleManager.AddClaimAsync(role, new Claim(ClaimConstants.Permission, ApplicationPermissions.GetPermissionByValue(claim))); if (!result.Succeeded) { await DeleteRoleAsync(role); return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray())); } } return(Tuple.Create(true, new string[] { })); }