-
Notifications
You must be signed in to change notification settings - Fork 0
/
azurectl.go
355 lines (300 loc) · 8.06 KB
/
azurectl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/user"
"path"
"strings"
"github.com/codegangsta/cli"
"github.com/pkg/browser"
)
//
// Token is the received JWT token.
//
type Token struct {
TokenType string `json:"token_type"`
ExpiresIn string `json:"expires_in"`
Scope string `json:"scope"`
ExpiresOn string `json:"expires_on"`
NotBefore string `json:"not_before"`
Resource string `json:"resource"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
IDToken string `json:"id_token"`
}
//
// Credentials contains information to authenticate and do requests.
//
type Credentials struct {
Company string
Token Token
}
//
// Group represents an Active Directory group.
//
type Group struct {
DisplayName string `json:"displayName"`
MailNickname string `json:"mailNickname"`
MailEnabled bool `json:"mailEnabled"`
SecurityEnabled bool `json:"securityEnabled"`
Description string `json:"description"`
}
func main() {
app := cli.NewApp()
app.Name = "azurectl"
app.Version = Version
app.Usage = ""
app.Author = "Erik Veld"
app.HideHelp = true
app.Commands = Commands
app.Run(os.Args)
}
//
// Commands that can be invoked on Azure Control
//
var Commands = []cli.Command{
{
Name: "auth",
Usage: "Authenticate with Azure Active Directory",
Description: "",
Action: authenticate,
ArgsUsage: "<company> <id> <secret>",
},
{
Name: "group",
Usage: "Group commands",
Description: "",
Subcommands: []cli.Command{
{
Name: "list",
Usage: "List groups",
Description: "",
Action: listGroups,
},
{
Name: "get",
Usage: "Get details of a group",
Description: "",
Action: getGroup,
ArgsUsage: "<id>",
},
{
Name: "create",
Usage: "Create a group",
Description: "",
Action: createGroup,
ArgsUsage: "<name>",
Flags: []cli.Flag{
cli.StringFlag{
Name: "description, d",
Usage: "Description of the group",
},
},
},
{
Name: "delete",
Usage: "Delete a group",
Description: "",
Action: deleteGroup,
ArgsUsage: "<id>",
},
},
},
}
//
// Authenticate the user and request an access token.
//
func authenticate(c *cli.Context) {
if len(c.Args()) != 3 {
cli.ShowCommandHelp(c, "auth")
os.Exit(1)
}
company := c.Args()[0]
clientID := c.Args()[1]
clientSecret := c.Args()[2]
showAuthPage(clientID)
http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
getAuthCode(w, r, company, clientID, clientSecret)
})
http.ListenAndServe(":27015", nil)
}
//
// Show the browser and direct the user to the login page.
//
func showAuthPage(clientID string) {
address := fmt.Sprintf("https://login.windows.net/common/oauth2/authorize?redirect_uri=http://localhost:27015/auth&client_id=%s&response_type=code&resource=https://graph.windows.net", clientID)
browser.OpenURL(address)
}
//
// Capture the response from the browser and get the authorization code.
//
func getAuthCode(w http.ResponseWriter, r *http.Request, company string, clientID string, clientSecret string) {
params, err := url.ParseQuery(r.URL.RawQuery)
check(err)
code := params["code"][0]
token := getAccessToken(clientID, clientSecret, code)
io.WriteString(w, "Received authorization code. You can now close this browser window.")
writeAccessToken(company, token)
go os.Exit(0)
}
//
// Request an access token based on the client id, client secret and received authorization code.
//
func getAccessToken(clientID string, clientSecret string, code string) Token {
address := fmt.Sprintf("https://login.windows.net/common/oauth2/token")
client := &http.Client{}
form := url.Values{}
form.Set("client_id", clientID)
form.Set("client_secret", clientSecret)
form.Set("code", code)
form.Set("grant_type", "authorization_code")
form.Set("resource", "https://graph.windows.net")
form.Set("redirect_uri", "http://localhost:27015/auth")
resp, err := client.PostForm(address, form)
check(err)
content, err := ioutil.ReadAll(resp.Body)
check(err)
var token Token
err = json.Unmarshal(content, &token)
check(err)
return token
}
//
// Write the received access token to disk.
//
func writeAccessToken(company string, token Token) {
usr, err := user.Current()
check(err)
var credentials Credentials
credentials.Company = company
credentials.Token = token
content, err := json.Marshal(credentials)
check(err)
err = ioutil.WriteFile(path.Join(usr.HomeDir, ".azurectl"), content, 0644)
check(err)
}
//
// Read the credentials from disk.
//
func readCredentials() Credentials {
var credentials Credentials
usr, err := user.Current()
check(err)
content, err := ioutil.ReadFile(path.Join(usr.HomeDir, ".azurectl"))
check(err)
err = json.Unmarshal(content, &credentials)
check(err)
return credentials
}
//
// List the groups in Active Directory.
//
func listGroups(c *cli.Context) {
credentials := readCredentials()
address := fmt.Sprintf("https://graph.windows.net/%s/groups?api-version=1.6", credentials.Company)
client := &http.Client{}
req, err := http.NewRequest("GET", address, nil)
req.Header.Add("Host", "graph.windows.net")
req.Header.Add("Authorization", credentials.Token.AccessToken)
req.Header.Add("Content-Type", "application/json")
req.Close = true
resp, err := client.Do(req)
check(err)
content, err := ioutil.ReadAll(resp.Body)
check(err)
fmt.Println(string(content))
}
//
// Get details about a group in Active Directory.
//
func getGroup(c *cli.Context) {
if len(c.Args()) < 1 {
cli.ShowSubcommandHelp(c)
os.Exit(1)
}
groupID := c.Args()[0]
credentials := readCredentials()
address := fmt.Sprintf("https://graph.windows.net/%s/groups/%s?api-version=1.6", credentials.Company, groupID)
client := &http.Client{}
req, err := http.NewRequest("GET", address, nil)
req.Header.Add("Host", "graph.windows.net")
req.Header.Add("Authorization", credentials.Token.AccessToken)
req.Header.Add("Content-Type", "application/json")
req.Close = true
resp, err := client.Do(req)
check(err)
content, err := ioutil.ReadAll(resp.Body)
check(err)
fmt.Println(string(content))
}
//
// Create a group in Active Directory.
//
func createGroup(c *cli.Context) {
if len(c.Args()) < 1 {
cli.ShowSubcommandHelp(c)
os.Exit(1)
}
displayName := c.Args()[0]
mailNickname := strings.TrimPrefix(displayName, ".")
credentials := readCredentials()
description := c.String("description")
var group Group
group.DisplayName = displayName
group.MailNickname = mailNickname
group.MailEnabled = false
group.SecurityEnabled = true
group.Description = description
groupJSON, err := json.Marshal(group)
check(err)
address := fmt.Sprintf("https://graph.windows.net/%s/groups?api-version=1.6", credentials.Company)
client := &http.Client{}
req, err := http.NewRequest("POST", address, bytes.NewBuffer(groupJSON))
req.Header.Add("Host", "graph.windows.net")
req.Header.Add("Authorization", credentials.Token.AccessToken)
req.Header.Add("Content-Type", "application/json")
req.Close = true
resp, err := client.Do(req)
check(err)
content, err := ioutil.ReadAll(resp.Body)
check(err)
fmt.Println(string(content))
}
//
// Delete a group from Active Directory.
//
func deleteGroup(c *cli.Context) {
if len(c.Args()) < 1 {
cli.ShowSubcommandHelp(c)
os.Exit(1)
}
groupID := c.Args()[0]
credentials := readCredentials()
address := fmt.Sprintf("https://graph.windows.net/%s/groups/%s?api-version=1.6", credentials.Company, groupID)
client := &http.Client{}
req, err := http.NewRequest("DELETE", address, nil)
req.Header.Add("Host", "graph.windows.net")
req.Header.Add("Authorization", credentials.Token.AccessToken)
req.Header.Add("Content-Type", "application/json")
req.Close = true
resp, err := client.Do(req)
check(err)
content, err := ioutil.ReadAll(resp.Body)
check(err)
fmt.Println(string(content))
}
//
// Handle errors in a common way.
//
func check(err error) {
if err != nil {
fmt.Printf("[ERROR] %s\n", err.Error())
os.Exit(1)
}
}