Recover a jwt user session from a cookie
484264
function recover_session($token=''){
		//$r = Env::getRequest();
		$key = Env::getConfig("jwt")->get('key');

		$expiration = Env::getConfig("jwt")->get('token_expiration');
		$cookie_key=   Env::getConfig("jwt")->get('cookie_key');

		if(empty($key) || empty($expiration) || empty($cookie_key)){
			throw new Exception("critical security failure. Please configure module",00);
		}
		//retrieve user token // priority order -> cookie-> headers
		$result = false;
		if(empty($token)){
			$token = (isset($_COOKIE[$cookie_key]))? $_COOKIE[$cookie_key] : Env::getRequest()->getToken();
		}
	//	var_dump($_COOKIE);

		try{


			//var_dump($token);

			$decoded = array();
			if(!empty($token)){
				$decoded = JWT::decode($token, $key, array('HS256'));

				if($decoded){
					//authenticated
					$result = true;
					$this->setToken($token);
				//	var_dump($token);
					if(Env::getConfig("jwt")->get('auto_renew')){
						$this->create_session((array)$decoded->data);
					}

					//$key = $this->getEntity()->onePKName();
				//	$this->load_user($decoded->data->$key);

				}
			}
		}
		catch(\Firebase\JWT\ExpiredException $e){

			$this->setError("Expired token, please log in again",101);
			return false;
		}
		catch( \Exception $e){

			$this->setError("Invalid token ".var_export($e,true),102);
			return false;
		}finally{
			if ($result) {
			//	$this->logout();

				$this->setDefaultDatas((array)$decoded->data);
				return true;
			}
		}
		return false;
	}
865410
def restore_session
      guest_token, payment_method_id =
        params.fetch(:merchantReturnData).split("|")

      cookies.permanent.signed[:guest_token] = guest_token

      @payment_method = Spree::PaymentMethod.find(payment_method_id)

      @order = Spree::Order.find_by!(number: order_number)
    end
743744
function JSONCookie (str) {
  if (typeof str !== 'string' || str.substr(0, 2) !== 'j:') {
    return undefined
  }

  try {
    return JSON.parse(str.slice(2))
  } catch (err) {
    return undefined
  }
}
177362
public static function GetAuthSessionData ($cookie_name, $user_name, $password, $name = self::DEFAULT_CONNECTION_NAME) {
		$options	= static::GetAuthCookieOptions($name);

		$server_key			= $options['server_key'];
		$server_salt		= $options['server_salt'];
		$stretcher			= $options['stretcher'];
		$separator_length	= $options['separator_length'];

		$raw_data	= file_get_contents(static::CreateCookieSavePath($cookie_name, $name));
		$raw_data	= CompressionGz::UnCompressVariable(OpenSSL::DecryptRandom($raw_data, $cookie_name, $server_salt, $server_key, $separator_length));
		$raw_data	= $raw_data['raw_data'];

		$server_salt	= Hash::HmacStringStretching($stretcher[1], $server_salt, $server_key);
		$password		= Hash::HmacStringStretching($stretcher[2], $password, $user_name);
		$hmac_key		= Hash::HmacStringStretching($stretcher[0], $server_salt, $password);

		return CompressionGz::UnCompressVariable(OpenSSL::DecryptRandom($raw_data, $password, $server_salt, $hmac_key, $separator_length));
	}
601182
def authenticate_credentials(self, payload):
        """"""
        username = payload.get('preferred_username') or payload.get('username')

        if username is None:
            raise exceptions.AuthenticationFailed('JWT must include a preferred_username or username claim!')
        else:
            try:
                user, __ = get_user_model().objects.get_or_create(username=username)
                attributes_updated = False
                for claim, attr in self.get_jwt_claim_attribute_map().items():
                    payload_value = payload.get(claim)

                    if getattr(user, attr) != payload_value and payload_value is not None:
                        setattr(user, attr, payload_value)
                        attributes_updated = True

                if attributes_updated:
                    user.save()
            except:
                msg = 'User retrieval failed.'
                logger.exception(msg)
                raise exceptions.AuthenticationFailed(msg)

        return user
663433
function(){
    if(window.localStorage){
      var saved = localStorage['cloudmineTodoSession'];
      if(!saved)
        return null;
      var prefs = JSON.parse(saved);
      return prefs.token;
    } else {
      var cookies = document.cookie.split(';');
      for (var i in cookies){
        var cookie = cookies[i].split('=');
        if (cookie[0] == 'cloudmineTodoSession' && cookie[1] != 'none'){
          $('#login').hide();
          $('#restoring_session').show();
          return cookie[1];
        }
      }
    }
    return null;
  }
157041
function(req,res,next){
  var token = req.get('X-OOSE-Token')
  if(!token || user.session.token !== token){
    res.status(401)
    res.json({error: 'Invalid session'})
  } else {
    req.session = user.session
    next()
  }
}
103107
function _getCookieToken (cookies, req, cookieName, cookieDomain, publicUrl) {
  let token = cookies.get(cookieName)
  if (!token) return null
  const reqOrigin = req.headers['origin']
  const originDomain = reqOrigin && new URL(reqOrigin).host

  // check that the origin of the request is part of the accepted domain
  if (reqOrigin && cookieDomain && originDomain !== cookieDomain && !originDomain.endsWith('.' + cookieDomain)) {
    debug(`A cookie was sent from origin ${reqOrigin} while cookie domain is ${cookieDomain}, ignore it`)
    return null
  }
  // or simply that it is strictly equal to current target if domain is unspecified
  // in this case we are also protected by sameSite
  if (reqOrigin && !cookieDomain && reqOrigin !== new URL(publicUrl).origin) {
    debug(`A cookie was sent from origin ${reqOrigin} while public url is ${publicUrl}, ignore it`)
    return null
  }

  // Putting the signature in a second token is recommended but optional
  // and we accept full JWT in id_token cooke
  const signature = cookies.get(cookieName + '_sign')
  if (signature && (token.match(/\./g) || []).length === 1) {
    token += '.' + signature
  }
  return token
}
72010
def unsign_jwt(token, secret_key, salt=None, **kw):
    
    s = itsdangerous.TimedJSONWebSignatureSerializer(secret_key, salt=salt, **kw)
    return s.loads(token)
1048412
function(req, user){
      req.session.authenticated = true;
      req.session.user = user;
    }
1066683
def get_session(key=None, username=None, password=None, cache=True,
                cache_expiry=datetime.timedelta(days=7), cookie_path=COOKIE_PATH, backend='memory',
                version=VERSION_GLOBAL):
    """"""
    class VooblyAuth(AuthBase):  # pylint: disable=too-few-public-methods
        """Voobly authorization storage."""

        def __init__(self, key, username, password, cookie_path, version):
            """Init."""
            self.key = key
            self.username = username
            self.password = password
            self.cookie_path = cookie_path
            self.base_url = BASE_URLS[version]

        def __call__(self, r):
            """Call is no-op."""
            return r

    if version not in BASE_URLS:
        raise ValueError('unsupported voobly version')

    session = requests.session()
    if cache:
        session = requests_cache.core.CachedSession(expire_after=cache_expiry, backend=backend)
    session.auth = VooblyAuth(key, username, password, cookie_path, version)
    if os.path.exists(cookie_path):
        _LOGGER.info("cookie found at: %s", cookie_path)
        session.cookies = _load_cookies(cookie_path)
    return session
1000124
def post_session():
    

    url_string = "{}/users/me/session".format(WinkApiInterface.BASE_URL)

    nonce = ''.join([str(random.randint(0, 9)) for i in range(9)])
    _json = {"nonce": str(nonce)}

    try:
        arequest = requests.post(url_string,
                                 data=json.dumps(_json),
                                 headers=API_HEADERS)
        response_json = arequest.json()
        return response_json
    except requests.exceptions.RequestException:
        return None
1027628
private void restoreFromSession(IExtendedRequest extRequest, HttpServletRequest req, String reqURL) {
		HttpSession postparamsession = req.getSession(false);
		if (postparamsession == null) {
			return;
		}
		String previousReq = (String) postparamsession.getAttribute(INITIAL_URL);
		if (previousReq != null && previousReq.equals(reqURL)) {
			try {
				if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
					Tr.debug(tc, "Found the session, restoring POST parameters.");
				}
				extRequest.setMethod("POST");
				Map paramValues = (Map) postparamsession.getAttribute(PARAM_VALUES);

				if (paramValues != null && !paramValues.isEmpty()) {
					if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
						Tr.debug(tc, "Restoring POST paramameters for URL : " + reqURL);
					}
					extRequest.setInputStreamData((HashMap) paramValues);
				}
			} catch (IOException exc) {
				if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
					Tr.debug(tc, "IOException restoring POST parameters onto a cookie: ", new Object[] { exc });
				}
			}
		} else if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
			Tr.debug(tc, "Parameters NOT restored. Original URL : " + previousReq + " req. URL : " + reqURL);
		}

		postparamsession.setAttribute(INITIAL_URL, null);
		postparamsession.setAttribute(PARAM_NAMES, null);
		postparamsession.setAttribute(PARAM_VALUES, null);
	}
1275278
@SuppressWarnings("unchecked")
    protected Session getSessionCookie(HttpServerExchange exchange) {
        Session session = Session.create()
            .withContent(new HashMap<>())
            .withAuthenticity(MangooUtils.randomString(STRING_LENGTH));
    
        if (this.config.getSessionCookieExpires() > 0) {
            session.withExpires(LocalDateTime.now().plusSeconds(this.config.getSessionCookieExpires()));
        }
        
        String cookieValue = getCookieValue(exchange, this.config.getSessionCookieName());
        if (StringUtils.isNotBlank(cookieValue)) {
            try {
                String decryptedValue = Application.getInstance(Crypto.class).decrypt(cookieValue, this.config.getSessionCookieEncryptionKey());
                JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                        .setVerificationKey(new HmacKey(this.config.getSessionCookieSignKey().getBytes(StandardCharsets.UTF_8)))
                        .setJwsAlgorithmConstraints(new AlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.HMAC_SHA512))
                        .build();
                
                JwtClaims jwtClaims = jwtConsumer.processToClaims(decryptedValue);
                String expiresClaim = jwtClaims.getClaimValue(ClaimKey.EXPIRES.toString(), String.class);
                
                if (("-1").equals(expiresClaim)) {
                    session = Session.create()
                            .withContent(MangooUtils.copyMap(jwtClaims.getClaimValue(ClaimKey.DATA.toString(), Map.class)))
                            .withAuthenticity(jwtClaims.getClaimValue(ClaimKey.AUTHENTICITY.toString(), String.class));
                } else if (LocalDateTime.parse(jwtClaims.getClaimValue(ClaimKey.EXPIRES.toString(), String.class), DateUtils.formatter).isAfter(LocalDateTime.now())) {
                    session = Session.create()
                            .withContent(MangooUtils.copyMap(jwtClaims.getClaimValue(ClaimKey.DATA.toString(), Map.class)))
                            .withAuthenticity(jwtClaims.getClaimValue(ClaimKey.AUTHENTICITY.toString(), String.class))
                            .withExpires(LocalDateTime.parse(jwtClaims.getClaimValue(ClaimKey.EXPIRES.toString(), String.class), DateUtils.formatter));
                } else {
                    //Ignore this and use default session
                }
            } catch (MalformedClaimException | InvalidJwtException e) {
                LOG.error("Failed to parse session cookie", e);
                session.invalidate();
            }
        }

        return session;
    }
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)
891031
function Session(req, res, cookies, opts) {
  this.req = req;
  this.res = res;
  this.cookies = cookies;
  this.opts = opts;
  if (opts.cookie.ephemeral && opts.cookie.maxAge) {
    throw new Error("you cannot have an ephemeral cookie with a maxAge.");
  }

  this.content = {};
  this.json = JSON.stringify(this._content);
  this.loaded = false;
  this.dirty = false;

  // no need to initialize it, loadFromCookie will do
  // via reset() or unbox()
  this.createdAt = null;
  this.duration = opts.duration;
  this.activeDuration = opts.activeDuration;

  // support for maxAge
  if (opts.cookie.maxAge) {
    this.expires = new Date(new Date().getTime() + opts.cookie.maxAge);
  } else {
    this.updateDefaultExpires();
  }

  // here, we check that the security bits are set correctly
  var secure = (res.socket && res.socket.encrypted) ||
      (req.connection && req.connection.proxySecure);
  if (opts.cookie.secure && !secure) {
    throw new Error("you cannot have a secure cookie unless the socket is " +
        " secure or you declare req.connection.proxySecure to be true.");
  }
}
514596
def logout(session, cookies, csrf_token):
    '''
    
    '''
    payload = {"jsonrpc": "2.0",
               "id": "ID0",
               "method": "logout",
               "params": []
               }
    session.post(DETAILS['url'],
                 data=json.dumps(payload),
                 cookies=cookies,
                 headers={'X-CSRF-Token': csrf_token})