/*
Usage:
   man := createTokenManager()
   bearer := man.getBearerToken()
   will automatically update config(configBearerToken) for other modules
*/
15379
func createApidTokenManager(isNewInstance bool) *apidTokenManager {
	isClosedInt := int32(0)

	t := &apidTokenManager{
		quitPollingForToken: make(chan bool, 1),
		closed:              make(chan bool),
		getTokenChan:        make(chan bool),
		invalidateTokenChan: make(chan bool),
		returnTokenChan:     make(chan *OauthToken),
		invalidateDone:      make(chan bool),
		tokenUpdatedChan:    make(chan bool, 1),
		isClosed:            &isClosedInt,
		isNewInstance:       isNewInstance,
	}
	return t
}
690263
func DefaultTokenHelper() (token.TokenHelper, error) {
	config, err := LoadConfig("")
	if err != nil {
		return nil, err
	}

	path := config.TokenHelper
	if path == "" {
		return &token.InternalTokenHelper{}, nil
	}

	path, err = token.ExternalTokenHelperPath(path)
	if err != nil {
		return nil, err
	}
	return &token.ExternalTokenHelper{BinaryPath: path}, nil
}
311433
func (s *MessageResult) SetUpdatedToken(v string) *MessageResult {
	s.UpdatedToken = &v
	return s
}
904662
func (c *UserConfig) GetToken() (string, string) {
	if c.AccessTokenKey != "" {
		return c.AccessTokenKey, c.AccessTokenSecret
	}
	if c.RequestTokenKey != "" {
		return c.RequestTokenKey, c.RequestTokenSecret
	}
	return "", ""
}
253176
func (t *apidTokenManager) invalidateToken() {
	log.Debug("invalidating token")
	t.invalidateTokenChan <- true
	<-t.invalidateDone
}
378699
func NewBearerAuthorizer(a *config.Azure, scope string) (*autorest.BearerAuthorizer, error) {
	oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, a.TenantID)
	if err != nil {
		log.Printf("Error trying to create new OAuth Config:%s\n", err)
		return nil, err
	}
	token, err := adal.NewServicePrincipalToken(*oauthConfig, a.ClientID, a.ClientSecret, scope)
	if err != nil {
		log.Printf("Error trying to create New Service Principal Token:%s", err)
		return nil, err
	}
	return autorest.NewBearerAuthorizer(token), nil
}
931192
func GetManagerForChain(chainID string) msp.MSPManager {
	m.Lock()
	defer m.Unlock()

	mspMgr, ok := mspMap[chainID]
	if !ok {
		mspLogger.Debugf("Created new msp manager for channel `%s`", chainID)
		mspMgmtMgr := &mspMgmtMgr{msp.NewMSPManager(), false}
		mspMap[chainID] = mspMgmtMgr
		mspMgr = mspMgmtMgr
	} else {
		// check for internal mspManagerImpl and mspMgmtMgr types. if a different
		// type is found, it's because a developer has added a new type that
		// implements the MSPManager interface and should add a case to the logic
		// above to handle it.
		if !(reflect.TypeOf(mspMgr).Elem().Name() == "mspManagerImpl" || reflect.TypeOf(mspMgr).Elem().Name() == "mspMgmtMgr") {
			panic("Found unexpected MSPManager type.")
		}
		mspLogger.Debugf("Returning existing manager for channel '%s'", chainID)
	}
	return mspMgr
}
232984
func AccessTokenWithManager(s string, manager tokens.Manager) Strategy {
	return &accessToken{
		accessToken: s,
		manager:     manager,
	}
}
1142768
func (p *tokenManager) CreateTokenFromCertificate(cert *x509.Certificate, tags []string) ([]byte, error) {

	// Combine the application claims with the standard claims
	claims := &verifierClaims{
		X:    cert.PublicKey.(*ecdsa.PublicKey).X,
		Y:    cert.PublicKey.(*ecdsa.PublicKey).Y,
		Tags: tags,
	}
	claims.ExpiresAt = cert.NotAfter.Unix()

	// Create the token and sign with our key
	strtoken, err := jwt.NewWithClaims(p.signMethod, claims).SignedString(p.privateKey)
	if err != nil {
		return []byte{}, err
	}

	return []byte(strtoken), nil
}
1056204
func NewAuthToken(signer Signer, tokenType string, expireIn int,
	submoduleName, version string, rh AuthTokenRefreshHandler) *AuthToken {
	clientName := fmt.Sprintf("go %s %s %s",
		submoduleName, libkb.GetPlatformString(), runtime.GOARCH)
	authToken := &AuthToken{
		signer:         signer,
		tokenType:      tokenType,
		expireIn:       expireIn,
		clientName:     clientName,
		clientVersion:  version,
		refreshHandler: rh,
	}
	return authToken
}
607960
func (c *NodeupModelContext) UseBootstrapTokens() bool {
	if c.IsMaster {
		return fi.BoolValue(c.Cluster.Spec.KubeAPIServer.EnableBootstrapAuthToken)
	}

	return c.Cluster.Spec.Kubelet != nil && c.Cluster.Spec.Kubelet.BootstrapKubeconfig != ""
}
972927
func (s *AuthServer) GenerateToken(req GenerateTokenRequest) (string, error) {
	if err := req.CheckAndSetDefaults(); err != nil {
		return "", trace.Wrap(err)
	}
	token, err := services.NewProvisionToken(req.Token, req.Roles, s.clock.Now().UTC().Add(req.TTL))
	if err != nil {
		return "", trace.Wrap(err)
	}
	if err := s.Provisioner.UpsertToken(token); err != nil {
		return "", trace.Wrap(err)
	}
	return req.Token, nil
}
885893
func ReadTokenManagerFromContext(ctx context.Context) (TokenManager, error) {
	tm := ctx.Value(contextTokenManagerKey)
	if tm == nil {
		log.Error(ctx, map[string]interface{}{
			"token": tm,
		}, "missing token manager")

		return nil, errors.New("missing token manager")
	}
	return tm.(*tokenManager), nil
}
858010
func (c *Client) CreateSignupToken(user services.UserV1, ttl time.Duration) (string, error) {
	if err := user.Check(); err != nil {
		return "", trace.Wrap(err)
	}
	out, err := c.PostJSON(c.Endpoint("signuptokens"), createSignupTokenReq{
		User: user,
		TTL:  ttl,
	})
	if err != nil {
		return "", trace.Wrap(err)
	}
	var token string
	if err := json.Unmarshal(out.Bytes(), &token); err != nil {
		return "", trace.Wrap(err)
	}
	return token, nil
}
887842
func (f *ProviderFactory) CreateSigningManager(cryptoProvider core.CryptoSuite) (core.SigningManager, error) {
	return signingMgr.New(cryptoProvider)
}
885104
func MustCreateProvisionToken(token string, roles teleport.Roles, expires time.Time) ProvisionToken {
	t, err := NewProvisionToken(token, roles, expires)
	if err != nil {
		panic(err)
	}
	return t
}
1261756
func (mgm *tokenManager) ParseToken(ctx context.Context, tokenString string) (*TokenClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
		kid, ok := token.Header["kid"]
		if !ok {
			log.Error(ctx, map[string]interface{}{}, "There is no 'kid' header in the token")
			return nil, errors.New("there is no 'kid' header in the token")
		}
		key := mgm.PublicKey(fmt.Sprintf("%s", kid))
		if key == nil {
			log.Error(ctx, map[string]interface{}{
				"kid": kid,
			}, "There is no public key with such ID")
			return nil, errors.Errorf("there is no public key with such ID: %s", kid)
		}
		return key, nil
	})
	if err != nil {
		return nil, err
	}
	claims := token.Claims.(*TokenClaims)
	if token.Valid {
		return claims, nil
	}
	return nil, errors.WithStack(errors.New("token is not valid"))
}