getOrCreateSession method

Future<AuthUserSession> getOrCreateSession({
  1. required String userId,
  2. String? mid,
  3. String? businessId,
  4. bool refresh = false,
  5. String? pin,
})

Retrieves a session from memory, or fetches/creates it from the server.

userId The ID of the user to get or create a session for. refresh If true, forces a fetch from the server even if a session exists in memory. pin Optional PIN for session creation when PIN verification is required.

Implementation

Future<AuthUserSession> getOrCreateSession({
  required String userId,
  String? mid,
  String? businessId,
  bool refresh = false,
  String? pin,
}) {
  return monitoringService.monitorAction<AuthUserSession>(
    actionName: 'get_or_create_session',
    provider: _providerName,
    attributes: {'userId': userId, 'refresh': refresh},
    action: (trace) async {
      _ensureInitialized();
      // Try to find in memory
      if (!refresh) {
        final existingSession = await _localSessionRepository.getSession(
          userId,
        );

        if (existingSession != null) {
          final session = await refreshSessionIfExpiring(existingSession);
          await validateSession(session);
          logger.info(this, 'Found session for user $userId');
          await _localSessionRepository.setActiveSession(session);
          return session;
        }

        // Not in memory or refresh required, try getting from server
        logger.info(this, 'Fetching session for user $userId from server.');
        try {
          var responseSession = await sessionService.getSession(
            userId,
            mid: mid,
            businessId: businessId,
          );
          var session = responseSession != null
              ? AuthUserSession.mapFromDto(dto: responseSession)
              : null;

          if (session != null) {
            await validateSession(session);
            logger.info(
              this,
              'Successfully fetched session for user $userId.',
            );
            await _localSessionRepository.saveSession(session);
            await _localSessionRepository.setActiveSession(session);
            return session;
          }
        } catch (e) {
          logger.warning(
            this,
            'Error fetching session for user $userId: $e',
            error: e,
          );
        }
      }

      // Not on server, create a new one
      logger.info(
        this,
        'No session found for user $userId. Creating a new one.',
      );
      return await createSession(
        userId,
        mid: mid,
        businessId: businessId,
        pin: pin,
      );
    },
  );
}