Skip to content

Commit 36d3e02

Browse files
refactor: add validations HasUserClaimsAsync at UserManagerService.cs and optimize the query
1 parent 0546be2 commit 36d3e02

1 file changed

Lines changed: 21 additions & 4 deletions

File tree

src/Infrastructure/Services/Identity/UserManagerService.cs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -328,11 +328,28 @@ public async Task<bool> HasUserClaimsAsync(
328328
IEnumerable<KeyValuePair<string, string>> claims
329329
)
330330
{
331-
List<UserClaim> userClaims = await UserClaims
332-
.Where(x => x.UserId == id && x.ClaimType == ClaimTypes.Permission)
333-
.ToListAsync();
331+
ArgumentNullException.ThrowIfNull(claims);
332+
List<KeyValuePair<string, string>> authorizeClaims = [..claims];
333+
334+
if (authorizeClaims.Count == 0)
335+
{
336+
return false;
337+
}
338+
339+
string key = authorizeClaims[0].Key;
340+
if (string.IsNullOrWhiteSpace(key))
341+
{
342+
throw new ArgumentException($"{nameof(claims)} key must not be empty or white space.", nameof(claims));
343+
}
344+
if (authorizeClaims.Any(p => p.Key != key))
345+
{
346+
throw new ArgumentException($"{nameof(claims)} doesn't has the same key.", nameof(claims));
347+
}
334348

335-
return userClaims.Exists(x => claims.Any(p => p.Key == x.ClaimType && p.Value == x.ClaimValue));
349+
List<string> values = authorizeClaims.ConvertAll(x => x.Value);
350+
return await UserClaims
351+
.Where(x => x.UserId == id && x.ClaimType == key)
352+
.AnyAsync(x => values.Contains(x.ClaimValue));
336353
}
337354

338355
public async Task<bool> HasUserPermissionAsync(Ulid id, IEnumerable<string> claims)

0 commit comments

Comments
 (0)