-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregistration.go
87 lines (73 loc) · 2.52 KB
/
registration.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
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/Nerzal/gocloak/v13"
)
/* TODO:
- make the IP address dynamic
- change to token authorization after first login; refresh token automatically with previous token
- change to config parameters or secrets to mount in K8s or alternatively, switch to certificates
*/
func main() {
log.Printf("Reading environment variables:\n KEYCLOAK, CLIENTID, REALM, USER, PASSWORD, SECRET, LIGHTHOUSE")
clientID := os.Getenv("CLIENTID")
realm := os.Getenv("REALM")
username := os.Getenv("USER")
secret := os.Getenv("SECRET")
password := os.Getenv("PASSWORD")
keycloak := os.Getenv("KEYCLOAK")
lighthouse := os.Getenv("LIGHTHOUSE")
advertiseAddress := os.Getenv("ADV_ADDRESS")
advertiseName := os.Getenv("ADV_NAME")
ctx := context.Background()
log.Print("clientID: " + clientID + "| realm: " + realm + "| username: " + username + "| keycloak: " + keycloak + "| lighthouse: " + lighthouse + "| advertising address: " + advertiseAddress + "| advertising name: " + advertiseName)
for {
ref_token, err := LoginUser(username, password, keycloak, secret, clientID, realm, ctx)
if err != nil {
log.Print(err)
}
localVarPath := lighthouse + "/controller/"
var localVarPostBody = []byte(`{"name": "` + advertiseName + `", "address": "` + advertiseAddress + `"}`)
req, err := http.NewRequest("POST", localVarPath, bytes.NewBuffer(localVarPostBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("api_key", ref_token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
switch resp.StatusCode {
case 201:
log.Println("Registered successfully")
case 202:
log.Println("Updated successfully")
default:
log.Println("Could not register controller:")
body, _ := io.ReadAll(resp.Body)
fmt.Println("response code: "+resp.Status+" with body: ", string(body))
}
time.Sleep(13 * time.Second)
}
}
// LoginUser - Logs user into the system
func LoginUser(username string, password string, server string, secret string, clientID string, realm string, ctx context.Context) (string, error) {
client := gocloak.NewClient(server)
token, err := client.Login(ctx, clientID, secret, realm, username, password)
if err != nil {
fmt.Println("Could not log in to IAM: ", err)
return "none", err
} else {
// filter the refresh token from the token
refresh_token := token.RefreshToken
return refresh_token, err
}
}