// RenewSession extends the expire time to newExpiration.
438573
func (c *Client) RenewSession(ctx context.Context, session *platform.Session, newExpiration time.Time) error {
	op := getOp(platform.OpRenewSession)
	if session == nil {
		return &platform.Error{
			Op:  op,
			Msg: "session is nil",
		}
	}
	return c.db.Update(func(tx *bolt.Tx) error {
		session.ExpiresAt = newExpiration
		if err := c.putSession(ctx, tx, session); err != nil {
			return &platform.Error{
				Op:  op,
				Err: err,
			}
		}
		return nil
	})
}
841889
func (u *UserV2) Expiry() time.Time {
	if u.Metadata.Expires != nil && !u.Metadata.Expires.IsZero() {
		return *u.Metadata.Expires
	}
	return u.Spec.Expires
}
845295
func (e *Kex2Provisionee) updateTemporarySession(m libkb.MetaContext, uv keybase1.UserVersion) (err error) {
	defer m.Trace("Kex2Provisionee#updateTemporarySession", func() error { return err })()
	m.Debug("login context: %T %+v", m.LoginContext(), m.LoginContext())
	return m.LoginContext().SaveState(string(e.sessionToken), string(e.csrfToken), libkb.NewNormalizedUsername(e.username), uv, e.device.ID)
}
315262
func NewRepoWithSession(session *mgo.Session, dbPrefix, collection string) (*Repo, error) {
	if session == nil {
		return nil, ErrNoDBSession
	}

	r := &Repo{
		session:    session,
		dbPrefix:   dbPrefix,
		collection: collection,
	}

	return r, nil
}
1071009
func (p *provider) newSession(sid string, expires time.Duration) *Session {
	onExpire := func() {
		p.Destroy(sid)
	}

	lifetime := p.db.Acquire(sid, expires)

	// simple and straight:
	if !lifetime.IsZero() {
		// if stored time is not zero
		// start a timer based on the stored time, if not expired.
		lifetime.Revive(onExpire)
	} else {
		// Remember:  if db not exist or it has been expired
		// then the stored time will be zero(see loadSessionFromDB) and the values will be empty.
		//
		// Even if the database has an unlimited session (possible by a previous app run)
		// priority to the "expires" is given,
		// again if <=0 then it does nothing.
		lifetime.Begin(expires, onExpire)
	}

	sess := &Session{
		sid:      sid,
		provider: p,
		flashes:  make(map[string]*flashMessage),
		Lifetime: lifetime,
	}

	return sess
}
745366
func (c *Client) Renew(ack *dhcp4.Packet) (*dhcp4.Packet, error) {
	return c.SendAndReadOne(c.RequestPacket(ack))
}
554427
func (v *vaultClient) renew() (bool, error) {
	// Track how long the request takes
	defer metrics.MeasureSince([]string{"nomad", "vault", "renew"}, time.Now())

	// Attempt to renew the token
	secret, err := v.auth.RenewSelf(v.tokenData.CreationTTL)
	if err != nil {
		// Check if there is a permission denied
		recoverable := !structs.VaultUnrecoverableError.MatchString(err.Error())
		return recoverable, fmt.Errorf("failed to renew the vault token: %v", err)
	}

	if secret == nil {
		// It's possible for RenewSelf to return (nil, nil) if the
		// response body from Vault is empty.
		return true, fmt.Errorf("renewal failed: empty response from vault")
	}

	// these treated as transient errors, where can keep renewing
	auth := secret.Auth
	if auth == nil {
		return true, fmt.Errorf("renewal successful but not auth information returned")
	} else if auth.LeaseDuration == 0 {
		return true, fmt.Errorf("renewal successful but no lease duration returned")
	}

	v.extendExpiration(auth.LeaseDuration)

	v.logger.Debug("successfully renewed server token")
	return true, nil
}
699005
func (db *TowerDB) DeleteSession(target wtdb.SessionID) error {
	db.mu.Lock()
	defer db.mu.Unlock()

	// Fail if the session doesn't exit.
	if _, ok := db.sessions[target]; !ok {
		return wtdb.ErrSessionNotFound
	}

	// Remove the target session.
	delete(db.sessions, target)

	// Remove the state updates for any blobs stored under the target
	// session identifier.
	for hint, sessionUpdates := range db.blobs {
		delete(sessionUpdates, target)

		// If this was the last state update, we can also remove the
		// hint that would map to an empty set.
		if len(sessionUpdates) == 0 {
			delete(db.blobs, hint)
		}
	}

	return nil
}
1339691
func (mc *mysqlConn) ResetSession(ctx context.Context) error {
	if mc.closed.IsSet() {
		return driver.ErrBadConn
	}
	mc.reset = true
	return nil
}
631869
func (c *Client) Renew(ctx context.Context, req TokenRequest) (*Signer, error) {
	s := &Signer{
		Certificate: req.Certificate,
	}

	rst, err := c.newRequest(req, "Renew", s)
	if err != nil {
		return nil, err
	}

	if req.Token == "" {
		return nil, errors.New("TokenRequest Token is required")
	}

	rst.RenewTarget = &internal.Target{Token: req.Token}

	header := soap.Header{
		Security: s,
		Action:   rst.Action(),
	}

	res, err := internal.Renew(c.WithHeader(ctx, header), c, &rst)
	if err != nil {
		return nil, err
	}

	s.Token = res.RequestedSecurityToken.Assertion

	return s, s.setLifetime(res.Lifetime)
}
1222410
func (t *TokenRenewer) renewDuration() time.Duration {
	return t.validUntil.Add(-renewBefore).Sub(time.Now().UTC())
}
108044
func (c *ACMEClient) Renew(name string) error {
	// Get access to ACME storage
	storage, err := c.config.StorageFor(c.config.CAUrl)
	if err != nil {
		return err
	}

	waiter, err := storage.TryLock(name)
	if err != nil {
		return err
	}
	if waiter != nil {
		log.Printf("[INFO] Certificate for %s is already being renewed elsewhere and stored; waiting", name)
		waiter.Wait()
		return nil // we assume the process with the lock succeeded, rather than hammering this execution path again
	}
	defer func() {
		if err := storage.Unlock(name); err != nil {
			log.Printf("[ERROR] Unable to unlock renew call for %s: %v", name, err)
		}
	}()

	// Prepare for renewal (load PEM cert, key, and meta)
	siteData, err := storage.LoadSite(name)
	if err != nil {
		return err
	}
	var certMeta acme.CertificateResource
	err = json.Unmarshal(siteData.Meta, &certMeta)
	certMeta.Certificate = siteData.Cert
	certMeta.PrivateKey = siteData.Key

	// Perform renewal and retry if necessary, but not too many times.
	var newCertMeta acme.CertificateResource
	var success bool
	for attempts := 0; attempts < 2; attempts++ {
		namesObtaining.Add([]string{name})
		acmeMu.Lock()
		newCertMeta, err = c.acmeClient.RenewCertificate(certMeta, true, c.config.MustStaple)
		acmeMu.Unlock()
		namesObtaining.Remove([]string{name})
		if err == nil {
			success = true
			break
		}

		// If the legal terms were updated and need to be
		// agreed to again, we can handle that.
		if _, ok := err.(acme.TOSError); ok {
			err := c.acmeClient.AgreeToTOS()
			if err != nil {
				return err
			}
			continue
		}

		// For any other kind of error, wait 10s and try again.
		wait := 10 * time.Second
		log.Printf("[ERROR] Renewing: %v; trying again in %s", err, wait)
		time.Sleep(wait)
	}

	if !success {
		return errors.New("too many renewal attempts; last error: " + err.Error())
	}

	return saveCertResource(storage, newCertMeta)
}
399767
func (cp *ConsulClient) renewService(keyName, ttl, sessionID string, jsonVal []byte, stopChan chan struct{}) {
	for {
		err := cp.client.Session().RenewPeriodic(ttl, sessionID, nil, stopChan)
		if err == nil {
			log.Infof("Stoping renew on %s", keyName)
			return
		}
		log.Infof("RenewPeriodic for session %s exited with error: %v. Retrying..", keyName, err)

		// session configuration
		sessCfg := api.SessionEntry{
			Name:      keyName,
			Behavior:  "delete",
			LockDelay: 10 * time.Millisecond,
			TTL:       ttl,
		}

		// Create consul session
		sessionID, _, err = cp.client.Session().CreateNoChecks(&sessCfg, nil)
		if err != nil {
			log.Errorf("Error Creating session for lock %s. Err: %v", keyName, err)
		}

		// Delete the old key if it exists..
		log.Infof("Deleting old service entry for key %s", keyName)
		_, err = cp.client.KV().Delete(keyName, nil)
		if err != nil {
			log.Errorf("Error deleting key %s. Err: %v", keyName, err)
		}

		// Set it via consul client
		succ, _, err := cp.client.KV().Acquire(&api.KVPair{Key: keyName, Value: jsonVal, Session: sessionID}, nil)
		if err != nil {
			log.Errorf("Error setting key %s, Err: %v", keyName, err)
		} else if !succ {
			log.Errorf("Failed to acquire key %s. Already acquired", keyName)
		}
	}
}
280684
func (nd *Node) refreshSessionToken() error {
	// no session token to refresh
	if !nd.cluster.clientPolicy.RequiresAuthentication() || nd.cluster.clientPolicy.AuthMode != AuthModeExternal {
		return nil
	}

	var deadline time.Time
	deadlineIfc := nd._sessionExpiration.Load()
	if deadlineIfc != nil {
		deadline = deadlineIfc.(time.Time)
	}

	if deadline.IsZero() || time.Now().Before(deadline) {
		return nil
	}

	nd.tendConnLock.Lock()
	defer nd.tendConnLock.Unlock()

	if err := nd.initTendConn(nd.cluster.clientPolicy.LoginTimeout); err != nil {
		return err
	}

	command := newLoginCommand(nd.tendConn.dataBuffer)
	if err := command.login(&nd.cluster.clientPolicy, nd.tendConn, nd.cluster.Password()); err != nil {
		// Socket not authenticated. Do not put back into pool.
		nd.tendConn.Close()
		return err
	}

	nd._sessionToken.Store(command.SessionToken)
	nd._sessionExpiration.Store(command.SessionExpiration)

	return nil
}
454702
func (m *ExpirationManager) renewAuthEntry(ctx context.Context, req *logical.Request, le *leaseEntry, increment time.Duration) (*logical.Response, error) {
	if le.ClientTokenType == logical.TokenTypeBatch {
		return logical.ErrorResponse("batch tokens cannot be renewed"), nil
	}

	auth := *le.Auth
	auth.IssueTime = le.IssueTime
	auth.Increment = increment
	if strings.HasPrefix(le.Path, "auth/token/") {
		auth.ClientToken = le.ClientToken
	} else {
		auth.ClientToken = ""
	}

	// Make sure we're operating in the right namespace
	nsCtx := namespace.ContextWithNamespace(ctx, le.namespace)

	authReq := logical.RenewAuthRequest(le.Path, &auth, nil)
	authReq.Connection = req.Connection
	resp, err := m.router.Route(nsCtx, authReq)
	if err != nil {
		return nil, errwrap.Wrapf("failed to renew entry: {{err}}", err)
	}
	return resp, nil
}
366845
func (d *DiskStorer) ResetExpiry(key string) error {
	if !validKey(key) {
		return errNoSession{}
	}

	filePath := path.Join(d.folderPath, key)
	nowTime := time.Now().UTC()

	return os.Chtimes(filePath, nowTime, nowTime)
}
1022079
func (r *RedisStorer) ResetExpiry(key string) error {
	return r.client.Expire(key, r.maxAge).Err()
}