impersonate method

Future<PocketBase> impersonate(
  1. String recordId,
  2. num duration, {
  3. String? expand,
  4. String? fields,
  5. Map<String, dynamic> body = const {},
  6. Map<String, dynamic> query = const {},
  7. Map<String, String> headers = const {},
})

Impersonate authenticates with the specified recordId and returns a new client with the received auth token in a memory store.

If duration is 0 the generated auth token will fallback to the default collection auth token duration.

This action currently requires superusers privileges.

Implementation

Future<PocketBase> impersonate(
  String recordId,
  num duration, {
  String? expand,
  String? fields,
  Map<String, dynamic> body = const {},
  Map<String, dynamic> query = const {},
  Map<String, String> headers = const {},
}) async {
  final enrichedBody = Map<String, dynamic>.of(body);
  enrichedBody["duration"] ??= duration;

  final enrichedQuery = Map<String, dynamic>.of(query);
  enrichedQuery["expand"] ??= expand;
  enrichedQuery["fields"] ??= fields;

  final enrichedHeaders = Map<String, String>.of(headers);
  enrichedHeaders["Authorization"] ??= client.authStore.token;

  // create a new client loaded with the impersonated auth state
  // ---
  final tempClient = PocketBase(
    client.baseURL,
    httpClientFactory: client.httpClientFactory,
    lang: client.lang,
  );

  final authData = await tempClient
      .send<Map<String, dynamic>>(
        "$baseCollectionPath/impersonate/${Uri.encodeComponent(recordId)}",
        method: "POST",
        body: enrichedBody,
        query: enrichedQuery,
        headers: enrichedHeaders,
      )
      .then(RecordAuth.fromJson);

  tempClient.authStore.save(authData.token, authData.record);
  // ---

  return tempClient;
}