// GetTokenFromCLI gets a token using Azure CLI 2.0 for local development scenarios.
438501
func GetTokenFromCLI(resource string) (*Token, error) {
	// This is the path that a developer can set to tell this class what the install path for Azure CLI is.
	const azureCLIPath = "AzureCLIPath"

	// The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI.
	azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles"))

	// Default path for non-Windows.
	const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin"

	// Validate resource, since it gets sent as a command line argument to Azure CLI
	const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed."
	match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource)
	if err != nil {
		return nil, err
	}
	if !match {
		return nil, fmt.Errorf(invalidResourceErrorTemplate, resource)
	}

	// Execute Azure CLI to get token
	var cliCmd *exec.Cmd
	if runtime.GOOS == "windows" {
		cliCmd = exec.Command(fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir")))
		cliCmd.Env = os.Environ()
		cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows))
		cliCmd.Args = append(cliCmd.Args, "/c", "az")
	} else {
		cliCmd = exec.Command("az")
		cliCmd.Env = os.Environ()
		cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath))
	}
	cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource)

	var stderr bytes.Buffer
	cliCmd.Stderr = &stderr

	output, err := cliCmd.Output()
	if err != nil {
		return nil, fmt.Errorf("Invoking Azure CLI failed with the following error: %s", stderr.String())
	}

	tokenResponse := Token{}
	err = json.Unmarshal(output, &tokenResponse)
	if err != nil {
		return nil, err
	}

	return &tokenResponse, err
}
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
}
863892
func GetTokenUser(token syscall.Token) (User, error) {
	tokenUser, err := token.GetTokenUser()
	if err != nil {
		return User{}, errors.Wrap(err, "GetTokenUser failed")
	}

	var user User
	user.SID, err = tokenUser.User.Sid.String()
	if err != nil {
		return user, errors.Wrap(err, "ConvertSidToStringSid failed")
	}

	user.Account, user.Domain, user.Type, err = tokenUser.User.Sid.LookupAccount("")
	if err != nil {
		return user, errors.Wrap(err, "LookupAccountSid failed")
	}

	return user, nil
}
33178
func GetToken(email, password, androidID string) (token string, err error) {
	sig, err := signature(email, password)
	if err != nil {
		return "", err
	}
	data := url.Values{
		"Email":           []string{email},
		"add_account":     []string{"1"},
		"EncryptedPasswd": []string{string(sig)},
		"androidId":       []string{androidID},
	}
	resp, err := http.Post(authURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
	if err != nil {
		return "", err
	}
	b, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return "", err
	}
	if resp.StatusCode != 200 {
		return "", fmt.Errorf("gpsoauth: %s: %s", resp.Status, b)
	}
	for _, line := range strings.Split(string(b), "\n") {
		sp := strings.SplitN(line, "=", 2)
		if len(sp) != 2 {
			continue
		}
		if sp[0] == "Token" {
			return sp[1], nil
		}
	}
	return "", fmt.Errorf("gpsoauth: no Token found")
}
720508
func FromCli(c *cli.Context) (plugin.Middleware, error) {
	return New(c.String("addr"), c.StringSlice("reqHeader"), c.StringSlice("respHeader"))
}
825551
func (ctx *Context) GetComponentAccessToken() (string, error) {
	accessTokenCacheKey := fmt.Sprintf("component_access_token_%s", ctx.AppID)
	val := ctx.Cache.Get(accessTokenCacheKey)
	if val == nil {
		return "", fmt.Errorf("cann't get component access token")
	}
	return val.(string), nil
}
747029
func (c *Client) GetToken(tag names.Tag) (string, error) {
	args := params.GetTokenArgs{Args: []params.GetTokenArg{
		{Tag: tag.String()}},
	}
	var results params.StringResults
	err := c.facade.FacadeCall("GetTokens", args, &results)
	if err != nil {
		return "", errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return "", errors.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		if params.IsCodeNotFound(result.Error) {
			return "", errors.NotFoundf("token for %v", tag)
		}
		return "", errors.Trace(result.Error)
	}
	return result.Result, nil
}
384342
func (a *Authorization) GetTokenLastEight() string {
	if a == nil || a.TokenLastEight == nil {
		return ""
	}
	return *a.TokenLastEight
}
938258
func (r *Registry) GetClientFunc(stream string) (func(*Peer, string, bool) (Client, error), error) {
	r.clientMu.RLock()
	defer r.clientMu.RUnlock()

	f := r.clientFuncs[stream]
	if f == nil {
		return nil, fmt.Errorf("stream %v not registered", stream)
	}
	return f, nil
}
30327
func (a AzureCLI) GetAccessToken(subscription, resource string) (*AccessToken, error) {
	cmd := []string{"account", "get-access-token"}
	if subscription != "" {
		cmd = append(cmd, "--subscription", subscription)
	}
	if resource != "" {
		cmd = append(cmd, "--resource", resource)
	}
	var tok AccessToken
	if err := a.run(&tok, cmd...); err != nil {
		return nil, errors.Trace(err)
	}
	return &tok, nil
}
464576
func (r Account_ProofOfConcept) GetReviewerEmailFromAccessToken(accessToken *string) (resp string, err error) {
	params := []interface{}{
		accessToken,
	}
	err = r.Session.DoRequest("SoftLayer_Account_ProofOfConcept", "getReviewerEmailFromAccessToken", params, &r.Options, &resp)
	return
}
489611
func (s *IdentityService) GetSignupToken(token string) (*services.SignupToken, error) {
	if token == "" {
		return nil, trace.BadParameter("missing token")
	}
	item, err := s.Get(context.TODO(), backend.Key(userTokensPrefix, token))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var signupToken services.SignupToken
	err = json.Unmarshal(item.Value, &signupToken)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &signupToken, nil
}
613345
func (api *AuthAPI) GetTokensByRefreshToken(refreshtoken string) (tokenOptions *TokenOptions, err error) {
	oidcClient, err := api.buildOIDCClient()
	if err != nil {
		return
	}

	tokenResponse, err := oidcClient.GetTokenByRefreshTokenGrant(refreshtoken)
	if err != nil {
		return
	}

	return api.toTokenOptions(tokenResponse), nil
}
1064436
func (c *Ctx) GetTokenInfo(slotID uint) (TokenInfo, error) {
	var cti C.CK_TOKEN_INFO
	e := C.GetTokenInfo(c.ctx, C.CK_ULONG(slotID), &cti)
	s := TokenInfo{
		Label:              strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.label[0]), 32)), " "),
		ManufacturerID:     strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.manufacturerID[0]), 32)), " "),
		Model:              strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.model[0]), 16)), " "),
		SerialNumber:       strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.serialNumber[0]), 16)), " "),
		Flags:              uint(cti.flags),
		MaxSessionCount:    uint(cti.ulMaxSessionCount),
		SessionCount:       uint(cti.ulSessionCount),
		MaxRwSessionCount:  uint(cti.ulMaxRwSessionCount),
		RwSessionCount:     uint(cti.ulRwSessionCount),
		MaxPinLen:          uint(cti.ulMaxPinLen),
		MinPinLen:          uint(cti.ulMinPinLen),
		TotalPublicMemory:  uint(cti.ulTotalPublicMemory),
		FreePublicMemory:   uint(cti.ulFreePublicMemory),
		TotalPrivateMemory: uint(cti.ulTotalPrivateMemory),
		FreePrivateMemory:  uint(cti.ulFreePrivateMemory),
		HardwareVersion:    toVersion(cti.hardwareVersion),
		FirmwareVersion:    toVersion(cti.firmwareVersion),
		UTCTime:            strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.utcTime[0]), 16)), " "),
	}
	return s, toError(e)
}
414026
func (scanner *Scanner) GetTokens() (tokens []string, err error) {
	tokens, _, err = scanner.getTokens(0)
	return
}
41102
func (s *tokenServiceImpl) RetrieveExternalToken(ctx context.Context, forResource string, req *goa.RequestData, forcePull *bool) (*app.ExternalToken, *string, error) {
	if forResource == "" {
		return nil, nil, errors.NewBadParameterError("for", "").Expected("git or OpenShift resource URL")
	}

	var currentIdentityID uuid.UUID
	serviceAccount := authtoken.IsSpecificServiceAccount(ctx, authtoken.OsoProxy, authtoken.Tenant, authtoken.JenkinsIdler, authtoken.JenkinsProxy)
	if serviceAccount {
		// Extract SA ID
		id, err := manager.ContextIdentity(ctx)
		if err != nil {
			return nil, nil, err
		}
		currentIdentityID = *id
	} else {
		// Extract user ID
		currentIdentity, err := s.Services().UserService().LoadContextIdentityIfNotBanned(ctx)
		if err != nil {
			return nil, nil, err
		}
		currentIdentityID = currentIdentity.ID
	}

	var appResponse app.ExternalToken

	linkingProvider, err := s.Factories().LinkingProviderFactory().NewLinkingProvider(ctx, currentIdentityID,
		rest.AbsoluteURL(req, "", nil), forResource)
	if err != nil {
		return nil, nil, err
	}

	osProvider, ok := linkingProvider.(provider.OpenShiftIdentityProvider)
	if ok && serviceAccount {
		// This is a request from OSO proxy, tenant, Jenkins Idler, or Jenkins proxy service to obtain a cluster wide token
		return s.retrieveClusterToken(ctx, forResource, forcePull, osProvider)
	}

	var externalToken *tokenrepo.ExternalToken
	err = s.ExecuteInTransaction(func() error {
		err := s.Repositories().Identities().CheckExists(ctx, currentIdentityID.String())
		if err != nil {
			return errors.NewUnauthorizedError(err.Error())
		}
		tokens, err := s.Repositories().ExternalTokens().LoadByProviderIDAndIdentityID(ctx, linkingProvider.ID(), currentIdentityID)
		if err != nil {
			return err
		}
		if len(tokens) > 0 {
			externalToken = &tokens[0]
		}
		return nil

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

	if externalToken != nil {
		if forcePull != nil && *forcePull {
			userProfile, err := linkingProvider.Profile(ctx, oauth2.Token{AccessToken: externalToken.Token})
			if err != nil {
				log.Error(ctx, map[string]interface{}{
					"err":           err,
					"for":           forResource,
					"provider_name": linkingProvider.TypeName(),
				}, "Unable to fetch user profile for external token. Account relinking may be required.")
				linkURL := rest.AbsoluteURL(req, fmt.Sprintf("%s?for=%s", client.LinkTokenPath(), forResource), nil)
				errorResponse := fmt.Sprintf("LINK url=%s, description=\"%s token is not valid or expired. Relink %s account\"",
					linkURL, linkingProvider.TypeName(), linkingProvider.TypeName())
				return nil, &errorResponse, errors.NewUnauthorizedError(err.Error())
			}

			externalToken.Username = userProfile.Username
			err = s.ExecuteInTransaction(func() error {
				return s.Repositories().ExternalTokens().Save(ctx, externalToken)
			})
			if err != nil {
				return nil, nil, err
			}
		}

		appResponse = app.ExternalToken{
			Scope:          externalToken.Scope,
			AccessToken:    externalToken.Token,
			TokenType:      "Bearer", // We aren't saving the token_type in the database
			Username:       externalToken.Username,
			ProviderAPIURL: linkingProvider.URL(),
		}

		return &appResponse, nil, nil
	}
	providerName := linkingProvider.TypeName()
	linkURL := rest.AbsoluteURL(req, fmt.Sprintf("%s?for=%s", client.LinkTokenPath(), forResource), nil)
	errorResponse := fmt.Sprintf("LINK url=%s, description=\"%s token is missing. Link %s account\"", linkURL, providerName, providerName)
	return nil, &errorResponse, errors.NewUnauthorizedError("token is missing")
}
114564
func GetForToken(document interface{}, decodedToken string) (interface{}, reflect.Kind, error) {
	return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider)
}