setAuth method

Future<void> setAuth({
  1. required String accessToken,
  2. required String refreshToken,
  3. required DateTime expiresAt,
  4. String? userId,
  5. required String organizationId,
  6. required String deviceId,
})

Set authentication state after successful HTTP auth

Implementation

Future<void> setAuth({
  required String accessToken,
  required String refreshToken,
  required DateTime expiresAt,
  String? userId,
  required String organizationId,
  required String deviceId,
}) async {
  try {
    final lib = PlatformLoader.loadCommons();
    final setAuth = lib.lookupFunction<
        Int32 Function(Pointer<RacAuthDataStruct>),
        int Function(Pointer<RacAuthDataStruct>)>('rac_state_set_auth');

    final expiresAtUnix = expiresAt.millisecondsSinceEpoch ~/ 1000;

    final accessTokenPtr = accessToken.toNativeUtf8();
    final refreshTokenPtr = refreshToken.toNativeUtf8();
    final userIdPtr = userId?.toNativeUtf8() ?? nullptr;
    final organizationIdPtr = organizationId.toNativeUtf8();
    final deviceIdPtr = deviceId.toNativeUtf8();

    final authData = calloc<RacAuthDataStruct>();

    try {
      authData.ref.accessToken = accessTokenPtr;
      authData.ref.refreshToken = refreshTokenPtr;
      authData.ref.expiresAtUnix = expiresAtUnix;
      authData.ref.userId = userIdPtr;
      authData.ref.organizationId = organizationIdPtr;
      authData.ref.deviceId = deviceIdPtr;

      final result = setAuth(authData);
      if (result != RacResultCode.success) {
        _logger
            .warning('Failed to set auth state', metadata: {'code': result});
      }
    } finally {
      calloc.free(accessTokenPtr);
      calloc.free(refreshTokenPtr);
      if (userIdPtr != nullptr) calloc.free(userIdPtr);
      calloc.free(organizationIdPtr);
      calloc.free(deviceIdPtr);
      calloc.free(authData);
    }

    // Also store in secure storage
    await _storeTokensInSecureStorage(
      accessToken: accessToken,
      refreshToken: refreshToken,
      deviceId: deviceId,
      userId: userId,
      organizationId: organizationId,
    );

    _logger.debug('Auth state set in C++');
  } catch (e) {
    _logger.debug('rac_state_set_auth error: $e');
  }
}