token_store.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package login
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. "github.com/Azure/go-autorest/autorest/azure/cli"
  21. "golang.org/x/oauth2"
  22. )
  23. type tokenStore struct {
  24. filePath string
  25. }
  26. // TokenInfo data stored in tokenStore
  27. type TokenInfo struct {
  28. Token oauth2.Token `json:"oauthToken"`
  29. TenantID string `json:"tenantId"`
  30. }
  31. func newTokenStore(path string) (tokenStore, error) {
  32. parentFolder := filepath.Dir(path)
  33. dir, err := os.Stat(parentFolder)
  34. if os.IsNotExist(err) {
  35. err = os.MkdirAll(parentFolder, 0700)
  36. if err != nil {
  37. return tokenStore{}, err
  38. }
  39. dir, err = os.Stat(parentFolder)
  40. }
  41. if err != nil {
  42. return tokenStore{}, err
  43. }
  44. if !dir.Mode().IsDir() {
  45. return tokenStore{}, errors.New("cannot use path " + path + " ; " + parentFolder + " already exists and is not a directory")
  46. }
  47. return tokenStore{
  48. filePath: path,
  49. }, nil
  50. }
  51. // GetTokenStorePath the path for token store
  52. func GetTokenStorePath() string {
  53. cliPath, _ := cli.AccessTokensPath()
  54. return filepath.Join(filepath.Dir(cliPath), tokenStoreFilename)
  55. }
  56. func (store tokenStore) writeLoginInfo(info TokenInfo) error {
  57. bytes, err := json.MarshalIndent(info, "", " ")
  58. if err != nil {
  59. return err
  60. }
  61. return ioutil.WriteFile(store.filePath, bytes, 0644)
  62. }
  63. func (store tokenStore) readToken() (TokenInfo, error) {
  64. bytes, err := ioutil.ReadFile(store.filePath)
  65. if err != nil {
  66. return TokenInfo{}, err
  67. }
  68. loginInfo := TokenInfo{}
  69. if err := json.Unmarshal(bytes, &loginInfo); err != nil {
  70. return TokenInfo{}, err
  71. }
  72. return loginInfo, nil
  73. }
  74. func (store tokenStore) removeData() error {
  75. return os.Remove(store.filePath)
  76. }