requireRolesGuard<TContext, TResponse> function

AuthGuard<TContext, TResponse> requireRolesGuard<TContext, TResponse>(
  1. Iterable<String> roles, {
  2. required AuthPrincipalResolver<TContext> principalResolver,
  3. bool any = false,
  4. GuardDeniedFactory<TContext, TResponse>? onUnauthenticated,
  5. GuardDeniedFactory<TContext, TResponse>? onForbidden,
})

Returns a guard that validates roles against the resolved principal.

Roles are trimmed and blank values are dropped. Guests use onUnauthenticated, authenticated users without a matching role use onForbidden, and an empty normalized role list allows any authenticated principal.

Implementation

AuthGuard<TContext, TResponse> requireRolesGuard<TContext, TResponse>(
  Iterable<String> roles, {
  required AuthPrincipalResolver<TContext> principalResolver,
  bool any = false,
  GuardDeniedFactory<TContext, TResponse>? onUnauthenticated,
  GuardDeniedFactory<TContext, TResponse>? onForbidden,
}) {
  final expected = roles
      .map((role) => role.trim())
      .where((role) => role.isNotEmpty)
      .toList(growable: false);

  return (context) {
    final principal = principalResolver(context);
    if (principal == null) {
      return GuardResult<TResponse>.deny(onUnauthenticated?.call(context));
    }

    if (expected.isEmpty) {
      return GuardResult<TResponse>.allow();
    }

    final matches = any
        ? expected.any(principal.hasRole)
        : expected.every(principal.hasRole);
    if (matches) {
      return GuardResult<TResponse>.allow();
    }
    return GuardResult<TResponse>.deny(onForbidden?.call(context));
  };
}