This repository was archived by the owner on Aug 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
105 lines (95 loc) · 2.16 KB
/
main.go
File metadata and controls
105 lines (95 loc) · 2.16 KB
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
authv1 "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func deductBalance(id *string) error {
url := fmt.Sprintf("%s/balances/%s:spend", os.Getenv("RECEIPT_VERIFIER_URL"), *id)
log.Println(url)
resp, err := http.Post(url, "text/plain", bytes.NewBuffer([]byte(os.Getenv("AUTH_PRICE"))))
if err != nil {
fmt.Println("Balance spend error:", err)
return err
}
b, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
fmt.Println("Balance spend error:", string(b))
return errors.New(string(b))
}
fmt.Println("Balance:", string(b))
return nil
}
func tokenAuth(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.NotFound(rw, req)
return
}
body := json.NewDecoder(req.Body)
tr := &authv1.TokenReview{}
err := body.Decode(tr)
if err != nil {
handleErr(rw, err)
return
}
err = deductBalance(&tr.Spec.Token)
if err != nil {
handleErr(rw, err)
return
}
user := os.Getenv("RBAC_USER")
// groups := []string{
// "testgroup",
// }
trResp := &authv1.TokenReview{
TypeMeta: metav1.TypeMeta{
APIVersion: "authentication.k8s.io/v1",
Kind: "TokenReview",
},
Status: authv1.TokenReviewStatus{
Authenticated: true,
User: authv1.UserInfo{
UID: user,
Username: user,
// Groups: groups,
},
},
}
writeResp(rw, trResp)
}
func writeResp(rw http.ResponseWriter, tr *authv1.TokenReview) {
rw.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(rw)
err := enc.Encode(tr)
if err != nil {
log.Println("Failed to encode token review response")
}
}
func handleErr(rw http.ResponseWriter, err error) {
writeResp(rw, &authv1.TokenReview{
TypeMeta: metav1.TypeMeta{
APIVersion: "authentication.k8s.io/v1",
Kind: "TokenReview",
},
Status: authv1.TokenReviewStatus{
Error: err.Error(),
},
})
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
addr := fmt.Sprintf(":%s", port)
http.HandleFunc("/token", tokenAuth)
fmt.Println("Starting server on", addr)
http.ListenAndServe(addr, nil)
}