// GetJWTToken looks up the index of a JWTToken in a project by the issue at time
504491
func GetJWTToken(proj *v1alpha1.AppProject, roleName string, issuedAt int64) (*v1alpha1.JWTToken, int, error) {
	role, _, err := GetRoleByName(proj, roleName)
	if err != nil {
		return nil, -1, err
	}
	for i, token := range role.JWTTokens {
		if issuedAt == token.IssuedAt {
			return &token, i, nil
		}
	}
	return nil, -1, fmt.Errorf("JWT token for role '%s' issued at '%d' does not exist in project '%s'", role.Name, issuedAt, proj.Name)
}
1038292
func jwtToAccessToken(t *jwt.Token) (*AccessToken, error) {
	var token AccessToken

	if t.Claims["exp"] != nil {
		exp := time.Unix(int64(t.Claims["exp"].(float64)), 0).UTC()
		token.ExpiresAt = &exp
	}

	if u, ok := t.Claims["User"].(map[string]interface{}); ok {
		var user empire.User

		if n, ok := u["Name"].(string); ok {
			user.Name = n
		} else {
			return &token, errors.New("missing name")
		}

		if gt, ok := u["GitHubToken"].(string); ok {
			user.GitHubToken = gt
		} else {
			return &token, errors.New("missing github token")
		}

		token.User = &user
	} else {
		return &token, errors.New("missing user")
	}

	return &token, nil
}
432081
func (oauther *OAuther) ObtainToken() (err error) {
	oauther.codeChannel = make(chan string)
	oauther.errorChannel = make(chan error)

	oauther.runServerIfNecessary()

	transport := oauther.Transport()

	// Get an authorization code from the data provider.
	// ("Please ask the user if I can access this resource.")
	authCodeUrl, _ := url.QueryUnescape(oauther.config.AuthCodeURL(""))
	webbrowser.Open(authCodeUrl)

	select {
	case authCode := <-oauther.codeChannel:
		// Exchange the authorization code for an access token.
		// ("Here's the code you gave the user, now give me a token!")
		oauther.Token, err = transport.Exchange(authCode)
		return
	case err = <-oauther.errorChannel:
		return
	}
}
1097515
func decodeJWT(a ast.Value) (*JSONWebToken, error) {
	// Parse the JSON Web Token
	astEncode, err := builtins.StringOperand(a, 1)
	if err != nil {
		return nil, err
	}

	encoding := string(astEncode)
	if !strings.Contains(encoding, ".") {
		return nil, errors.New("encoded JWT had no period separators")
	}

	parts := strings.Split(encoding, ".")
	if len(parts) != 3 {
		return nil, fmt.Errorf("encoded JWT must have 3 sections, found %d", len(parts))
	}

	return &JSONWebToken{header: parts[0], payload: parts[1], signature: parts[2]}, nil
}
113500
func getClaimJWT(client *http.Client, url, accessToken string) (string, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// TODO: Allow passing request body with configurable information.
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", fmt.Errorf("while calling %v: %v", url, err)
	}
	if accessToken != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", accessToken))
	}
	req = req.WithContext(ctx)
	response, err := client.Do(req)
	if err != nil {
		return "", err
	}
	// Report non-OK status code as an error.
	if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusIMUsed {
		return "", fmt.Errorf("error while getting distributed claim JWT: %v", response.Status)
	}
	defer response.Body.Close()
	responseBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", fmt.Errorf("could not decode distributed claim response")
	}
	return string(responseBytes), nil
}
1236989
func (idp *IDP) getChallengeToken(challengeString string) (*jwt.Token, error) {
	token, err := jwt.Parse(challengeString, func(token *jwt.Token) (interface{}, error) {
		_, ok := token.Method.(*jwt.SigningMethodRSA)
		if !ok {
			return nil, ErrorBadSigningMethod
		}

		return idp.getVerificationKey()
	})

	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, ErrorInvalidToken
	}

	return token, nil
}
875393
func (t *TokenProvider) GetToken(audience string) (*auth.Token, error) {
	signature, expiry := t.signer.SignWithDuration(audience, 2*time.Hour)
	return auth.NewToken(auth.CBSTokenTypeSAS, signature, expiry), nil
}
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
}
54156
func (a *Authorization) GetHashedToken() string {
	if a == nil || a.HashedToken == nil {
		return ""
	}
	return *a.HashedToken
}
944228
func (c *Cache) GetToken(token string) (services.ProvisionToken, error) {
	return c.provisionerCache.GetToken(token)
}
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
}
600409
func (r Brand) GetToken(userId *int) (resp string, err error) {
	params := []interface{}{
		userId,
	}
	err = r.Session.DoRequest("SoftLayer_Brand", "getToken", params, &r.Options, &resp)
	return
}
27916
func GetTokenInfo(token string) (Version, Purpose, error) {
	parts := strings.Split(token, ".")
	if len(parts) < 3 {
		return "", 0, ErrIncorrectTokenFormat
	}

	var version Version
	var purpose Purpose

	switch parts[0] {
	case string(Version1):
		version = Version1
	case string(Version2):
		version = Version2
	default:
		return "", 0, ErrUnsupportedTokenVersion
	}

	switch parts[1] {
	case "local":
		purpose = LOCAL
	case "public":
		purpose = PUBLIC
	default:
		return "", 0, ErrUnsupportedTokenType
	}

	return version, purpose, nil
}
666984
func (s *tokenReviewLister) Get(name string) (*v1.TokenReview, error) {
	obj, exists, err := s.indexer.GetByKey(name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1.Resource("tokenreview"), name)
	}
	return obj.(*v1.TokenReview), nil
}
422498
func GetIssueByIndex(repoID, index int64) (*Issue, error) {
	issue, err := GetRawIssueByIndex(repoID, index)
	if err != nil {
		return nil, err
	}
	return issue, issue.LoadAttributes()
}
404048
func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) {
	tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v, internal.AuthStyle(c.Endpoint.AuthStyle))
	if err != nil {
		if rErr, ok := err.(*internal.RetrieveError); ok {
			return nil, (*RetrieveError)(rErr)
		}
		return nil, err
	}
	return tokenFromInternal(tk), nil
}
1369343
func (api *RemoteRelationsAPI) GetTokens(args params.GetTokenArgs) (params.StringResults, error) {
	results := params.StringResults{
		Results: make([]params.StringResult, len(args.Args)),
	}
	for i, arg := range args.Args {
		entityTag, err := names.ParseTag(arg.Tag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		token, err := api.st.GetToken(entityTag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
		}
		results.Results[i].Result = token
	}
	return results, nil
}