Accepts the invitation request.

@throws UserTokenExpiredException when the token is expired
540015
public function acceptInvitation()
    {
        if ($this->isInvitationTokenAccepted()) {
            throw new UserInvitationAlreadyAcceptedException();
        }
        if ($this->isInvitationTokenExpired()) {
            throw new UserTokenExpiredException();
        }
        $this->invitationToken = null;
        $this->updatedOn = new \DateTimeImmutable();
        $this->publish(
            new UserRegistered(
                $this->id(),
                $this->email()
            )
        );
    }
484067
@Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
      IdleStateEvent e = (IdleStateEvent) evt;
      // See class comment for timeout semantics. In addition to ensuring we only timeout while
      // there are outstanding requests, we also do a secondary consistency check to ensure
      // there's no race between the idle timeout and incrementing the numOutstandingRequests
      // (see SPARK-7003).
      //
      // To avoid a race between TransportClientFactory.createClient() and this code which could
      // result in an inactive client being returned, this needs to run in a synchronized block.
      synchronized (this) {
        boolean hasInFlightRequests = responseHandler.numOutstandingRequests() > 0;
        boolean isActuallyOverdue =
          System.nanoTime() - responseHandler.getTimeOfLastRequestNs() > requestTimeoutNs;
        if (e.state() == IdleState.ALL_IDLE && isActuallyOverdue) {
          if (hasInFlightRequests) {
            String address = getRemoteAddress(ctx.channel());
            logger.error("Connection to {} has been quiet for {} ms while there are outstanding " +
              "requests. Assuming connection is dead; please adjust spark.network.timeout if " +
              "this is wrong.", address, requestTimeoutNs / 1000 / 1000);
            client.timeOut();
            ctx.close();
          } else if (closeIdleConnections) {
            // While CloseIdleConnections is enable, we also close idle connection
            client.timeOut();
            ctx.close();
          }
        }
      }
    }
    ctx.fireUserEventTriggered(evt);
  }
733519
public function tokenExpired($purpose, $value)
    {
        $this->eventDispatcher->dispatch(
            TokenEvents::TOKEN_EXPIRED,
            $event = new TokenExpiredEvent($purpose, $value)
        );

        return $event;
    }
792011
function(){
    if (!service.token) {
      return;
    }
    if(typeof(service.token.expires_in) !== 'undefined' && service.token.expires_in !== null) {
      var expires_at = new Date();
      expires_at.setSeconds(expires_at.getSeconds() + parseInt(service.token.expires_in)-60); // 60 seconds less to secure browser and response latency
      service.token.expires_at = expires_at;
    }
    else {
      service.token.expires_at = null;
    }
  }
901038
public function isAccessTokenExpired() {
    if (null == $this->token) {
      return true;
    }

    // If the token is set to expire in the next 30 seconds.
    $expired = ($this->token['created']
        + ($this->token['expires_in'] - 30)) < time();

    return $expired;
  }
102146
@Override
    public String getToken() throws TokenManagerException {
        if (hasTokenExpired()) {
            synchronized (this) {
                if (hasTokenExpired()) {
                    try {
                        final IAMToken iamToken = invokeTokenApi();
                        expiresAt = (long) (TimeUnit.SECONDS.toNanos(
                                iamToken.expires_in) * tokenExpiryThreshold)
                                + System.nanoTime();
                        token = iamToken.access_token;
                    } catch (final IAMTokenException e) {
                        throw new TokenManagerException("Failed getting Token.",
                                e);
                    }

                }
            }
        }
        return token;
    }
196431
public void accept() throws NotConnectedException, InterruptedException {
        Stanza acceptPacket = new AcceptPacket(this.session.getWorkgroupJID());
        connection.sendStanza(acceptPacket);
        // TODO: listen for a reply.
        accepted = true;
    }
1302043
public final void accept(T value) {

        if (GATE_UPDATER.get(this) == GATE_CLOSED) {
            onDrop(value);
            return;
        }

        onAccept(value);
        onNotification();
    }
1311357
@Trivial
    final void accept(boolean runOnSubmitter) {
        long time;
        nsAcceptEnd = time = System.nanoTime();
        if (runOnSubmitter)
            nsQueueEnd = time;
        state.setSubmitted();
    }
285519
private void timeoutExpired(final Timeout timeout, final TimeoutContext context) {
        try {
            removeExpiredTimeout(timeout);

            for (TimeoutExpired callback : callbacks) {
                if (callback instanceof TimeoutExpirationCallback) {
                    ((TimeoutExpirationCallback) callback).expired(timeout, context);
                } else {
                    callback.expired(timeout);
                }
            }
        } catch (Exception ex) {
            // catch all exceptions. otherwise calling timeout thread of timers thread pool will be terminated.
            LOG.error("Error handling timeout.", ex);
        }
    }
19988
def token_expired(self):
        """"""
        if self._token_timer is None:
            return True
        return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR)
1138032
def post(self, request, *args, **kwargs):
        
        status = 201
        accepted = {"accepted": True}
        send_invite_messages.apply_async()
        return Response(accepted, status=status)
40889
private synchronized boolean refreshAuthToken(final AuthHandler handler,
                                                  final boolean forceRefresh) {

        if (handler == null) {
            return false;
        }

        AuthToken token = authToken.get();

        if (!forceRefresh && token != null && token.isValid()) {
            logger.fine("Auth token is already valid");
            return true;
        }

        try {
            handler.setForceRefresh(forceRefresh);
            token = handler.call();
            authToken.set(token);

            if (token != null) {
                if (token instanceof UserBearerAuthToken) {
                    final UserBearerAuthToken bt = (UserBearerAuthToken) token;
                    logger.info("Acquired auth token. Expires: "
                                + bt.getExpires() + " token="
                                + bt.getToken());
                } else if (token instanceof ProjectBearerAuthToken) {
                    ProjectBearerAuthToken pt = (ProjectBearerAuthToken) token;
                    logger.info("Acquired proj token. Expires: " + pt.getExpires() + " token="
                                + pt.getToken());
                } else {
                    logger.info("Acquired auth token. Token valid="
                                + token.isValid());
                }
            }
        } catch (ExecutionException e) {
            final Throwable cause = e.getCause();

            if (cause != null) {
                logger.warning("Authentication failed: " + cause.getMessage());
            } else {
                logger.warning("Authentication failed: " + e.getMessage());
            }
        } catch (Exception e) {
            logger.warning("Authentication failed: " + e.getMessage());
        } finally {
            handler.setForceRefresh(false);
        }
        return true;
    }
533320
public void authenticate() {
        URL url;
        try {
            url = new URL(this.getTokenURL());
        } catch (MalformedURLException e) {
            assert false : "An invalid token URL indicates a bug in the SDK.";
            throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e);
        }

        String jwtAssertion = this.constructJWTAssertion();

        String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

        BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
        request.shouldAuthenticate(false);
        request.setBody(urlParameters);

        String json;
        try {
            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        } catch (BoxAPIException ex) {
            // Use the Date advertised by the Box server as the current time to synchronize clocks
            List<String> responseDates = ex.getHeaders().get("Date");
            NumericDate currentTime;
            if (responseDates != null) {
                String responseDate = responseDates.get(0);
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
                try {
                    Date date = dateFormat.parse(responseDate);
                    currentTime = NumericDate.fromMilliseconds(date.getTime());
                } catch (ParseException e) {
                    currentTime = NumericDate.now();
                }
            } else {
                currentTime = NumericDate.now();
            }

            // Reconstruct the JWT assertion, which regenerates the jti claim, with the new "current" time
            jwtAssertion = this.constructJWTAssertion(currentTime);
            urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

            // Re-send the updated request
            request = new BoxAPIRequest(this, url, "POST");
            request.shouldAuthenticate(false);
            request.setBody(urlParameters);

            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        }

        JsonObject jsonObject = JsonObject.readFrom(json);
        this.setAccessToken(jsonObject.get("access_token").asString());
        this.setLastRefresh(System.currentTimeMillis());
        this.setExpires(jsonObject.get("expires_in").asLong() * 1000);

        //if token cache is specified, save to cache
        if (this.accessTokenCache != null) {
            String key = this.getAccessTokenCacheKey();
            JsonObject accessTokenCacheInfo = new JsonObject()
                    .add("accessToken", this.getAccessToken())
                    .add("lastRefresh", this.getLastRefresh())
                    .add("expires", this.getExpires());

            this.accessTokenCache.put(key, accessTokenCacheInfo.toString());
        }
    }
1321012
protected function refreshToken(TokenInterface $expiredToken, ResourceOwnerInterface $resourceOwner)
    {
        if (!$expiredToken->getRefreshToken()) {
            return $expiredToken;
        }

        $token = new OAuthToken($resourceOwner->refreshAccessToken($expiredToken->getRefreshToken()));
        $token->setRefreshToken($expiredToken->getRefreshToken());
        $this->tokenStorage->setToken($token);

        return $token;
    }
497016
protected function onAfterWrite() {
        parent::onAfterWrite();
        
        
        //Clean up the expired tokens
        $expiredTokens=KapostPreviewToken::get()->filter('Created:LessThan', date('Y-m-d H:i:s', strtotime('-'.KapostService::config()->preview_token_expiry.' minutes')));
        if($expiredTokens->count()>0) {
            foreach($expiredTokens as $token) {
                $token->delete();
            }
        }
    }
679111
private function assignExceptions(RequestException $ex)
    {
        if ($ex->hasResponse() && $ex->getResponse()->getStatusCode() == 401) {
            throw new TokenExpiredException('Salesforce token has expired', $ex);
        } elseif ($ex->hasResponse()) {
            throw new SalesforceException('Salesforce response error: '.$ex->getMessage(), $ex);
        } else {
            throw new SalesforceException('Invalid request: %s', $ex);
        }
    }