This repository was archived by the owner on Nov 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapplication.go
179 lines (157 loc) · 4.25 KB
/
application.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
// Copyright (c) 2012 Brian Hetro <[email protected]>
// Use of this source code is governed by the ISC
// license that can be found in the LICENSE file.
package adn
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type Application struct {
Id string
Secret string
RedirectURI string
Scopes Scopes
PasswordSecret string
}
var DefaultApplication = &Application{}
var apiHttpClient = &http.Client{}
type Request struct {
Token string // Authentication token for the user or ""
Body io.Reader // Data for the body
BodyType string // Value for the Content-Type header
}
func (c *Application) request(r *Request, name string, args EpArgs) (body io.ReadCloser, err error) {
var path bytes.Buffer
err = epTemplates.ExecuteTemplate(&path, name, args)
if err != nil {
return
}
ep := ApiEndpoints[name]
url := path.String()
req, err := http.NewRequest(string(ep.Method), url, r.Body)
if err != nil {
return
}
req.Header.Set("X-ADN-Migration-Overrides", "response_envelope=1")
if r.Token != "" {
req.Header.Set("Authorization", "Bearer "+r.Token)
}
if r.BodyType != "" {
req.Header.Set("Content-Type", r.BodyType)
}
resp, err := apiHttpClient.Do(req)
if err != nil {
return
}
body = resp.Body
return
}
// Do handles all API requests.
// The Request contains the authentication token and optional body.
// The name comes from ApiEndpoints, with template arguments provided in args.
// The response is unpacked into v.
//
// In the future, you would not call this function directly, instead using a helper
// function for the specific action.
func (c *Application) Do(r *Request, name string, args EpArgs, v interface{}) error {
body, err := c.request(r, name, args)
if err != nil {
return err
}
defer body.Close()
resp, err := ioutil.ReadAll(body)
if err != nil {
return err
}
epOptions := ApiEndpoints[name].Options
if epOptions == nil || epOptions.ResponseEnvelope {
re := &responseEnvelope{Data: v}
err = json.Unmarshal(resp, re)
if err != nil {
return err
}
if re.Meta.ErrorId != "" {
return APIError(re.Meta)
}
} else {
err = json.Unmarshal(resp, v)
if err != nil {
return err
}
}
return err
}
// Generate the authentication URL for the server-side flow.
func (c *Application) AuthenticationURL(state string) (string, error) {
var url bytes.Buffer
args := struct {
*Application
State string
}{c, state}
err := epTemplates.ExecuteTemplate(&url, "authentication url", args)
if err != nil {
return "", err
}
return url.String(), nil
}
// During server-side flow, the user will be redirected back with a code.
// AccessToken uses this code to request an access token for the user.
// This token is returned as a string.
func (c *Application) AccessToken(code string) (string, error) {
data := url.Values{}
data.Set("client_id", c.Id)
data.Set("client_secret", c.Secret)
data.Set("grant_type", "authorization_code")
data.Set("redirect_uri", c.RedirectURI)
data.Set("code", code)
r := &Request{
Body: strings.NewReader(data.Encode()),
BodyType: "application/x-www-form-urlencoded",
}
resp := &struct {
AccessToken string `json:"access_token"`
Error string
}{}
err := c.Do(r, "get access token", EpArgs{}, resp)
if err != nil {
return "", err
}
if resp.Error != "" {
return "", errors.New(resp.Error)
}
return resp.AccessToken, nil
}
// PasswordToken is used to carry out the password flow. The function submits
// the username and password to get an access token. This token is returned
// as a string.
func (c *Application) PasswordToken(username, password string) (string, error) {
data := url.Values{}
data.Set("client_id", c.Id)
data.Set("password_grant_secret", c.PasswordSecret)
data.Set("grant_type", "password")
data.Set("username", username)
data.Set("password", password)
data.Set("scope", c.Scopes.Spaced())
r := &Request{
Body: strings.NewReader(data.Encode()),
BodyType: "application/x-www-form-urlencoded",
}
resp := &struct {
AccessToken string `json:"access_token"`
Error string
}{}
err := c.Do(r, "get access token", EpArgs{}, resp)
if err != nil {
return "", err
}
if resp.Error != "" {
return "", errors.New(resp.Error)
}
return resp.AccessToken, nil
}