tokenStore.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2020 Docker, Inc.
  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. "golang.org/x/oauth2"
  21. )
  22. type tokenStore struct {
  23. filePath string
  24. }
  25. // TokenInfo data stored in tokenStore
  26. type TokenInfo struct {
  27. Token oauth2.Token `json:"oauthToken"`
  28. TenantID string `json:"tenantId"`
  29. }
  30. func newTokenStore(path string) (tokenStore, error) {
  31. parentFolder := filepath.Dir(path)
  32. dir, err := os.Stat(parentFolder)
  33. if os.IsNotExist(err) {
  34. err = os.MkdirAll(parentFolder, 0700)
  35. if err != nil {
  36. return tokenStore{}, err
  37. }
  38. dir, err = os.Stat(parentFolder)
  39. }
  40. if err != nil {
  41. return tokenStore{}, err
  42. }
  43. if !dir.Mode().IsDir() {
  44. return tokenStore{}, errors.New("cannot use path " + path + " ; " + parentFolder + " already exists and is not a directory")
  45. }
  46. return tokenStore{
  47. filePath: path,
  48. }, nil
  49. }
  50. func (store tokenStore) writeLoginInfo(info TokenInfo) error {
  51. bytes, err := json.MarshalIndent(info, "", " ")
  52. if err != nil {
  53. return err
  54. }
  55. return ioutil.WriteFile(store.filePath, bytes, 0644)
  56. }
  57. func (store tokenStore) readToken() (TokenInfo, error) {
  58. bytes, err := ioutil.ReadFile(store.filePath)
  59. if err != nil {
  60. return TokenInfo{}, err
  61. }
  62. loginInfo := TokenInfo{}
  63. if err := json.Unmarshal(bytes, &loginInfo); err != nil {
  64. return TokenInfo{}, err
  65. }
  66. return loginInfo, nil
  67. }