requireRoles function

AuthGuard requireRoles(
  1. List<String> roles, {
  2. SessionAuthService? sessionAuth,
  3. bool any = false,
})

Implementation

AuthGuard requireRoles(
  List<String> roles, {
  SessionAuthService? sessionAuth,
  bool any = false,
}) {
  final expected = roles
      .map((role) => role.trim())
      .where((role) => role.isNotEmpty)
      .toList(growable: false);

  final auth = sessionAuth ?? SessionAuth.instance;

  return (EngineContext ctx) {
    final principal = auth.current(ctx);
    if (principal == null) {
      ctx.response.statusCode = HttpStatus.unauthorized;
      ctx.response.write('Authentication required');
      return GuardResult.deny(ctx.response);
    }

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

    final matches = any
        ? expected.any(principal.hasRole)
        : expected.every(principal.hasRole);
    return matches ? GuardResult.allow() : GuardResult.deny();
  };
}