requireRoles function
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();
};
}