// WithStorageSession returns a context that is logged into the storage
// platform.
197532
func WithStorageSession(parent context.Context) (types.Context, error) {

	pctx := New(parent)

	d, ok := MustDriver(parent).(types.StorageDriverWithLogin)
	if !ok {
		pctx.Debug("driver is not StorageDriverWithLogin")
		return pctx, nil
	}

	sess, err := d.Login(pctx)
	if err != nil {
		pctx.WithError(err).Error("error logging into storage driver")
		return nil, err
	}
	if sess == nil {
		pctx.Warn("session is nil")
		return pctx, nil
	}

	return newContext(pctx, SessionKey, sess, nil, nil), nil
}
1101376
func WithStorageBackendString(ctx context.Context, sb string) context.Context {
	return WithStorageBackend(ctx, storageBackendFromName(sb))
}
780319
func (s *Service) FindSession(ctx context.Context, key string) (*platform.Session, error) {
	result, found := s.sessionKV.Load(key)
	if !found {
		return nil, &platform.Error{
			Code: platform.ENotFound,
			Msg:  platform.ErrSessionNotFound,
		}
	}

	sess := new(platform.Session)
	*sess = result.(platform.Session)

	// TODO(desa): these values should be cached so it's not so expensive to lookup each time.
	f := platform.UserResourceMappingFilter{UserID: sess.UserID}
	mappings, _, err := s.FindUserResourceMappings(ctx, f)
	if err != nil {
		return nil, &platform.Error{
			Err: err,
		}
	}

	ps := make([]platform.Permission, 0, len(mappings))
	for _, m := range mappings {
		p, err := m.ToPermissions()
		if err != nil {
			return nil, &platform.Error{
				Err: err,
			}
		}

		ps = append(ps, p...)
	}
	ps = append(ps, platform.MePermissions(sess.UserID)...)
	sess.Permissions = ps
	return sess, nil
}
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
}
109946
func newSession(stor storage.Storage, o *opt.Options) (s *session, err error) {
	if stor == nil {
		return nil, os.ErrInvalid
	}
	storLock, err := stor.Lock()
	if err != nil {
		return
	}
	s = &session{
		stor:      newIStorage(stor),
		storLock:  storLock,
		refCh:     make(chan *vTask),
		relCh:     make(chan *vTask),
		deltaCh:   make(chan *vDelta),
		abandon:   make(chan int64),
		fileRefCh: make(chan chan map[int64]int),
		closeC:    make(chan struct{}),
	}
	s.setOptions(o)
	s.tops = newTableOps(s)

	s.closeW.Add(1)
	go s.refLoop()
	s.setVersion(nil, newVersion(s))
	s.log("log@legend F·NumFile S·FileSize N·Entry C·BadEntry B·BadBlock Ke·KeyError D·DroppedEntry L·Level Q·SeqNum T·TimeElapsed")
	return
}
1301033
func (session *Session) WithContext(ctx context.Context) *Session {
	s := *session
	s.context = ctx
	return &s
}
789751
func (o *UploadTaskFileParams) WithContext(ctx context.Context) *UploadTaskFileParams {
	o.SetContext(ctx)
	return o
}
623350
func WithUser(parent Context, user user.Info) Context {
	return WithValue(parent, userKey, user)
}
820758
func (b *backend) ResetSession(_ context.Context) {
	b.lock.Lock()
	defer b.lock.Unlock()

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

	b.session = nil
}
1120634
func (handle *ContextHandle) ReturnSession(session mPkcs11.SessionHandle) {

	handle.lock.RLock()
	defer handle.lock.RUnlock()

	_, e := handle.ctx.GetSessionInfo(session)
	if e != nil {
		logger.Warnf("not returning session [%d], due to error [%s]. Discarding it", session, e)
		e = handle.ctx.CloseSession(session)
		if e != nil {
			logger.Warn("unable to close session:", e)
		}
		return
	}

	select {
	case handle.sessions <- session:
		// returned session back to session cache
	default:
		// have plenty of sessions in cache, dropping
		e = handle.ctx.CloseSession(session)
		if e != nil {
			logger.Warn("unable to close session: ", e)
		}
	}
}
712692
func (t *Tokbox) NewSession(location string, mm MediaMode, ctx ...context.Context) (*Session, error) {
	params := url.Values{}

	if len(location) > 0 {
		params.Add("location", location)
	}

	params.Add("p2p.preference", string(mm))

	var endpoint string
	if t.BetaUrl == "" {
		endpoint = apiHost
	} else {
		endpoint = t.BetaUrl
	}
	req, err := http.NewRequest("POST", endpoint+apiSession, strings.NewReader(params.Encode()))
	if err != nil {
		return nil, err
	}

	//Create jwt token
	jwt, err := t.jwtToken()
	if err != nil {
		return nil, err
	}

	req.Header.Add("Accept", "application/json")
	req.Header.Add("X-OPENTOK-AUTH", jwt)

	if len(ctx) == 0 {
		ctx = append(ctx, nil)
	}
	res, err := client(ctx[0]).Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		return nil, fmt.Errorf("Tokbox returns error code: %v", res.StatusCode)
	}

	var s []Session
	if err = json.NewDecoder(res.Body).Decode(&s); err != nil {
		return nil, err
	}

	if len(s) < 1 {
		return nil, fmt.Errorf("Tokbox did not return a session")
	}

	o := s[0]
	o.T = t
	return &o, nil
}
14367
func newSession(parentCtx context.Context, c *asticontext.Canceller, d *dispatcher, i *identifier, w *writer) *Session {
	return &Session{object: newObject(parentCtx, c, d, i, w, i.new())}
}
712035
func (o *RevokeConsentSessionsParams) WithContext(ctx context.Context) *RevokeConsentSessionsParams {
	o.SetContext(ctx)
	return o
}
1041165
func (c *Ctx) WithContext(ctx context.Context) {
	c.request = c.request.WithContext(ctx)
}
1158222
func (c *Context) mapSession() {
	if cookie, err := c.req.Cookie(soap.SessionCookieName); err == nil {
		if val, ok := c.svc.sm.sessions[cookie.Value]; ok {
			c.SetSession(val, false)
		}
	}
}
731887
func (r *Request) WithContext(ctx context.Context) *Request {
	r.Request = r.Request.WithContext(ctx)
	return r
}
110850
func (c *Client) FindSession(ctx context.Context, key string) (*platform.Session, error) {
	op := getOp(platform.OpFindSession)
	var sess *platform.Session
	err := c.db.View(func(tx *bolt.Tx) error {
		s, err := c.findSession(ctx, tx, key)
		if err != nil {
			return err
		}

		sess = s
		return nil
	})

	if err != nil {
		return nil, &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	if err := sess.Expired(); err != nil {
		// todo(leodido) > do we want to return session also if expired?
		return sess, &platform.Error{
			Err: err,
			Op:  op,
		}
	}
	return sess, nil
}