github.com/coreos/mantle@v0.13.0/auth/do.go (about) 1 // Copyright 2017 CoreOS, Inc. 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package auth 16 17 import ( 18 "encoding/json" 19 "fmt" 20 "os" 21 "os/user" 22 "path/filepath" 23 ) 24 25 const DOConfigPath = ".config/digitalocean.json" 26 27 // DOProfile represents a parsed DigitalOcean profile. This is a custom 28 // format specific to Mantle. 29 type DOProfile struct { 30 AccessToken string `json:"token"` 31 } 32 33 // ReadDOConfig decodes a DigitalOcean config file, which is a custom format 34 // used by Mantle to hold personal access tokens. 35 // 36 // If path is empty, $HOME/.config/digitalocean.json is read. 37 func ReadDOConfig(path string) (map[string]DOProfile, error) { 38 if path == "" { 39 user, err := user.Current() 40 if err != nil { 41 return nil, err 42 } 43 path = filepath.Join(user.HomeDir, DOConfigPath) 44 } 45 46 f, err := os.Open(path) 47 if err != nil { 48 return nil, err 49 } 50 defer f.Close() 51 52 var profiles map[string]DOProfile 53 if err := json.NewDecoder(f).Decode(&profiles); err != nil { 54 return nil, err 55 } 56 if len(profiles) == 0 { 57 return nil, fmt.Errorf("DigitalOcean config %q contains no profiles", path) 58 } 59 60 return profiles, nil 61 }