crossplane
65 строк · 1.7 Кб
1/*
2Copyright 2023 The Crossplane Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package upbound18
19import (20"encoding/json"21"path/filepath"22
23"github.com/spf13/afero"24
25"github.com/crossplane/crossplane-runtime/pkg/errors"26)
27
28const errInvalidTokenFile = "token file is invalid"29
30// TokenFile is the format in which Upbound tokens are stored on disk.
31type TokenFile struct {32AccessID string `json:"accessId"`33Token string `json:"token"`34}
35
36// tokenConf is the configuration for obtaining a token.
37type tokenConf struct {38fs afero.Fs39}
40
41// TokenOption modifies how a token is obtained.
42type TokenOption func(conf *tokenConf)43
44// TokenFromPath extracts a token from the provided path.
45func TokenFromPath(path string, opts ...TokenOption) (TokenFile, error) {46conf := &tokenConf{47fs: afero.NewOsFs(),48}49for _, o := range opts {50o(conf)51}52tf := TokenFile{}53f, err := conf.fs.Open(filepath.Clean(path))54if err != nil {55return tf, err56}57defer f.Close() //nolint:errcheck // we don't care about the error58if err := json.NewDecoder(f).Decode(&tf); err != nil {59return tf, err60}61if tf.AccessID == "" || tf.Token == "" {62return tf, errors.New(errInvalidTokenFile)63}64return tf, nil65}
66