summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Wirzenius <lwirzenius@wikimedia.org>2020-01-02 17:18:23 +0200
committerLars Wirzenius <lwirzenius@wikimedia.org>2020-01-02 17:18:23 +0200
commited64333c59670e2851c351d4b0d4979737bbccc6 (patch)
treebc74d23bae0dc529dbe8bd57531296dab0d014f3
parent8365a675ce61fdf8be4cdb8c3828fb9e79a099c3 (diff)
downloadickadmin-ed64333c59670e2851c351d4b0d4979737bbccc6.tar.gz
Refactor: move getting access token to its own function
-rw-r--r--ickadmin.go50
1 files changed, 31 insertions, 19 deletions
diff --git a/ickadmin.go b/ickadmin.go
index ad66985..8519f27 100644
--- a/ickadmin.go
+++ b/ickadmin.go
@@ -40,28 +40,11 @@ func main() {
os.Exit(1)
}
- data := url.Values{}
- data.Add("grant_type", "client_credentials")
- data.Add("scope", "uapi_projects_get")
-
- client := &http.Client{}
- req, err := http.NewRequest("POST", cfg.idp, strings.NewReader(data.Encode()))
- req.SetBasicAuth(cfg.id, cfg.secret)
- req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
-
- resp, err := client.Do(req)
+ token, err := get_access_token(cfg)
if err != nil {
- fmt.Fprintf(os.Stderr, "POST %s: %v\n", cfg.idp, err)
os.Exit(1)
}
-
- bodyText, err := ioutil.ReadAll(resp.Body)
- s := string(bodyText)
-
- res := jwt{}
- json.Unmarshal([]byte(s), &res)
- fmt.Fprintf(os.Stdout, "%s\n", res.Access_token)
+ fmt.Fprintf(os.Stdout, "%s\n", token)
}
func NewConfig(idp string, id string, secret string) *config {
@@ -81,3 +64,32 @@ func get_creds(filename string) (*config, error) {
secret := cfg.Section("").Key("secret").String()
return NewConfig(idp, id, secret), nil
}
+
+func get_access_token(cfg *config) (string, error) {
+ data := url.Values{}
+ data.Add("grant_type", "client_credentials")
+ data.Add("scope", "uapi_projects_get")
+
+ client := &http.Client{}
+ req, err := http.NewRequest("POST", cfg.idp, strings.NewReader(data.Encode()))
+ req.SetBasicAuth(cfg.id, cfg.secret)
+ req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
+
+ resp, err := client.Do(req)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "POST %s: %v\n", cfg.idp, err)
+ return "", err
+ }
+
+ bodyText, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "reading HTTP response: %v\n", err)
+ return "", err
+ }
+
+ s := string(bodyText)
+ res := jwt{}
+ json.Unmarshal([]byte(s), &res)
+ return res.Access_token, nil
+}