Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
195581
def login(request, user):
    
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        session_key = request.session[SESSION_KEY]
        if session_key != user.pk or (
                session_auth_hash and
                request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user.pk
    request.session[BACKEND_SESSION_KEY] = user.backend
    request.session[USER_DATA_SESSION_KEY] = user.user_data
    request.session[HASH_SESSION_KEY] = session_auth_hash

    update_token_in_session(request.session, user.token)

    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
1228217
public void setAuthenticated(final String sessionId, final Principal user) {

		securityContext = SecurityContext.getInstance(user, AccessMode.Backend);
		securityContext.setSessionId(sessionId);

		logger.debug("Session ID of security context " + securityContext + " set to " + sessionId);

		timedOut = false;
	}
406383
public function persistSession( SessionBackend $session, WebRequest $request ) {
		$metadata = $session->getProviderMetadata();
		$this->remoteToken = $metadata[ 'filteredUserName' ];
		return parent::persistSession( $session, $request );
	}
902637
protected function setUserSessionBackup()
    {
        $this->userSessionBackup = isset($_SESSION[self::SESSION_PARAMETER_CLOUDCONTROL]) ? $_SESSION[self::SESSION_PARAMETER_CLOUDCONTROL] : null;
        $fakeUser = new \stdClass();
        $fakeUser->username = self::SESSION_PARAMETER_FORM_COMPONENT;
        $_SESSION[self::SESSION_PARAMETER_CLOUDCONTROL] = $fakeUser;
    }
658487
private function persist()
    {
        $items = $this->persistableList();

        $this->session->set('stack', $items);

        $user = $this->users->getCurrentUser();
        $user['stack'] = $items;
        $this->users->saveUser($user);
    }
804671
def add_user(self, user, **kwargs):
        """"""
        if isinstance(user, User):
            user = user['id']

        assert isinstance(user, six.string_types)

        endpoint = '{0}/{1}/users/{2}'.format(
            self.endpoint,
            self['id'],
            user,
        )
        result = self.request('PUT', endpoint=endpoint, query_params=kwargs)
        return result
1123504
def _make_before_request(self):
        
        def before_request():
            """
            Process invalid identity statuses and attach user to request.

            :raises: :exception:`exceptions.FlaskKeystoneUnauthorized`

            This function guarantees that a bad token will return a 401
            when :mod:`keystonemiddleware` is configured to
            defer_auth_decision. Once this is done, it instantiates a user
            from the generated User model and attaches it to the request
            context for later access.
            """
            identity_status = request.headers.get(
                "X-Identity-Status", "Invalid"
            )
            if identity_status != "Confirmed":
                msg = ("Couldn't authenticate user '%s' with "
                       "X-Identity-Status '%s'")
                self.logger.info(msg % (
                    request.headers.get("X-User-Id", "None"),
                    request.headers.get("X-Identity-Status", "None")
                ))
                if not self.config.allow_anonymous_access:
                    msg = "Anonymous Access disabled, rejecting %s"
                    self.logger.debug(
                        msg % request.headers.get("X-User-Id", "None")
                    )
                    raise FlaskKeystoneUnauthorized()
                else:
                    self.logger.debug("Setting Anonymous user.")
                    self._set_anonymous_user()
                    return

            self._set_user(request)

        return before_request
202984
public function unimpersonateUser()
    {
        $realId = $this->session->remove('__realId');
        if ($realId !== null) {
            $this->user->identity->remove();
            $this->session->set($this->user->idParam, $realId);
            $identity = User::findOne($realId);
            $this->user->setIdentity($identity);
            $this->restoreBackedUpToken();
        }
    }
981875
def put(self, data, request, id):
        
        if not id:
            # can't update the whole container
            raise errors.MethodNotAllowed()
        userdata = self._dict_to_model(data)
        userdata.pk = id
        try:
            userdata.save(force_update=True)
        except DatabaseError:
            # can't udpate non-existing user
            raise errors.NotFound()
325776
public function SetIdentity($UserID, $Persist = FALSE) {
      if (is_null($UserID)) {
         $this->_ClearIdentity();
         return;
      }
      
      $this->UserID = $UserID;
      
      // If we're persisting, both the cookie and its payload expire in 30days
      $PayloadExpires = time();
      if ($Persist) {
         
         $PayloadExpires += (86400 * self::COOKIE_PERSIST_DAYS);
         $CookieExpires = $PayloadExpires;
         
      // Otherwise the payload expires in 2 days and the cookie expires on borwser restart
      } else {
         // Note: $CookieExpires = 0 causes cookie to die when browser closes.
         
         $PayloadExpires += (86400 * self::COOKIE_SESSION_DAYS);
         $CookieExpires = 0;
      }

      // Create the cookie
      $KeyData = $UserID.'-'.$PayloadExpires;
      $this->_SetCookie($this->CookieName, $KeyData, array($UserID, $PayloadExpires), $CookieExpires);
      $this->SetVolatileMarker($UserID);
   }
666504
private void saveToSession(HttpServletRequest req, String reqURL, Map params) {
		HttpSession postparamsession = req.getSession(true);
		if (postparamsession != null && params != null && !params.isEmpty()) {
			postparamsession.setAttribute(INITIAL_URL, reqURL);
			postparamsession.setAttribute(PARAM_NAMES, null);
			postparamsession.setAttribute(PARAM_VALUES, params);
			if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
				Tr.debug(tc, "URL saved: " + reqURL.toString());
			}
		}
	}
506860
function(user) {
      if (Parse.User._currentUser !== user) {
        Parse.User.logOut();
      }
      user._isCurrentUser = true;
      Parse.User._currentUser = user;
      Parse.User._currentUserMatchesDisk = true;

      var json = user.toJSON();
      json._id = user.id;
      json._sessionToken = user._sessionToken;
      Parse.localStorage.setItem(
          Parse._getParsePath(Parse.User._CURRENT_USER_KEY),
          JSON.stringify(json));
    }
668219
def store_user_data(user=None, group=None,data_kind=DINGOS_USER_DATA_TYPE_NAME,user_data=None,iobject_name=None):
        

        if not user_data:
            user_data = {}

        if not user.is_authenticated():
            user = None

        user_config,created =  UserData.objects.get_or_create(user=user,group=group,data_kind=data_kind)
        return user_config.store(user_data,iobject_type_name=data_kind,iobject_name=iobject_name)
332776
def begin(request, provider):
    
    # store url to where user will be redirected
    request.session['next_url'] = request.GET.get("next") or settings.LOGIN_REDIRECT_URL

    # start the authentication process
    backend = get_backend(provider)
    return backend.begin(request, dict(request.REQUEST.items()))
149341
function(options) {
      var storedUser = ((!this.isOAuth2Mode() && this.Storage.retrieve(this.loggedInUserKey)) || this.Storage.retrieve('oauth2.user'));
      //The logged in user's ID is saved in local storage until removed, so we need to check to make sure that the user has valid login credentials before returning the login ID.
      if ( options && options['success'] ){
        this.hasValidOAuth(options);
      } else {
        return (this.isLoggedIn(options) && storedUser) ? storedUser : null;
      }
    }
1046855
protected function storeIntendedUrl()
    {
        // Do not store the URL if it was the login itself
        $previousUrl = url()->previous();
        $loginUrl    = url()->route($this->core->prefixRoute(NamedRoute::AUTH_LOGIN));

        if ($previousUrl == $loginUrl) return;

        session()->put('url.intended', $previousUrl);
    }
1322154
function (authenticationRequest, callback) {
            // create query to fetch the user
            var query = this._createQueryForUser(authenticationRequest.get(this.$.usernameField));
            var collection = this.$.dataSource.createCollection(this.$collectionClass).query(query);

            collection.fetch({limit: 1}, function (err, users) {
                var user;
                if (!err && users.size()) {
                    user = users.at(0);
                    user.fetch(null, callback);
                } else {
                    callback(err, null);
                }
            });
        }