isAuthorized method

  1. @override
CedarAuthorizationResponse isAuthorized(
  1. CedarAuthorizationRequest request, {
  2. List<CedarEntity>? entities,
  3. CedarPolicySet? policies,
})

Responds to an authorization request.

Implementation

@override
CedarAuthorizationResponse isAuthorized(
  CedarAuthorizationRequest request, {
  List<CedarEntity>? entities,
  CedarPolicySet? policies,
}) {
  if (_closed) {
    throw StateError('Cedar engine is closed');
  }
  return using((arena) {
    final query = arena<CCedarQuery>();
    query.ref
      ..principal_str = switch (request.principal) {
        final principal? => principal.normalized
            .toString()
            .toNativeUtf8(allocator: arena)
            .cast(),
        null => nullptr,
      }
      ..resource_str = switch (request.resource) {
        final resource? => resource.normalized
            .toString()
            .toNativeUtf8(allocator: arena)
            .cast(),
        null => nullptr,
      }
      ..action_str = switch (request.action) {
        final action? =>
          action.normalized.toString().toNativeUtf8(allocator: arena).cast(),
        null => nullptr,
      }
      ..context_json = switch (request.context) {
        final context? =>
          jsonEncode(context).toNativeUtf8(allocator: arena).cast(),
        null => nullptr,
      }
      ..entities_json = switch (entities) {
        final entities? =>
          jsonEncode(entities.map((e) => e.toJson()).toList())
              .toNativeUtf8(allocator: arena)
              .cast(),
        null => nullptr,
      }
      ..policies_json = switch (policies) {
        final policies? =>
          jsonEncode(policies.toJson()).toNativeUtf8(allocator: arena).cast(),
        null => nullptr,
      };
    final cDecision = bindings.cedar_is_authorized(_ref, query);
    return switch (cDecision) {
      CAuthorizationDecision(:final completion_error)
          when completion_error != nullptr =>
        throw Exception(
          'Error performing authorization: '
          '${completion_error.cast<Utf8>().toDartString()}',
        ),
      CAuthorizationDecision(
        :final is_authorized,
        :final reasons,
        :final reasons_len,
        :final errors,
        :final errors_len,
      ) =>
        CedarAuthorizationResponse(
          decision: switch (is_authorized) {
            true => CedarAuthorizationDecision.allow,
            false => CedarAuthorizationDecision.deny,
          },
          reasons: reasons == nullptr || reasons_len == 0
              ? const []
              : [
                  for (var i = 0; i < reasons_len; i++)
                    reasons[i].cast<Utf8>().toDartString(),
                ],
          errors: errors == nullptr || errors_len == 0
              ? const []
              : [
                  for (var i = 0; i < errors_len; i++)
                    errors[i].cast<Utf8>().toDartString(),
                ],
        ),
    };
  });
}