1 package cli
2 3 // Copyright 2017 Microsoft Corporation
4 //
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
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
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.
16 17 import (
18 "bytes"
19 "encoding/json"
20 "fmt"
21 "io/ioutil"
22 "os"
23 "path/filepath"
24 25 "github.com/dimchansky/utfbom"
26 "github.com/mitchellh/go-homedir"
27 )
28 29 // Profile represents a Profile from the Azure CLI
30 type Profile struct {
31 InstallationID string `json:"installationId"`
32 Subscriptions []Subscription `json:"subscriptions"`
33 }
34 35 // Subscription represents a Subscription from the Azure CLI
36 type Subscription struct {
37 EnvironmentName string `json:"environmentName"`
38 ID string `json:"id"`
39 IsDefault bool `json:"isDefault"`
40 Name string `json:"name"`
41 State string `json:"state"`
42 TenantID string `json:"tenantId"`
43 User *User `json:"user"`
44 }
45 46 // User represents a User from the Azure CLI
47 type User struct {
48 Name string `json:"name"`
49 Type string `json:"type"`
50 }
51 52 const azureProfileJSON = "azureProfile.json"
53 54 func configDir() string {
55 return os.Getenv("AZURE_CONFIG_DIR")
56 }
57 58 // ProfilePath returns the path where the Azure Profile is stored from the Azure CLI
59 func ProfilePath() (string, error) {
60 if cfgDir := configDir(); cfgDir != "" {
61 return filepath.Join(cfgDir, azureProfileJSON), nil
62 }
63 return homedir.Expand("~/.azure/" + azureProfileJSON)
64 }
65 66 // LoadProfile restores a Profile object from a file located at 'path'.
67 func LoadProfile(path string) (result Profile, err error) {
68 var contents []byte
69 contents, err = ioutil.ReadFile(path)
70 if err != nil {
71 err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
72 return
73 }
74 reader := utfbom.SkipOnly(bytes.NewReader(contents))
75 76 dec := json.NewDecoder(reader)
77 if err = dec.Decode(&result); err != nil {
78 err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err)
79 return
80 }
81 82 return
83 }
84