3 // Copyright 2017 Microsoft Corporation
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
25 // LoadToken restores a Token object from a file located at 'path'.
26 func LoadToken(path string) (*Token, error) {
27 file, err := os.Open(path)
29 return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
35 dec := json.NewDecoder(file)
36 if err = dec.Decode(&token); err != nil {
37 return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err)
42 // SaveToken persists an oauth token at the given location on disk.
43 // It moves the new file into place so it can safely be used to replace an existing file
44 // that maybe accessed by multiple processes.
45 func SaveToken(path string, mode os.FileMode, token Token) error {
46 dir := filepath.Dir(path)
47 err := os.MkdirAll(dir, os.ModePerm)
49 return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err)
52 newFile, err := ioutil.TempFile(dir, "token")
54 return fmt.Errorf("failed to create the temp file to write the token: %v", err)
56 tempPath := newFile.Name()
58 if err := json.NewEncoder(newFile).Encode(token); err != nil {
59 return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err)
61 if err := newFile.Close(); err != nil {
62 return fmt.Errorf("failed to close temp file %s: %v", tempPath, err)
65 // Atomic replace to avoid multi-writer file corruptions
66 if err := os.Rename(tempPath, path); err != nil {
67 return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err)
69 if err := os.Chmod(path, mode); err != nil {
70 return fmt.Errorf("failed to chmod the token file %s: %v", path, err)