/*
需要重新获取access_token的条件：
1. 是DEV用户，即 isBceKey为false
2. isAuthorized为false，或isAuthorized为true，但当前时间晚于expireDate前一天
483287
protected Boolean needAuth() {
        if (isBceKey.get()) {
            return false;
        }
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 1);
        return !isAuthorized.get() || c.after(expireDate);
    }
264990
function(){
    // Don't bother if there's no expires token
    if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) {
      return;
    }
    cancelExpiresAtEvent();
    var time = (new Date(service.token.expires_at))-(new Date());
    if(time && time > 0 && time <= 2147483647){
      expiresAtEvent = $interval(function(){
        $rootScope.$broadcast('oauth:expired', service.token);
      }, time, 1);
    }
  }
872911
protected boolean refreshToken() {
		long now = System.currentTimeMillis();
		boolean notExpired = tokenKeyExpires != null && tokenKeyExpires > now;
		boolean canRefresh = tokenKeyNextRefresh != null &&
				(tokenKeyNextRefresh < now || tokenKeyNextRefresh > tokenKeyExpires);
		// token present and NOT expired
		if (tokenKey != null && notExpired && canRefresh) {
			Map<String, Object> result = getEntity(invokeGet(JWT_PATH, null), Map.class);
			if (result != null && result.containsKey("user") && result.containsKey("jwt")) {
				Map<?, ?> jwtData = (Map<?, ?>) result.get("jwt");
				tokenKey = (String) jwtData.get("access_token");
				tokenKeyExpires = (Long) jwtData.get("expires");
				tokenKeyNextRefresh = (Long) jwtData.get("refresh");
				return true;
			} else {
				clearAccessToken();
			}
		}
		return false;
	}
484945
function CheckTokens(callback, token_fetch)
	{
		// build list of tokens we're missing
		var todo = [];

		// force token_fetch to an array
		token_fetch = [].concat(token_fetch);

		// make sure we're actually logged in first
		if (!auth_obj.auth_code)
		{
			Log("Need to login - no auth token found");
			todo.push({name: "Login", func: Login});
		}

		if (!auth_obj.expire_time || auth_obj.expire_time < new Date().getTime())
		{
			// token has expired! Fetch access_token again
			Log("Need to fetch access tokens - tokens expired");
			todo.push({name: "GetAccessToken", func: GetAccessToken});
		}
		else if (!auth_obj.access_token)
		{
			// we have no access token (?!)
			Log("Need to fetch access tokens - no token available");
			todo.push({name: "GetAccessToken", func: GetAccessToken});
		}

		if (!auth_obj.username || !auth_obj.region)
		{
			// missing player username/region
			Log("Need to fetch userdata - no region or username available");
			todo.push({name: "GetUserData", func: GetUserData});
		}

		if (todo.length == 0)
		{
			// everything is fine
			if (callback) callback(false);
		}
		else
		{
			// work through our list of tokens we need to update
			var step = function()
			{
				var func = todo.shift();
				if (!func)
				{
					// all done!
					if (callback) callback(false);
					return;
				}

				if (token_fetch.indexOf(func.func) >= 0)
				{
					// if we're actually calling a token fetch function, skip!
					process.nextTick(step);
				}
				else
				{
					func.func(function(error) {
						if (error)
						{
							// token fetching error!
							if (callback) callback(func.name + " :: " + error);
							return;
						}

						// do next step
						process.nextTick(step);
					});
				}
			};

			// start updating tokens
			process.nextTick(step);
		}
	}
825500
private function getAccessToken($expired = false) {
        // Refresh the access token if force refresh or the expiretime has passed
        if ($expired || isset($this->expireTime) && $this->expireTime <= time()) {
            // If there is no refresh token throw exception
            if (!isset($this->refreshToken)) {
                throw new OAuthException('Token expired but no refresh token found');
            }

            $this->refreshAccessToken();
        }
        // If there no access token fetch one
        else if (!$expired && !isset($this->accessToken)) {
            $this->fetchAccessToken();
        }

        // If there still is no access token at this point. Throw exception
        if (!isset($this->accessToken)) {
            throw new OAuthException('No access token found');
        }

        return $this->accessToken;
    }
1056672
function() {
      var oauth_accessToken = StackMob.Storage.retrieve('oauth2.accessToken');
      var oauth_macKey = StackMob.Storage.retrieve('oauth2.macKey');
      var oauth_expires = StackMob.Storage.retrieve('oauth2.expires');
      var oauth_refreshToken = StackMob.Storage.retrieve(StackMob.REFRESH_TOKEN_KEY);
      var userSchemaInfo = StackMob.Storage.retrieve('oauth2.userSchemaInfo');
      var oauth_schema = null;

      try {
        oauth_schema = JSON.parse(userSchemaInfo);
      } catch (e) { /* Harmless if this fails (in theory!)*/ }

      if (_.every([oauth_accessToken, oauth_macKey, oauth_expires, oauth_refreshToken, oauth_schema])) {
        var creds = {
          'oauth2.accessToken' : oauth_accessToken,
          'oauth2.macKey' : oauth_macKey,
          'oauth2.expires' : oauth_expires,
          'oauth2.userSchemaInfo' : oauth_schema
        };
        creds[StackMob.REFRESH_TOKEN_KEY] = oauth_refreshToken;

        return creds;
      } else {
        return {};
      }

    }
516920
def create_refresh_token(self, access_token_value):
        # type: (str) -> str
        
        if access_token_value not in self.access_tokens:
            raise InvalidAccessToken('{} unknown'.format(access_token_value))

        if not self.refresh_token_lifetime:
            logger.debug('no refresh token issued for for access_token=%s', access_token_value)
            return None

        refresh_token = rand_str()
        authz_info = {'access_token': access_token_value, 'exp': int(time.time()) + self.refresh_token_lifetime}
        self.refresh_tokens[refresh_token] = authz_info

        logger.debug('issued refresh_token=%s expiring=%d for access_token=%s', refresh_token, authz_info['exp'],
                     access_token_value)
        return refresh_token
149869
function getTokenFromJSSDK() {
    $key = "weibojs_" . $this->client_id;
    if ( isset($_COOKIE[$key]) && $cookie = $_COOKIE[$key] ) {
      parse_str($cookie, $token);
      if ( isset($token['access_token']) && isset($token['refresh_token']) ) {
        $this->access_token = $token['access_token'];
        $this->refresh_token = $token['refresh_token'];
        return $token;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
323274
public function setAccessTokenExpire($access_token_expire)
    {
        //Store expiry date as unix timestamp (now + expires in)
        $access_token_expire = time() + $access_token_expire;
        $this->access_token_expire = $access_token_expire;
        $config = SiteConfig::current_site_config();
        $config->HailAccessTokenExpire = $access_token_expire;
        $config->write();
    }
930836
def auth_expired(self):
        
        if self._auth and self._expires:
            now_with_skew = time.time() + AUTH_TOKEN_CLOCK_SKEW_MAX
            return now_with_skew > self._expires
        return True
887891
public function refreshAccessToken($authorizer_appid, $authorizer_refresh_token)
    {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->component_access_token)) {
            return false;
        }
        $data = array();
        $data['component_appid'] = $this->component_appid;
        $data['authorizer_appid'] = $authorizer_appid;
        $data['authorizer_refresh_token'] = $authorizer_refresh_token;
        $url = self::URL_PREFIX . self::REFRESH_ACCESS_TOKEN . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        if (($result = $this->_decode($result)) === false) {
            Tools::log("Get getAuthorizerOption Faild. {$this->errMsg} [$this->errCode]", "ERR - {$this->authorizer_appid}");
        }
        return $result;
    }
362695
@JsonIgnore
    protected boolean isAccessTokenExpired(final TicketState ticketState) {
        val currentSystemTime = ZonedDateTime.now(ZoneOffset.UTC);
        val creationTime = ticketState.getCreationTime();

        var expirationTime = creationTime.plus(this.maxTimeToLiveInSeconds, ChronoUnit.SECONDS);
        if (currentSystemTime.isAfter(expirationTime)) {
            LOGGER.debug("Access token is expired because the time since creation is greater than maxTimeToLiveInSeconds");
            return true;
        }

        val expirationTimeToKill = ticketState.getLastTimeUsed().plus(this.timeToKillInSeconds, ChronoUnit.SECONDS);
        if (currentSystemTime.isAfter(expirationTimeToKill)) {
            LOGGER.debug("Access token is expired because the time since last use is greater than timeToKillInSeconds");
            return true;
        }
        return false;
    }
154710
def get_access_token(self):
        
        if self.is_access_token_expired():

            if is_debug_enabled():
                debug('requesting new access_token')

            token = get_access_token(username=self.username,
                                     password=self.password,
                                     client_id=self.client_id,
                                     client_secret=self.client_secret,
                                     app_url=self.app_url)

            # lets make sure to refresh before we're halfway to expiring
            self.expires_at = time.time() + token['expires_in']/2
            self.access_token = token['access_token']

        return self.access_token
1343019
public function updateAccessToken($access_token)
    {
        $this->getEventDispatcher()->addListener('request.before_send', function(Event $event) use($access_token){
            $request = $event['request'];
            $request->setHeader('Authorization ','Bearer '. $access_token);
        });
    }
122117
private HeaderCacheElement updateToken() {
    HeaderCacheElement newToken;
    try {
      LOG.info("Refreshing the OAuth token");
      newToken = new HeaderCacheElement(credentials.refreshAccessToken());
    } catch (Exception e) {
      LOG.warn("Got an unexpected exception while trying to refresh google credentials.", e);
      newToken = new HeaderCacheElement(
          Status.UNAUTHENTICATED
              .withDescription("Unexpected error trying to authenticate")
              .withCause(e)
      );
    }
    synchronized (lock) {
      // Update the token only if the new token is good or the old token is bad
      if (newToken.isValid() || !headerCache.isValid()) {
        headerCache = newToken;
      } else {
        LOG.warn("Failed to refresh the access token. Falling back to existing token. "
            + "New token state: {}, status: {}", newToken.getCacheState(), newToken.getToken().status);
      }
      futureToken = null;

      return headerCache;
    }
  }
19988
def token_expired(self):
        """"""
        if self._token_timer is None:
            return True
        return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR)
291731
private void initAccessTokens(String accessToken, String refreshToken, Long expireTime) {
		this.accessToken = accessToken;
		this.expireTime = expireTime;		
		if (refreshToken != null) {
			this.refreshToken = refreshToken;
		}
	}