reload session from local storage (or other) then try a call on server needing user rights elevation (as user retrieval)) : if error : session was closed and so reload as not logged in if no error : session stills alive : so reload as previously logged in
492803
function() {
			var app = this,
				config = app.config;
			// TODO : samething for register and change password
			return deep.restful(config.session.store)
				.get("/session")
				.done(function(session) {
					//console.log("User form appData = ", session);
					if (!session.user)
						return new Error();
					return deep.restful(config.login.userStore)
						.get(user.id)
						.done(function(user) {
							if (config.loggedIn)
								this.done(config.loggedIn);
							session.user = user;
							return session;
						})
						.done(function(session) {
							return deep.restful(config.session.store)
							.put(session, "/session");
						})
						.done(config.sessionModes);
				})
				.fail(function(e) {
					var session = {};
					deep.restful(config.session.store).post(session, "/session");
					return config.sessionModes(session);
				})
				.done(deep.Modes)
				.elog();
		}
532042
def reload_handler(self, c, e):
        """"""
        cmd = self.is_reload(e)
        cmdchar = self.config['core']['cmdchar']
        if cmd is not None:
            # If we're in a minimal reload state, only the owner can do stuff, as we can't rely on the db working.
            if self.reload_event.set():
                admins = [self.config['auth']['owner']]
            else:
                with self.handler.db.session_scope() as session:
                    admins = [x.nick for x in session.query(orm.Permissions).all()]
            if e.source.nick not in admins:
                c.privmsg(self.get_target(e), "Nope, not gonna do it.")
                return
            importlib.reload(reloader)
            self.reload_event.set()
            cmdargs = cmd[len('%sreload' % cmdchar) + 1:]
            try:
                if reloader.do_reload(self, e, cmdargs):
                    if self.config.getboolean('feature', 'server'):
                        self.server = server.init_server(self)
                    self.reload_event.clear()
                logging.info("Successfully reloaded")
            except Exception as ex:
                backtrace.handle_traceback(ex, c, self.get_target(e), self.config)
1236649
function updateSession(callback) {
  core.api({method: ''}, function(err, response) {
    var session;
    if (err) {
      core.log('error encountered updating session:', err);
      callback && callback(err, null);
      return;
    }

    if (!response.token.valid) {
      // Invalid token. Either it has expired or the user has
      // revoked permission, so clear out our stored data.
      logout(callback);
      return;
    }

    callback && callback(null, session);
  });
}
943876
def _login(server, creds_file=None, api_key=None, silent=False):
    
    # fetch_api_key and check_version expect server to end in /
    if server[-1] != "/":
        server = server + "/"

    # creds file path setup
    if creds_file is None:
        creds_file = os.path.expanduser("~/.onecodex")

    # check if the creds file exists and is readable
    if not os.path.exists(creds_file):
        if silent:
            return None

        creds = {}
    elif not os.access(creds_file, os.R_OK):
        click.echo("Please check the permissions on {}".format(collapse_user(creds_file)), err=True)
        sys.exit(1)
    else:
        # it is, so let's read it!
        with open(creds_file, "r") as fp:
            try:
                creds = json.load(fp)
            except ValueError:
                click.echo(
                    "Your ~/.onecodex credentials file appears to be corrupted. "  # noqa
                    "Please delete it and re-authorize.",
                    err=True,
                )
                sys.exit(1)

        # check for updates if logged in more than one day ago
        last_update = creds.get("updated_at") or creds.get("saved_at")
        last_update = last_update if last_update else datetime.datetime.now().strftime(DATE_FORMAT)
        diff = datetime.datetime.now() - datetime.datetime.strptime(last_update, DATE_FORMAT)

        if diff.days >= 1:
            # if creds_file is old, check for updates
            upgrade_required, msg = check_version(__version__, server)
            creds["updated_at"] = datetime.datetime.now().strftime(DATE_FORMAT)

            try:
                json.dump(creds, open(creds_file, "w"))
            except Exception as e:
                if e.errno == errno.EACCES:
                    click.echo(
                        "Please check the permissions on {}".format(collapse_user(creds_file)),
                        err=True,
                    )
                    sys.exit(1)
                else:
                    raise

            if upgrade_required:
                click.echo("\nWARNING: {}\n".format(msg), err=True)

        # finally, give the user back what they want (whether silent or not)
        if silent:
            return creds.get("api_key", None)

        click.echo(
            "Credentials file already exists ({}). Logout first.".format(collapse_user(creds_file)),
            err=True,
        )
        return creds.get("email", None)

    # creds_file was not found and we're not silent, so prompt user to login
    email, api_key = login_uname_pwd(server, api_key=api_key)

    if api_key is None:
        click.echo(
            "We could not verify your credentials. Either you mistyped your email "
            "or password, or your account does not currently have API access. "
            "Please contact help@onecodex.com if you continue to experience problems."
        )
        sys.exit(1)

    creds.update(
        {
            "api_key": api_key,
            "saved_at": datetime.datetime.now().strftime(DATE_FORMAT),
            "updated_at": None,
            "email": email,
        }
    )

    try:
        json.dump(creds, open(creds_file, "w"))
    except Exception as e:
        if e.errno == errno.EACCES:
            click.echo("Please check the permissions on {}".format(creds_file), err=True)
            sys.exit(1)
        else:
            raise

    click.echo("Your ~/.onecodex credentials file was successfully created.", err=True)

    return email
258880
function() {
      if (Parse.User._currentUser) {
        return Parse.User._currentUser;
      }

      if (Parse.User._currentUserMatchesDisk) {
        
        return Parse.User._currentUser;
      }

      // Load the user from local storage.
      Parse.User._currentUserMatchesDisk = true;

      var userData = Parse.localStorage.getItem(Parse._getParsePath(
          Parse.User._CURRENT_USER_KEY));
      if (!userData) {
        
        return null;
      }
      Parse.User._currentUser = Parse.Object._create("_User");
      Parse.User._currentUser._isCurrentUser = true;

      var json = JSON.parse(userData);
      Parse.User._currentUser.id = json._id;
      delete json._id;
      Parse.User._currentUser._sessionToken = json._sessionToken;
      delete json._sessionToken;
      Parse.User._currentUser._finishFetch(json);

      Parse.User._currentUser._synchronizeAllAuthData();
      Parse.User._currentUser._refreshCache();
      Parse.User._currentUser._opSetQueue = [{}];
      return Parse.User._currentUser;
    }
138542
def get_session(user_agent):
    """"""

    client = requests.Session()
    client.headers.update({
        'Content-Type': 'application/json',
        'User-Agent': user_agent,
    })
    retry = Retry(connect=3, backoff_factor=3)
    adapter = HTTPAdapter(max_retries=retry)
    client.mount('https://', adapter)
    return client
151967
def in_session(self):
        """"""
        session = self.get_session()
        try:
            yield session
            session.commit()
        except IntegrityError:
            session.rollback()
            raise DuplicateError("Duplicate unique value detected!")
        except (OperationalError, DisconnectionError):
            session.rollback()
            self.close()
            logger.warn("Database Connection Lost!")
            raise DatabaseConnectionError()
        except Exception:
            session.rollback()
            raise
        finally:
            session.close()
859731
def _is_logged_in(self):
        
        # if the user has not logged in in 24 hours, relogin
        if not self._http._has_session() or datetime.utcnow() >= self._lastlogin + timedelta(hours=24):
            return self._login()
        else:
            return {}
798294
def _refresh(self, **kwargs):
        """"""
        requests_params = self._handle_requests_params(kwargs)
        refresh_session = self._meta_data['bigip']._meta_data['icr_session']

        if self._meta_data['uri'].endswith('/stats/'):
            # Slicing off the trailing slash here for Stats enpoints because
            # iWorkflow doesn't consider those `stats` URLs valid if they
            # include the trailing slash.
            #
            # Other than that, functionality does not change
            uri = self._meta_data['uri'][0:-1]
        else:
            uri = self._meta_data['uri']

        response = refresh_session.get(uri, **requests_params)
        self._local_update(response.json())
1229015
@InterfaceAudience.Private
    protected void checkSession() {
        if (getAuthenticator() != null) {
            Authorizer auth = (Authorizer) getAuthenticator();
            auth.setRemoteURL(remote);
            auth.setLocalUUID(db.publicUUID());
        }
        if (getAuthenticator() != null && getAuthenticator() instanceof SessionCookieAuthorizer) {
            // Sync Gateway session API is at /db/_session; try that first
            checkSessionAtPath("_session");
        } else {
            login();
        }
    }
837940
def reload_data(self):
        
        # We must force a rollback here to ensure that we are working on a fresh session, without any cache
        db.session.rollback()

        self.__data = {}
        try:
            for ns in db.ConfigNamespace.all():
                self.__data[ns.namespace_prefix] = {x.key: x.value for x in ns.config_items}

        except SQLAlchemyError as ex:
            if str(ex).find('1146') != -1:
                pass
482373
def current_user(self):
        
        if not hasattr(self, '_serverInfo') or 'username' not in self._serverInfo:

            url = self._get_url('serverInfo')
            r = self._session.get(url, headers=self._options['headers'])

            r_json = json_loads(r)
            if 'x-ausername' in r.headers:
                r_json['username'] = r.headers['x-ausername']
            else:
                r_json['username'] = None
            self._serverInfo = r_json
            # del r_json['self']  # this isn't really an addressable resource
        return self._serverInfo['username']
605973
function(callback) {
        if (res.parsedHeader.payload.mode === 'handshake') {
          res.session = {
            sid: reqSid,
            cert: senderCert,
            token: reqToken
          };
          callback(null);
        } else {
          var querySid;
          if (sessionStore instanceof Store || 'undefined' !== typeof window) {
            querySid = my.config.urlBase;
          } else {
            querySid = reqSid;
          }
          // load the session if exists
          sessionStore.load(querySid, function(err, session){
            if (err) {
              callback(err);
            } else if (session) {
              log.debug('%s loaded session', app.name);
              log.debug(session);
              res.session = session;
              callback(null);
            } else {
              callback('session expired');
            }
          });
        }
      }
771920
public void checkInactiveSession(Session session) {
        if (session == null) {
            return;
        }
        if (log.isDebugEnabled()) {
            log.debug("Checking for idle " +  session.getId());
        }
        try (Lock ignored = session.lock()) {
            if (getEvictionPolicy() > 0 && session.isIdleLongerThan(getEvictionPolicy()) &&
                    session.isValid() && session.isResident() && session.getRequests() <= 0) {
                // Be careful with saveOnInactiveEviction - you may be able to re-animate a session that was
                // being managed on another node and has expired.
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Evicting idle session " + session.getId());
                    }

                    // save before evicting
                    if (isSaveOnInactiveEviction() && sessionDataStore != null) {
                        if (sessionDataStore.isPassivating()) {
                            sessionHandler.willPassivate(session);
                        }
                        sessionDataStore.store(session.getId(), session.getSessionData());
                    }

                    doDelete(session.getId()); // detach from this cache
                    session.setResident(false);
                } catch (Exception e) {
                    log.warn("Passivation of idle session" + session.getId() + " failed", e);
                    session.updateInactivityTimer();
                }
            }
        }
    }
1351444
def reload
      response = session.send_request('GET', path)
      assign_attributes(response.fetch(self.class.tag))
      assign_errors(response)
      self
    end
987965
def try_storage(self, identifier, req, resp, resource, uri_kwargs):
        
        if identifier is None:
            user = None

        # note: if user_storage is defined, always use it in order to
        #       authenticate user.
        elif self.user_storage is not None:
            user = self.user_storage.get_user(
                self, identifier, req, resp, resource, uri_kwargs
            )

        # note: some authentication middleware classes may not require
        #       to be initialized with their own user_storage. In such
        #       case this will always authenticate with "syntetic user"
        #       if there is a valid indentity.
        elif self.user_storage is None and not self.only_with_storage:
            user = {
                'identified_with': self,
                'identifier': identifier
            }

        else:  # pragma: nocover
            # note: this should not happen if the base class is properly
            #       initialized. Still, user can skip super().__init__() call.
            user = None

        return user
212077
def _UpdateSessionIfRequired(self, request_headers, response_result, response_headers):    
        

        '''if this request was made with consistency level as session, then update
        the session'''

        if response_result is None or response_headers is None:
            return

        is_session_consistency = False
        if http_constants.HttpHeaders.ConsistencyLevel in request_headers:
            if documents.ConsistencyLevel.Session == request_headers[http_constants.HttpHeaders.ConsistencyLevel]:
                is_session_consistency = True
              
        if is_session_consistency:
            # update session
            self.session.update_session(response_result, response_headers)