// Regenerate a new session ID for your current session
331089
func (s *StorageOverseer) Regenerate(w http.ResponseWriter, r *http.Request) error {
	id, err := s.options.getCookieValue(w, r)
	if err != nil {
		return errors.Wrap(err, "unable to get session id from cookie")
	}

	val, err := s.Storer.Get(id)
	if err != nil {
		return errors.Wrap(err, "unable to get session value")
	}

	// Delete the old session
	_ = s.Storer.Del(id)

	// Generate a new ID
	id = uuid.NewV4().String()

	// Create a new session with the old value
	if err = s.Storer.Set(id, val); err != nil {
		return errors.Wrap(err, "unable to set session value")
	}

	// Override the old cookie with the new cookie
	w.(cookieWriter).SetCookie(s.options.makeCookie(id))

	return nil
}
1135429
func (s *Server) invalidateSession(id string) {
	defer metrics.MeasureSince([]string{"session_ttl", "invalidate"}, time.Now())

	// Clear the session timer
	s.sessionTimers.Del(id)

	// Create a session destroy request
	args := structs.SessionRequest{
		Datacenter: s.config.Datacenter,
		Op:         structs.SessionDestroy,
		Session: structs.Session{
			ID: id,
		},
	}

	// Retry with exponential backoff to invalidate the session
	for attempt := uint(0); attempt < maxInvalidateAttempts; attempt++ {
		_, err := s.raftApply(structs.SessionRequestType, args)
		if err == nil {
			s.logger.Printf("[DEBUG] consul.state: Session %s TTL expired", id)
			return
		}

		s.logger.Printf("[ERR] consul.session: Invalidation failed: %v", err)
		time.Sleep((1 << attempt) * invalidateRetryBase)
	}
	s.logger.Printf("[ERR] consul.session: maximum revoke attempts reached for session: %s", id)
}
281835
func (c *Conn) LockSession(id string) {
	c.object.Call(dbusInterface+".LockSession", 0, id)
}
554636
func (p *FileProvider) Regenerate(oldsid, sid string) (_ RawStore, err error) {
	if err := p.regenerate(oldsid, sid); err != nil {
		return nil, err
	}

	return p.Read(sid)
}
1267592
func (id *InsertIDGenerator) Generate() string {
	prefix := id.Prefix
	if prefix == "" {
		prefix = defaultPrefix
	}
	c := atomic.AddInt64(&id.Counter, 1)
	return fmt.Sprintf("%s:%d", prefix, c)
}
643001
func (c *cmd) renewSession(id string, stopCh chan struct{}) {
	session := c.apiclient.Session()
	for {
		select {
		case <-time.After(rExecRenewInterval):
			_, _, err := session.Renew(id, nil)
			if err != nil {
				c.UI.Error(fmt.Sprintf("Session renew failed: %v", err))
				return
			}
		case <-stopCh:
			return
		}
	}
}
16597
func New(user, key string, nick ...string) (s *Session, err error) {
	var sessionName string
	if len(nick) > 0 {
		sessionName = nick[0]
	}

	s = &Session{
		User: user,
		Key:  key,
		Nick: sessionName,
	}

	params, err := json.Marshal(s)
	if err != nil {
		return
	}

	response, err := http.Post(createURL, "application/json", bytes.NewBuffer(params))
	if err != nil {
		return
	}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}

	m := map[string]string{}
	err = json.Unmarshal([]byte(body), &m)
	if err != nil {
		return
	}

	if m["status"] == "success" {
		s.Nick = m["nick"]
	} else {
		err = fmt.Errorf(m["status"])
		return
	}

	return
}
242735
func (s *Session) RenewPeriodic(initialTTL string, id string, q *WriteOptions, doneCh <-chan struct{}) error {
	ctx := q.Context()

	ttl, err := time.ParseDuration(initialTTL)
	if err != nil {
		return err
	}

	waitDur := ttl / 2
	lastRenewTime := time.Now()
	var lastErr error
	for {
		if time.Since(lastRenewTime) > ttl {
			return lastErr
		}
		select {
		case <-time.After(waitDur):
			entry, _, err := s.Renew(id, q)
			if err != nil {
				waitDur = time.Second
				lastErr = err
				continue
			}
			if entry == nil {
				return ErrSessionExpired
			}

			// Handle the server updating the TTL
			ttl, _ = time.ParseDuration(entry.TTL)
			waitDur = ttl / 2
			lastRenewTime = time.Now()

		case <-doneCh:
			// Attempt a session destroy
			s.Destroy(id, q)
			return nil

		case <-ctx.Done():
			// Bail immediately since attempting the destroy would
			// use the canceled context in q, which would just bail.
			return ctx.Err()
		}
	}
}
820758
func (b *backend) ResetSession(_ context.Context) {
	b.lock.Lock()
	defer b.lock.Unlock()

	if b.session != nil {
		b.session.Close()
	}

	b.session = nil
}
848225
func (kv *consulKV) renewSession(
	pair *api.KVPair,
	ttl uint64,
	noCreate bool,
) (string, error) {
	// Check if there is any previous session with an active TTL
	session, err := kv.getActiveSession(pair.Key)
	if err != nil {
		logrus.Infof("Failed to find session: %v", err)
		return "", err
	}

	if session != "" {
		if noCreate {
			// Do not create new session for the key
			return "", kvdb.ErrModified
		}
		// Destroy the existing session associated with the key
		kv.client.Destroy(session, nil)
	}

	durationTTL := time.Duration(int64(ttl)) * time.Second

	entry := &api.SessionEntry{
		Behavior:  api.SessionBehaviorDelete, // Delete the key when the session expires
		TTL:       durationTTL.String(),
		LockDelay: 0, // Virtually disable lock delay
	}

	// Create the key session
	session, _, err = kv.client.Create(entry, nil)

	// Session timer is started after a call to "Renew"
	kv.client.Renew(session, nil)

	return session, err
}
1255787
func Regenerate(c *client.Client, username string, all bool) (string, error) {
	var reqBody []byte
	var err error

	if all == true {
		reqBody, err = json.Marshal(api.AuthRegenerateRequest{All: all})
	} else if username != "" {
		reqBody, err = json.Marshal(api.AuthRegenerateRequest{Name: username})
	}

	if err != nil {
		return "", err
	}

	body, err := c.BasicRequest("POST", "/v1/auth/tokens/", reqBody)

	if err != nil {
		return "", err
	}

	if all == true {
		return "", nil
	}

	token := api.AuthRegenerateResponse{}
	if err = json.Unmarshal([]byte(body), &token); err != nil {
		return "", err
	}

	return token.Token, nil
}
3492
func (e *Endpoint) Regenerate(owner Owner, regenMetadata *ExternalRegenerationMetadata) <-chan bool {
	done := make(chan bool, 1)

	var (
		ctx   context.Context
		cFunc context.CancelFunc
	)

	if regenMetadata.ParentContext != nil {
		ctx, cFunc = context.WithCancel(regenMetadata.ParentContext)
	} else {
		ctx, cFunc = context.WithCancel(context.Background())
	}

	regenContext := regenMetadata.toRegenerationContext(ctx, cFunc)

	epEvent := eventqueue.NewEvent(&EndpointRegenerationEvent{
		owner:        owner,
		regenContext: regenContext,
		ep:           e,
	})

	// This may block if the Endpoint's EventQueue is full. This has to be done
	// synchronously as some callers depend on the fact that the event is
	// synchronously enqueued.
	resChan := e.EventQueue.Enqueue(epEvent)

	go func() {

		// Free up resources with context.
		defer cFunc()

		var buildSuccess bool
		var regenError error

		select {
		case result, ok := <-resChan:
			if ok {
				regenResult := result.(*EndpointRegenerationResult)
				regenError = regenResult.err
				buildSuccess = regenError == nil
			} else {
				// This may be unnecessary(?) since 'closing' of the results
				// channel means that event has been cancelled?
				e.getLogger().Debug("regeneration was cancelled")
			}
		}

		done <- buildSuccess
		close(done)
	}()

	return done
}
653484
func New(name string, keys []string) *Session {
	session := Session{
		data:   make(map[interface{}]interface{}),
		Cookie: &http.Cookie{Name: name},
		keys:   keys,
	}
	return &session
}
249078
func NewRequestID() (string, error) {
	id, err := uuid.NewV4()
	if err != nil {
		return "", err
	}

	return strings.Replace(id.String(), "-", "", -1), nil
}
1194099
func (s *Server) resetSessionTimer(id string, session *structs.Session) error {
	// Fault the session in if not given
	if session == nil {
		state := s.fsm.State()
		_, s, err := state.SessionGet(nil, id)
		if err != nil {
			return err
		}
		if s == nil {
			return fmt.Errorf("Session '%s' not found", id)
		}
		session = s
	}

	// Bail if the session has no TTL, fast-path some common inputs
	switch session.TTL {
	case "", "0", "0s", "0m", "0h":
		return nil
	}

	// Parse the TTL, and skip if zero time
	ttl, err := time.ParseDuration(session.TTL)
	if err != nil {
		return fmt.Errorf("Invalid Session TTL '%s': %v", session.TTL, err)
	}
	if ttl == 0 {
		return nil
	}

	s.createSessionTimer(session.ID, ttl)
	return nil
}
1297669
func RegenerateRecoveryCodes(userID int64) error {
	recoveryCodes, err := generateRecoveryCodes(userID)
	if err != nil {
		return fmt.Errorf("generateRecoveryCodes: %v", err)
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = deleteRecoveryCodesByUserID(sess, userID); err != nil {
		return fmt.Errorf("deleteRecoveryCodesByUserID: %v", err)
	} else if _, err = sess.Insert(recoveryCodes); err != nil {
		return fmt.Errorf("insert new recovery codes: %v", err)
	}

	return sess.Commit()
}
891096
func (p *LedisProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
	if p.Exist(sid) {
		return nil, fmt.Errorf("new sid '%s' already exists", sid)
	}

	kvs := make([]byte, 0)
	if p.Exist(oldsid) {
		if kvs, err = p.c.Get([]byte(oldsid)); err != nil {
			return nil, err
		} else if _, err = p.c.Del([]byte(oldsid)); err != nil {
			return nil, err
		}
	}
	if err = p.c.SetEX([]byte(sid), p.expire, kvs); err != nil {
		return nil, err
	}

	var kv map[interface{}]interface{}
	if len(kvs) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		kv, err = session.DecodeGob([]byte(kvs))
		if err != nil {
			return nil, err
		}
	}

	return NewLedisStore(p.c, sid, p.expire, kv), nil
}