summaryrefslogtreecommitdiff
path: root/ickadmin.go
blob: ad66985223263e609b80c214b932338d9c08f74f (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main

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

type jwt struct {
	Scope        string
	Access_token string
}

type config struct {
	idp    string
	id     string
	secret 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 := get_creds(config)
	if err != nil {
		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)
	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)
}

func NewConfig(idp string, id string, secret string) *config {
	new := config{idp: idp, id: id, secret: secret}
	return &new
}

func get_creds(filename string) (*config, error) {
	cfg, err := ini.Load(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "reading config %s: %v\n", filename, err)
		return nil, err
	}

	idp := cfg.Section("").Key("idp").String()
	id := cfg.Section("").Key("id").String()
	secret := cfg.Section("").Key("secret").String()
	return NewConfig(idp, id, secret), nil
}