rolesGate<TContext> function

AuthGateCallback<TContext> rolesGate<TContext>(
  1. Iterable<String> requiredRoles, {
  2. bool any = false,
  3. bool allowGuest = false,
})

Creates a roles gate callback.

When requiredRoles is empty, authenticated users are allowed and guests follow allowGuest.

Implementation

AuthGateCallback<TContext> rolesGate<TContext>(
  Iterable<String> requiredRoles, {
  bool any = false,
  bool allowGuest = false,
}) {
  final normalized = requiredRoles
      .map((role) => role.trim())
      .where((role) => role.isNotEmpty)
      .toList(growable: false);

  return (AuthGateEvaluationContext<TContext> context) {
    final principal = context.principal;
    if (principal == null) {
      return allowGuest;
    }
    if (normalized.isEmpty) {
      return true;
    }
    return any
        ? normalized.any(principal.hasRole)
        : normalized.every(principal.hasRole);
  };
}