// FindByToken finds a session by its token and returns it.
436390
func (r *sessionRepository) FindByToken(ctx context.Context, token string) (*sessions.Session, error) {
	conn := r.pool.Get()
	defer conn.Close()

	return getSession(conn, sessionKey(token))
}
1370151
func FindById(i interface{}, id string) error {
	return Find(i, bson.M{"_id": bson.ObjectIdHex(id)})
}
394789
func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	dcontext.GetLogger(ctx).Info("getToken")

	params := r.URL.Query()
	service := params.Get("service")
	scopeSpecifiers := params["scope"]
	var offline bool
	if offlineStr := params.Get("offline_token"); offlineStr != "" {
		var err error
		offline, err = strconv.ParseBool(offlineStr)
		if err != nil {
			handleError(ctx, ErrorBadTokenOption.WithDetail(err), w)
			return
		}
	}

	requestedAccessList := ResolveScopeSpecifiers(ctx, scopeSpecifiers)

	authorizedCtx, err := ts.accessController.Authorized(ctx, requestedAccessList...)
	if err != nil {
		challenge, ok := err.(auth.Challenge)
		if !ok {
			handleError(ctx, err, w)
			return
		}

		// Get response context.
		ctx, w = dcontext.WithResponseWriter(ctx, w)

		challenge.SetHeaders(r, w)
		handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail(challenge.Error()), w)

		dcontext.GetResponseLogger(ctx).Info("get token authentication challenge")

		return
	}
	ctx = authorizedCtx

	username := dcontext.GetStringValue(ctx, "auth.user.name")

	ctx = context.WithValue(ctx, acctSubject{}, username)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, acctSubject{}))

	dcontext.GetLogger(ctx).Info("authenticated client")

	ctx = context.WithValue(ctx, requestedAccess{}, requestedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, requestedAccess{}))

	grantedAccessList := filterAccessList(ctx, username, requestedAccessList)
	ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, grantedAccess{}))

	token, err := ts.issuer.CreateJWT(username, service, grantedAccessList)
	if err != nil {
		handleError(ctx, err, w)
		return
	}

	dcontext.GetLogger(ctx).Info("authorized client")

	response := tokenResponse{
		Token:     token,
		ExpiresIn: int(ts.issuer.Expiration.Seconds()),
	}

	if offline {
		response.RefreshToken = newRefreshToken()
		ts.refreshCache[response.RefreshToken] = refreshToken{
			subject: username,
			service: service,
		}
	}

	ctx, w = dcontext.WithResponseWriter(ctx, w)

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)

	dcontext.GetResponseLogger(ctx).Info("get token complete")
}
1060527
func GetToken(ctx context.Context) (string, error) {
	a, ok := ctx.Value(authorizerCtxKey).(platform.Authorizer)
	if !ok {
		return "", &platform.Error{
			Msg:  "authorizer not found on context",
			Code: platform.EInternal,
		}
	}

	auth, ok := a.(*platform.Authorization)
	if !ok {
		return "", &platform.Error{
			Msg:  fmt.Sprintf("authorizer not an authorization but a %T", a),
			Code: platform.EInternal,
		}
	}

	return auth.Token, nil
}
326135
func nextToken(in []byte) (*token, error) {
	left := in[:]
	parenCount := 0
	var cur token
	if len(left) == 0 {
		return nil, nil
	}

	if left[0] == '-' {
		return &token{
			Type:  tokNegate,
			Text:  []byte{'-'},
			Input: in[:1],
		}, nil
	}

	foundSpace := false

loop:
	for len(left) > 0 {
		c := left[0]
		switch c {
		case '(':
			parenCount++
			cur.Text = append(cur.Text, c)
			left = left[1:]
		case ')':
			if parenCount == 0 {
				if len(cur.Text) == 0 {
					cur.Text = []byte{')'}
					left = left[1:]
				}
				break loop
			}

			cur.Text = append(cur.Text, c)
			left = left[1:]
			parenCount--

		case '"':
			t, n, err := parseStringLiteral(left)
			if err != nil {
				return nil, err
			}
			cur.Text = append(cur.Text, t...)
			left = left[n:]
		case '\\':
			left = left[1:]
			if len(left) == 0 {
				return nil, fmt.Errorf("query: lone \\ at end")
			}
			c := left[0]
			cur.Text = append(cur.Text, '\\', c)
			left = left[1:]

		case ' ', '\n', '\t':
			if parenCount > 0 {
				foundSpace = true
			}
			break loop
		default:
			cur.Text = append(cur.Text, c)
			left = left[1:]
		}
	}

	if len(cur.Text) == 0 {
		return nil, nil
	}

	if foundSpace && cur.Text[0] == '(' {
		cur.Text = cur.Text[:1]
		cur.Input = in[:1]
	} else {
		cur.Input = in[:len(in)-len(left)]
	}
	cur.setType()
	return &cur, nil
}
961308
func (c *DiskTokenCache) GetToken(key *CacheKey) (*Token, error) {
	cache, err := c.readCacheFile()
	if err != nil {
		return nil, err
	}
	for _, entry := range cache.Cache {
		if EqualCacheKeys(&entry.Key, key) {
			return &Token{
				Token: entry.Token,
				Email: entry.Email,
			}, nil
		}
	}
	return nil, nil
}
1216283
func (s *Credentials) SetSessionToken(v string) *Credentials {
	s.SessionToken = &v
	return s
}
862099
func (r *sessionRepository) DeleteByOwnerToken(ctx context.Context, ownerToken string) ([]sessions.Session, error) {
	conn := r.pool.Get()
	defer conn.Close()

	deleted := []sessions.Session{}
	ownerSessionsKey := ownerSessionsKey(ownerToken)
	sessionKeys, err := redigo.Values(conn.Do("HKEYS", ownerSessionsKey))
	if err != nil {
		return nil, errors.Wrap(err, "could not get the ownerToken index")
	}
	if sessionKeys == nil || len(sessionKeys) == 0 {
		return deleted, nil
	}
	vals, err := redigo.ByteSlices(conn.Do("MGET", sessionKeys...))
	if err != nil {
		return nil, errors.Wrap(err, "could not get the sessions by ownerToken")
	}
	for _, val := range vals {
		session := sessions.Session{}
		if err := json.Unmarshal(val, &session); err != nil {
			return nil, errors.Wrap(err, "found session unmarshalling failed")
		}
		deleted = append(deleted, session)
	}
	if _, err := redigo.Int(conn.Do("DEL", append([]interface{}{ownerSessionsKey}, sessionKeys...)...)); err != nil {
		return nil, errors.Wrap(err, "could not delete the sessions by ownerToken")
	}
	return deleted, nil
}
1322577
func retrieveToken(ctx context.Context, c *Config, v url.Values) (*oauth2.Token, error) {
	tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.TokenURL, v)
	if err != nil {
		return nil, err
	}
	return tokenFromInternal(tk), nil
}
1125231
func (c ClientCookies) GetToken(r *http.Request) string {
	cookie, err := r.Cookie(c.Name)
	if err != nil {
		return ""
	}
	return cookie.Value
}
982670
func (session *SafeSession) Find(keyspace, shard string, tabletType topodatapb.TabletType) int64 {
	if session == nil {
		return 0
	}
	session.mu.Lock()
	defer session.mu.Unlock()
	for _, shardSession := range session.ShardSessions {
		if keyspace == shardSession.Target.Keyspace && tabletType == shardSession.Target.TabletType && shard == shardSession.Target.Shard {
			return shardSession.TransactionId
		}
	}
	return 0
}
607351
func (c *MemoryTokenCache) GetToken(key *CacheKey) (*Token, error) {
	k := key.ToMapKey()
	c.lock.RLock()
	tok, ok := c.cache[k]
	c.lock.RUnlock()
	if ok {
		return &tok, nil
	}
	return nil, nil
}
562775
func (l *Lexer) NextToken() (t token.Token) {
	l.skipWhitespace()
	typ := resolveTokenType(l.ch)
	t.Type = typ
	switch typ {
	case token.EOF:
		t.Literal = ""
	case token.IDENT:
		if isLetter(l.ch) {
			// letters
			lit := l.readIdentifier()
			typ := token.LookupIdent(lit)
			t = l.newToken(typ, lit)
			return
		}
		if isDigit(l.ch) {
			// numbers
			lit := l.readNumber()
			t = l.newToken(token.INT, lit)
			return
		}

		t = l.newTokenRune(token.ILLEGAL, l.ch)
	default:
		t = l.newTokenRune(typ, l.ch)
	}
	l.readChar() // set the pos to the next
	return
}
521032
func IsJwtToken(authstring string) bool {
	_, _, err := new(jwt.Parser).ParseUnverified(authstring, jwt.MapClaims{})
	return err == nil
}
150936
func GetSessionByUID(uid string) *Session {
	// TODO: Block this operation in backend servers
	if val, ok := sessionsByUID.Load(uid); ok {
		return val.(*Session)
	}
	return nil
}
1139037
func ExtractUserToken(opts ...interface{}) *opt.UserTokenOption {
	for _, o := range opts {
		if v, ok := o.(*opt.UserTokenOption); ok {
			return v
		}
	}
	return nil
}
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
}