// OpenSession create a new session for a user with given expiration time.
// It returns unique session ID.
772025
func (s *SessionStore) OpenSession(c context.Context, userID string, u *auth.User, exp time.Time) (string, error) {
	if strings.IndexByte(s.Prefix, '/') != -1 {
		return "", fmt.Errorf("gaeauth: bad prefix (%q) in SessionStore", s.Prefix)
	}
	if strings.IndexByte(userID, '/') != -1 {
		return "", fmt.Errorf("gaeauth: bad userID (%q), cannot have '/' inside", userID)
	}
	if err := u.Identity.Validate(); err != nil {
		return "", fmt.Errorf("gaeauth: bad identity string (%q) - %s", u.Identity, err)
	}
	c = defaultNS(c)

	now := clock.Now(c).UTC()
	prof := profile{
		Identity:  string(u.Identity),
		Superuser: u.Superuser,
		Email:     u.Email,
		Name:      u.Name,
		Picture:   u.Picture,
	}

	// Set in the transaction below.
	var sessionID string

	err := ds.RunInTransaction(ds.WithoutTransaction(c), func(c context.Context) error {
		// Grab existing userEntity or initialize a new one.
		userEnt := userEntity{ID: s.Prefix + "/" + userID}
		err := ds.Get(c, &userEnt)
		if err != nil && err != ds.ErrNoSuchEntity {
			return err
		}
		if err == ds.ErrNoSuchEntity {
			userEnt.Profile = prof
			userEnt.Created = now
		}
		userEnt.LastLogin = now

		// Make new session. ID will be generated by the datastore.
		sessionEnt := sessionEntity{
			Parent:     ds.KeyForObj(c, &userEnt),
			Profile:    prof,
			Created:    now,
			Expiration: exp.UTC(),
		}
		if err = ds.Put(c, &userEnt, &sessionEnt); err != nil {
			return err
		}

		sessionID = fmt.Sprintf("%s/%s/%d", s.Prefix, userID, sessionEnt.ID)
		return nil
	}, nil)

	if err != nil {
		return "", transient.Tag.Apply(err)
	}
	return sessionID, nil
}
440591
func (c *cmd) createSession() (string, error) {
	var id string
	var err error
	if c.conf.foreignDC {
		id, err = c.createSessionForeign()
	} else {
		id, err = c.createSessionLocal()
	}
	if err == nil {
		c.stopCh = make(chan struct{})
		go c.renewSession(id, c.stopCh)
	}
	return id, err
}
1213205
func (s *SecureChannelSession) open() (*responseAPDU, error) {
	return transmit(s.card, &commandAPDU{
		Cla:  claSCWallet,
		Ins:  insOpenSecureChannel,
		P1:   s.PairingIndex,
		P2:   0,
		Data: s.publicKey,
		Le:   0,
	})
}
1014794
func (c *Client) LogSessionCreate(appIdentity string, options *LogSessionCreateOpts) (*LogSession, error) {
	var logSessionRes LogSession
	return &logSessionRes, c.Post(&logSessionRes, "/apps/"+appIdentity+"/log-sessions", options)
}
448493
func (c *Client) NewSession() (*Session, error) {
	ch, in, err := c.OpenChannel("session", nil)
	if err != nil {
		return nil, err
	}
	return newSession(ch, in)
}
456355
func (mgr *MemorySessionManager) NewSession() (Session, error) {
	sid, err := mgr.sessionID()
	if err != nil {
		return nil, err
	}
	s := MemorySession{sid: sid, data: make(map[string]interface{}), createdAt: time.Now()}
	mgr.lock.Lock()
	mgr.sessions[sid] = &s
	mgr.lock.Unlock()
	return &s, nil
}
588077
func (s *SessionService) CreateSession(ctx context.Context, user string) (*platform.Session, error) {
	return s.CreateSessionFn(ctx, user)
}
1004088
func (s *StorageOverseer) ResetExpiry(w http.ResponseWriter, r *http.Request) error {
	sessID, err := s.options.getCookieValue(w, r)
	if err != nil {
		return errors.Wrap(err, "unable to get session id from cookie")
	}

	// Reset the expiry of the server-side session
	err = s.Storer.ResetExpiry(sessID)
	if err != nil {
		return errors.Wrap(err, "unable to reset expiry of server side session")
	}

	// Reset the expiry in the client-side cookie
	if s.options.MaxAge != 0 {
		w.(cookieWriter).SetCookie(s.options.makeCookie(sessID))
	}

	return nil
}
936114
func (s *Session) Open() (net.Conn, error) {
	conn, err := s.OpenStream()
	if err != nil {
		return nil, err
	}
	return conn, nil
}
1223921
func (s *SessionService) ExpireSession(ctx context.Context, key string) error {
	return s.ExpireSessionFn(ctx, key)
}
936924
func StartSession(ctx context.Context) context.Context {
	sessionTrackerOnce.Do(startSessionTracking)
	return sessionTracker.StartSession(ctx)
}
945786
func (s *Session) Expired() error {
	if time.Now().After(s.ExpiresAt) {
		return fmt.Errorf(ErrSessionExpired)
	}

	return nil
}
1036385
func (s *Session) Open() error {
	s.log(LogInformational, "called")

	var err error

	// Prevent Open or other major Session functions from
	// being called while Open is still running.
	s.Lock()
	defer s.Unlock()

	// If the websock is already open, bail out here.
	if s.wsConn != nil {
		return ErrWSAlreadyOpen
	}

	// Get the gateway to use for the Websocket connection
	if s.gateway == "" {
		s.gateway, err = s.Gateway()
		if err != nil {
			return err
		}

		// Add the version and encoding to the URL
		s.gateway = s.gateway + "?v=" + APIVersion + "&encoding=json"
	}

	// Connect to the Gateway
	s.log(LogInformational, "connecting to gateway %s", s.gateway)
	header := http.Header{}
	header.Add("accept-encoding", "zlib")
	s.wsConn, _, err = websocket.DefaultDialer.Dial(s.gateway, header)
	if err != nil {
		s.log(LogWarning, "error connecting to gateway %s, %s", s.gateway, err)
		s.gateway = "" // clear cached gateway
		s.wsConn = nil // Just to be safe.
		return err
	}

	s.wsConn.SetCloseHandler(func(code int, text string) error {
		return nil
	})

	defer func() {
		// because of this, all code below must set err to the error
		// when exiting with an error :)  Maybe someone has a better
		// way :)
		if err != nil {
			s.wsConn.Close()
			s.wsConn = nil
		}
	}()

	// The first response from Discord should be an Op 10 (Hello) Packet.
	// When processed by onEvent the heartbeat goroutine will be started.
	mt, m, err := s.wsConn.ReadMessage()
	if err != nil {
		return err
	}
	e, err := s.onEvent(mt, m)
	if err != nil {
		return err
	}
	if e.Operation != 10 {
		err = fmt.Errorf("expecting Op 10, got Op %d instead", e.Operation)
		return err
	}
	s.log(LogInformational, "Op 10 Hello Packet received from Discord")
	s.LastHeartbeatAck = time.Now().UTC()
	var h helloOp
	if err = json.Unmarshal(e.RawData, &h); err != nil {
		err = fmt.Errorf("error unmarshalling helloOp, %s", err)
		return err
	}

	// Now we send either an Op 2 Identity if this is a brand new
	// connection or Op 6 Resume if we are resuming an existing connection.
	sequence := atomic.LoadInt64(s.sequence)
	if s.sessionID == "" && sequence == 0 {

		// Send Op 2 Identity Packet
		err = s.identify()
		if err != nil {
			err = fmt.Errorf("error sending identify packet to gateway, %s, %s", s.gateway, err)
			return err
		}

	} else {

		// Send Op 6 Resume Packet
		p := resumePacket{}
		p.Op = 6
		p.Data.Token = s.Token
		p.Data.SessionID = s.sessionID
		p.Data.Sequence = sequence

		s.log(LogInformational, "sending resume packet to gateway")
		s.wsMutex.Lock()
		err = s.wsConn.WriteJSON(p)
		s.wsMutex.Unlock()
		if err != nil {
			err = fmt.Errorf("error sending gateway resume packet, %s, %s", s.gateway, err)
			return err
		}

	}

	// A basic state is a hard requirement for Voice.
	// We create it here so the below READY/RESUMED packet can populate
	// the state :)
	// XXX: Move to New() func?
	if s.State == nil {
		state := NewState()
		state.TrackChannels = false
		state.TrackEmojis = false
		state.TrackMembers = false
		state.TrackRoles = false
		state.TrackVoice = false
		s.State = state
	}

	// Now Discord should send us a READY or RESUMED packet.
	mt, m, err = s.wsConn.ReadMessage()
	if err != nil {
		return err
	}
	e, err = s.onEvent(mt, m)
	if err != nil {
		return err
	}
	if e.Type != `READY` && e.Type != `RESUMED` {
		// This is not fatal, but it does not follow their API documentation.
		s.log(LogWarning, "Expected READY/RESUMED, instead got:\n%#v\n", e)
	}
	s.log(LogInformational, "First Packet:\n%#v\n", e)

	s.log(LogInformational, "We are now connected to Discord, emitting connect event")
	s.handleEvent(connectEventType, &Connect{})

	// A VoiceConnections map is a hard requirement for Voice.
	// XXX: can this be moved to when opening a voice connection?
	if s.VoiceConnections == nil {
		s.log(LogInformational, "creating new VoiceConnections map")
		s.VoiceConnections = make(map[string]*VoiceConnection)
	}

	// Create listening chan outside of listen, as it needs to happen inside the
	// mutex lock and needs to exist before calling heartbeat and listen
	// go rountines.
	s.listening = make(chan interface{})

	// Start sending heartbeats and reading messages from Discord.
	go s.heartbeat(s.wsConn, s.listening, h.HeartbeatInterval)
	go s.listen(s.wsConn, s.listening)

	s.log(LogInformational, "exiting")
	return nil
}
1255304
func (c *Client) CloseSession() {
	c.Pool.Close()
	currClient = nil
	once = sync.Once{}
}
831282
func (m *SessionManager) Create(user User) (session Session) {
	// Set the expires from the cookie config
	session = Session{
		Expires: m.nowFunc().Add(m.cookie.Age),
		UserID:  user.ID,
		manager: m,
	}

	// Generate a new random session key
	for {
		session.Key = m.keyFunc()

		// No duplicates - generate a new key if this key already exists
		var duplicate string
		stmt := sol.Select(
			Sessions.C("key"),
		).Where(Sessions.C("key").Equals(session.Key)).Limit(1)
		m.conn.Query(stmt, &duplicate)
		if duplicate == "" {
			break
		}
	}

	// Insert the session
	m.conn.Query(Sessions.Insert().Values(session))
	return
}
144178
func (engine *Engine) NewSession() *Session {
	session := &Session{engine: engine}
	session.Init()
	return session
}
91018
func NewSession(ro *RequestOptions) *Session {
	if ro == nil {
		ro = &RequestOptions{}
	}

	ro.UseCookieJar = true

	return &Session{RequestOptions: ro, HTTPClient: BuildHTTPClient(*ro)}
}