Skip to content

Commit b02d846

Browse files
committed
- refactored utils
- added `env.go` - added necessary features JSON Templating
1 parent 235600b commit b02d846

File tree

4 files changed

+141
-95
lines changed

4 files changed

+141
-95
lines changed

internals/proxy/proxy.go

Lines changed: 34 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
"strings"
1414
"text/template"
1515

16-
log "github.com/codeshelldev/secured-signal-api/utils"
16+
log "github.com/codeshelldev/secured-signal-api/utils/logger"
1717
)
1818

1919
type AuthType string
@@ -81,6 +81,19 @@ func renderTemplate(name string, tmplStr string, data any) (string, error) {
8181
return buf.String(), nil
8282
}
8383

84+
func templateJSON(data map[string]interface{}, variables map[string]interface{}) map[string]interface{} {
85+
for k, v := range data {
86+
if str, ok := v.(string); ok && len(str) > 4 && str[:3] == "{{." {
87+
key := str[3 : len(str)-2]
88+
if val, found := variables[key]; found {
89+
data[k] = val
90+
}
91+
}
92+
}
93+
94+
return data
95+
}
96+
8497
func AuthMiddleware(next http.Handler, token string) http.Handler {
8598
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
8699
if token == "" {
@@ -169,7 +182,7 @@ func BlockedEndpointMiddleware(next http.Handler, BLOCKED_ENDPOINTS []string) ht
169182
})
170183
}
171184

172-
func TemplatingMiddleware(next http.Handler, VARIABLES map[string]string) http.Handler {
185+
func TemplatingMiddleware(next http.Handler, VARIABLES map[string]interface{}) http.Handler {
173186
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
174187
if req.Body != nil {
175188
bodyBytes, err := io.ReadAll(req.Body)
@@ -182,23 +195,19 @@ func TemplatingMiddleware(next http.Handler, VARIABLES map[string]string) http.H
182195

183196
req.Body.Close()
184197

185-
modifiedBody := string(bodyBytes)
186-
187-
modifiedBody, _ = renderTemplate("json", modifiedBody, VARIABLES)
198+
var modifiedBodyData map[string]interface{}
188199

189-
modifiedBodyBytes := []byte(modifiedBody)
200+
err = json.Unmarshal(bodyBytes, &modifiedBodyData)
190201

191-
if req.URL.RawQuery != "" {
192-
var modifiedBodyData map[string]interface{}
202+
if err != nil {
203+
log.Error("Could not decode Body: ", err.Error())
204+
http.Error(w, "Internal Error", http.StatusInternalServerError)
205+
return
206+
}
193207

194-
err = json.Unmarshal(modifiedBodyBytes, &modifiedBodyData)
195-
196-
if err != nil {
197-
log.Error("Could not decode Body: ", err.Error())
198-
http.Error(w, "Internal Error", http.StatusInternalServerError)
199-
return
200-
}
208+
modifiedBodyData = templateJSON(modifiedBodyData, VARIABLES)
201209

210+
if req.URL.RawQuery != "" {
202211
query, _ := renderTemplate("query", req.URL.RawQuery, VARIABLES)
203212

204213
modifiedQuery := req.URL.Query()
@@ -217,19 +226,19 @@ func TemplatingMiddleware(next http.Handler, VARIABLES map[string]string) http.H
217226

218227
req.URL.RawQuery = modifiedQuery.Encode()
219228

220-
modifiedBodyBytes, err = json.Marshal(modifiedBodyData)
221-
222-
if err != nil {
223-
log.Error("Could not encode Body: ", err.Error())
224-
http.Error(w, "Internal Error", http.StatusInternalServerError)
225-
return
226-
}
227-
228229
log.Debug("Applied Query Templating: ", query)
230+
}
229231

230-
modifiedBody = string(modifiedBodyBytes)
232+
modifiedBodyBytes, err := json.Marshal(modifiedBodyData)
233+
234+
if err != nil {
235+
log.Error("Could not encode Body: ", err.Error())
236+
http.Error(w, "Internal Error", http.StatusInternalServerError)
237+
return
231238
}
232-
239+
240+
modifiedBody := string(modifiedBodyBytes)
241+
233242
log.Debug("Applied Body Templating: ", modifiedBody)
234243

235244
req.Body = io.NopCloser(bytes.NewReader(modifiedBodyBytes))

main.go

Lines changed: 10 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,93 +1,40 @@
11
package main
22

33
import (
4-
"encoding/json"
54
"net/http"
65
"net/http/httputil"
76
"os"
87

98
proxy "github.com/codeshelldev/secured-signal-api/internals/proxy"
10-
log "github.com/codeshelldev/secured-signal-api/utils"
9+
env "github.com/codeshelldev/secured-signal-api/utils/env"
10+
log "github.com/codeshelldev/secured-signal-api/utils/logger"
1111
)
1212

1313
var handler *httputil.ReverseProxy
1414

15-
var VARIABLES map[string]string = map[string]string{
16-
"RECIPIENTS": os.Getenv("DEFAULT_RECIPIENTS"),
17-
"NUMBER": os.Getenv("SENDER"),
18-
}
19-
20-
var BLOCKED_ENDPOINTS []string = []string{
21-
"/v1/about",
22-
"/v1/configuration",
23-
"/v1/devices",
24-
"/v1/register",
25-
"/v1/unregister",
26-
"/v1/qrcodelink",
27-
"/v1/accounts",
28-
"/v1/contacts",
29-
}
15+
var ENV env.ENV_
3016

3117
func main() {
3218
logLevel := os.Getenv("LOG_LEVEL")
3319

3420
log.Init(logLevel)
3521

36-
port := os.Getenv("PORT")
37-
signalUrl := os.Getenv("SIGNAL_API_URL")
38-
39-
blockedEndpointJSON := os.Getenv("BLOCKED_ENDPOINTS")
40-
variablesJSON := os.Getenv("VARIABLES")
41-
42-
token := os.Getenv("API_TOKEN")
43-
44-
log.Info("Loaded Environment Variables")
45-
46-
if token == "" {
47-
log.Warn("No API TOKEN provided this is NOT recommended")
48-
49-
log.Info("Disabling Security Features due to incomplete Congfiguration")
50-
51-
BLOCKED_ENDPOINTS = []string{}
52-
}
53-
54-
if blockedEndpointJSON != "" {
55-
var blockedEndpoints []string
56-
57-
err := json.Unmarshal([]byte(blockedEndpointJSON), &blockedEndpoints)
58-
59-
if err != nil {
60-
log.Error("Could not decode Blocked Endpoints: ", blockedEndpointJSON)
61-
}
62-
63-
BLOCKED_ENDPOINTS = blockedEndpoints
64-
}
65-
66-
if variablesJSON != "" {
67-
var variables map[string]string
68-
69-
err := json.Unmarshal([]byte(variablesJSON), &variables)
70-
71-
if err != nil {
72-
log.Error("Could not decode Variables ", variablesJSON)
73-
}
22+
env.Load()
7423

75-
VARIABLES = variables
76-
}
24+
ENV = env.ENV
7725

78-
handler = proxy.Create(signalUrl)
26+
handler = proxy.Create(ENV.API_URL)
7927

8028
finalHandler := proxy.AuthMiddleware(
8129
proxy.BlockedEndpointMiddleware(
8230
proxy.TemplatingMiddleware(handler,
83-
VARIABLES ),
84-
85-
BLOCKED_ENDPOINTS ),
86-
token )
31+
ENV.VARIABLES ),
32+
ENV.BLOCKED_ENDPOINTS ),
33+
ENV.API_TOKEN )
8734

8835
log.Info("Initialized Proxy Handler")
8936

90-
addr := "0.0.0.0:" + port
37+
addr := "0.0.0.0:" + ENV.PORT
9138

9239
log.Info("Server Listening on ", addr)
9340

utils/env/env.go

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package env
2+
3+
import (
4+
"encoding/json"
5+
"os"
6+
7+
log "github.com/codeshelldev/secured-signal-api/utils/logger"
8+
)
9+
10+
type ENV_ struct {
11+
PORT string
12+
API_URL string
13+
API_TOKEN string
14+
BLOCKED_ENDPOINTS []string
15+
VARIABLES map[string]any
16+
}
17+
18+
var ENV ENV_ = ENV_{
19+
BLOCKED_ENDPOINTS: []string {
20+
"/v1/about",
21+
"/v1/configuration",
22+
"/v1/devices",
23+
"/v1/register",
24+
"/v1/unregister",
25+
"/v1/qrcodelink",
26+
"/v1/accounts",
27+
"/v1/contacts",
28+
},
29+
VARIABLES: map[string]any {
30+
"RECIPIENTS": []string{},
31+
"NUMBER": os.Getenv("SENDER"),
32+
},
33+
}
34+
35+
func Load() {
36+
ENV.PORT = os.Getenv("PORT")
37+
ENV.API_URL = os.Getenv("SIGNAL_API_URL")
38+
39+
ENV.API_TOKEN = os.Getenv("API_TOKEN")
40+
41+
blockedEndpointJSON := os.Getenv("BLOCKED_ENDPOINTS")
42+
recipientsJSON := os.Getenv("DEFAULT_RECIPIENTS")
43+
variablesJSON := os.Getenv("VARIABLES")
44+
45+
log.Info("Loaded Environment Variables")
46+
47+
if ENV.API_TOKEN == "" {
48+
log.Warn("No API TOKEN provided this is NOT recommended")
49+
50+
log.Info("Disabling Security Features due to incomplete Congfiguration")
51+
52+
ENV.BLOCKED_ENDPOINTS = []string{}
53+
}
54+
55+
if blockedEndpointJSON != "" {
56+
var blockedEndpoints []string
57+
58+
err := json.Unmarshal([]byte(blockedEndpointJSON), &blockedEndpoints)
59+
60+
if err != nil {
61+
log.Error("Could not decode Blocked Endpoints: ", blockedEndpointJSON)
62+
}
63+
64+
ENV.BLOCKED_ENDPOINTS = blockedEndpoints
65+
}
66+
67+
if variablesJSON != "" {
68+
var variables map[string]interface{}
69+
70+
err := json.Unmarshal([]byte(variablesJSON), &variables)
71+
72+
if err != nil {
73+
log.Error("Could not decode Variables ", variablesJSON)
74+
}
75+
76+
ENV.VARIABLES = variables
77+
}
78+
79+
if recipientsJSON != "" {
80+
var recipients []string
81+
82+
err := json.Unmarshal([]byte(recipientsJSON), &recipients)
83+
84+
if err != nil {
85+
log.Error("Could not decode Variables ", variablesJSON)
86+
}
87+
88+
ENV.VARIABLES["RECIPIENTS"] = recipients
89+
}
90+
}

utils/logger.go renamed to utils/logger/logger.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"go.uber.org/zap/zapcore"
88
)
99

10-
var log *zap.Logger
10+
var _log *zap.Logger
1111

1212
func Init(level string) {
1313
logLevel := getLogLevel(level)
@@ -36,7 +36,7 @@ func Init(level string) {
3636

3737
var err error
3838

39-
log, err = cfg.Build(zap.AddCaller(), zap.AddCallerSkip(1))
39+
_log, err = cfg.Build(zap.AddCaller(), zap.AddCallerSkip(1))
4040

4141
if err != nil {
4242
panic(err)
@@ -61,22 +61,22 @@ func getLogLevel(level string) zapcore.Level {
6161
}
6262

6363
func Info(msg ...string) {
64-
log.Info(strings.Join(msg, " "))
64+
_log.Info(strings.Join(msg, " "))
6565
}
6666

6767
func Debug(msg ...string) {
68-
log.Debug(strings.Join(msg, " "))
68+
_log.Debug(strings.Join(msg, " "))
6969
}
7070

7171
func Error(msg ...string) {
72-
log.Error(strings.Join(msg, " "))
72+
_log.Error(strings.Join(msg, " "))
7373
}
7474

7575
func Warn(msg ...string) {
76-
log.Warn(strings.Join(msg, " "))
76+
_log.Warn(strings.Join(msg, " "))
7777
}
7878

7979

8080
func Sync() {
81-
_ = log.Sync()
81+
_ = _log.Sync()
8282
}

0 commit comments

Comments
 (0)