updateSession method

  1. @override
  2. @protected
  3. @visibleForTesting
void updateSession({
  1. FrappeSessionStatusInfo? sessionStatus,
  2. bool loggedIn = false,
  3. double? useTimestamp,
})
override

Updates the session locally.

The AuthController.sessionStatus BehaviorSubject is updated if the new session sessionStatus is different than the old one.

If the sessions match, nothing happens.

If useTimestamp is specified, it will be used as the timestamp of the new session, otherwise, the current timestamp will be used.

Implementation

@override
@protected
@visibleForTesting
void updateSession(
    {FrappeSessionStatusInfo? sessionStatus,
    bool loggedIn = false,
    double? useTimestamp}) {
  // Update when old and new status  don't match
  final old = getSession() ?? FrappeSessionStatusInfo(false, 0);
  final newStatus = sessionStatus ?? FrappeSessionStatusInfo(false, 0);

  newStatus
    ..loggedIn = loggedIn
    ..timestamp = 0;
  if (loggedIn) {
    newStatus.currentUser = sessionStatus!.user;
  }
  newStatus.timestamp = null;
  newStatus.homePage = null;
  newStatus.message = null;
  old.timestamp = null;
  old.homePage = null;
  old.message = null;

  // check for old-new mismatch
  if (!identical(old, newStatus)) {
    final token = newStatus.token;

    // lets clear cache before everything else
    getCore().clearCache();

    // its better to update the BehaviorSubject before doing anything else
    final session = newStatus;
    newStatus.timestamp =
        useTimestamp ?? (DateTime.now().millisecondsSinceEpoch / 1000);

    if (newStatus.loggedIn == true) {
      if (token != null) {
        currentToken = token;
        // when simply checking auth status, token isn't returned
        setAuthToken(token);
      }
      if (newStatus.lang != null) {
        config.coreInstance.translate.setCurrentLanguage(newStatus.lang!);
      }
      if (getFrappe().getAppsVersion('renovation_core') != null) {
        config.coreInstance.translate.loadTranslations(lang: newStatus.lang);
      }
      currentUser = newStatus.currentUser;
    } else {
      clearAuthToken();
      currentUserRoles = <String>[];
      currentUser = null;
    }
    // Update SessionStatus after setting token
    // This is important because there might be functions ready to execute
    // right after session update
    setSession(session);
  }
}