summaryrefslogtreecommitdiff
path: root/ickadmin.go
blob: 945ce9a5e2d9af1cb41265f295db74b664bfc35a (plain)
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
package main

import (
	"flag"
	"fmt"
	"github.com/go-ini/ini"
	"net/http"
	"io/ioutil"
	"os"
	"net/url"
	"strings"
	"strconv"
	"encoding/json"
)

type jwt struct {
	Scope string
	Access_token string
}

func main() {
	var config string

	flag.StringVar(&config, "config", "", "what config file to read?")
	flag.Parse()

	if config == "" {
		fmt.Fprintf(os.Stderr, "MUST give config file\n")
		os.Exit(1)
	}

	cfg, err := ini.Load(config)
	if err != nil {
		fmt.Fprintf(os.Stderr, "reading %s: %v\n", config, err)
		os.Exit(1)
	}

	idp := cfg.Section("").Key("idp").String()
	id := cfg.Section("").Key("id").String()
	secret := cfg.Section("").Key("secret").String()

	data := url.Values{}
	data.Add("grant_type", "client_credentials")
	data.Add("scope", "uapi_projects_get")

	client := &http.Client{}
	req, err := http.NewRequest("POST", idp, strings.NewReader(data.Encode()))
	req.SetBasicAuth(id, 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", 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)
}