-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
188 lines (155 loc) · 4.46 KB
/
main.go
File metadata and controls
188 lines (155 loc) · 4.46 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/sobhanatar/kauth/config"
"io"
"net/http"
"strconv"
)
const (
PluginName = "kauth"
CfgAdr = "/opt/krakend/plugins/kauth.json"
UserUUID = "User-Uuid"
UserID = "User-Id"
)
// ClientRegisterer is the symbol the plugin loader will try to load. It must implement the RegisterClient interface
var ClientRegisterer = registerer(PluginName)
type registerer string
var (
logger Logger = nil
cfg config.KauthConfig
)
type IdentityResponse struct {
Data struct {
Result []struct {
Id int `json:"id,omitempty"`
Uuid string `json:"uuid,omitempty"`
} `json:"result,omitempty"`
} `json:"data,omitempty"`
}
func (registerer) RegisterLogger(v interface{}) {
l, ok := v.(Logger)
if !ok {
return
}
logger = l
logger.Debug(fmt.Sprintf("[PLUGIN: %s] Logger loaded", ClientRegisterer))
}
func (r registerer) RegisterClients(f func(
name string,
handler func(context.Context, map[string]interface{}) (http.Handler, error),
)) {
f(string(r), r.registerClients)
}
func (r registerer) registerClients(_ context.Context, extra map[string]interface{}) (http.Handler, error) {
name, ok := extra["name"].(string)
if !ok {
return nil, errors.New("wrong config")
}
if name != string(r) {
return nil, fmt.Errorf("unknown register %s", name)
}
// The config variable contains all the keys you have defined in the configuration:
//_, _ = extra["kauth"].(map[string]interface{})
if err := cfg.ParseClient(CfgAdr); err != nil {
return nil, fmt.Errorf(err.Error())
}
logger.Info(fmt.Sprintf("config loaded. identity path is: %s", cfg.Path))
// return the actual handler wrapping or your custom logic, so it can be used as a replacement for the default http handler
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var (
idInfo IdentityResponse
userUUID string
userID int
)
req.Header.Del(UserUUID)
req.Header.Del(UserID)
bearerToken := req.Header.Get("Authorization")
if len(bearerToken) == 0 {
logger.Info("the request doesn't have a bearerToken token and will be executed directly")
err := processMainRequest(w, req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
logger.Info(fmt.Sprintf("the request has bearer token. getting %s from: %s", UserUUID, cfg.Path))
authResp, err := processAuthRequest(bearerToken)
if err != nil {
logger.Error(fmt.Sprintf("calling auth point returned with error: %s", err.Error()))
logger.Info("calling main endpoint without ")
}
defer authResp.Body.Close()
if authResp.StatusCode == http.StatusOK {
body, _ := io.ReadAll(authResp.Body)
_ = json.Unmarshal(body, &idInfo)
userUUID = idInfo.Data.Result[0].Uuid
userID = idInfo.Data.Result[0].Id
logger.Info(fmt.Sprintf("Executing primary request using \"%s\" and \"%d\"", userUUID, userID))
req.Header.Add(UserUUID, userUUID)
req.Header.Add(UserID, strconv.Itoa(userID))
}
err = processMainRequest(w, req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logger.Info("Removing User-Uuid from response header...")
w.Header().Del(UserUUID)
w.Header().Del(UserID)
return
}), nil
}
func processAuthRequest(bearer string) (idResp *http.Response, err error) {
idReq, err := http.NewRequest(http.MethodGet, cfg.Path, nil)
if err != nil {
return
}
idReq.Header.Add("Authorization", bearer)
idReq.Header.Add("Accept", "application/json")
idReq.Header.Add("Content-Type", "application/json")
idResp, err = http.DefaultClient.Do(idReq)
return
}
func processMainRequest(w http.ResponseWriter, req *http.Request) (err error) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
err = setResponse(w, resp)
return
}
func setResponse(w http.ResponseWriter, resp *http.Response) (err error) {
setHeader(w, resp)
w.WriteHeader(resp.StatusCode)
err = setBody(w, resp)
return
}
func setHeader(w http.ResponseWriter, resp *http.Response) {
for k, hs := range resp.Header {
for _, h := range hs {
w.Header().Add(k, h)
}
}
}
func setBody(w http.ResponseWriter, resp *http.Response) (err error) {
if resp.Body != nil {
if _, err = io.Copy(w, resp.Body); err != nil {
return
}
}
return
}
func main() {}
type Logger interface {
Debug(v ...interface{})
Info(v ...interface{})
Warning(v ...interface{})
Error(v ...interface{})
Critical(v ...interface{})
Fatal(v ...interface{})
}