public async Task <Tuple <bool, string[]> > UpdateRoleAsync(ApplicationRole role, IEnumerable <string> claims) { if (claims != null) { string[] invalidClaims = claims.Where(c => PermissionConstants.GetPermissionByValue(c) == null).ToArray(); if (invalidClaims.Any()) { return(Tuple.Create(false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) })); } } var result = await this.roleManager.UpdateAsync(role); if (!result.Succeeded) { return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray())); } if (claims != null) { var roleClaims = (await this.roleManager.GetClaimsAsync(role)).Where(c => c.Type == "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 this.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 this.roleManager.AddClaimAsync(role, new Claim("permission", PermissionConstants.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 => PermissionConstants.GetPermissionByValue(c) == null).ToArray(); if (invalidClaims.Any()) { return(Tuple.Create(false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) })); } var result = await this.roleManager.CreateAsync(role); if (!result.Succeeded) { return(Tuple.Create(false, result.Errors.Select(e => e.Description).ToArray())); } role = await this.roleManager.FindByNameAsync(role.Name); foreach (string claim in claims.Distinct()) { result = await this.roleManager.AddClaimAsync(role, new Claim("permission", PermissionConstants.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[] { })); }