feat: add API Key Auth middleware
Signed-off-by: HeshamTB <hishaminv@gmail.com>
This commit is contained in:
parent
77c41ce3f3
commit
ca29b792fb
@ -63,6 +63,7 @@ func run(ctx *cli.Context) {
|
|||||||
apiMux.HandleFunc("GET /peers", hvpnnode3.HandleGetPeers(wgLink))
|
apiMux.HandleFunc("GET /peers", hvpnnode3.HandleGetPeers(wgLink))
|
||||||
|
|
||||||
var handler http.Handler = apiMux
|
var handler http.Handler = apiMux
|
||||||
|
handler = hvpnnode3.HttpAuthToken(handler, ctx.String("http-api-key"))
|
||||||
handler = hvpnnode3.HttpLogHandler2(handler)
|
handler = hvpnnode3.HttpLogHandler2(handler)
|
||||||
|
|
||||||
port := fmt.Sprintf("%d", httpPort)
|
port := fmt.Sprintf("%d", httpPort)
|
||||||
@ -185,6 +186,12 @@ func createCliApp() *cli.App {
|
|||||||
}
|
}
|
||||||
app.Flags = append(app.Flags, &httpPort)
|
app.Flags = append(app.Flags, &httpPort)
|
||||||
|
|
||||||
|
apiSecret := cli.StringFlag{
|
||||||
|
Name: "http-api-key",
|
||||||
|
Usage: "Secure endpoints with this key; 'Authorization: Bearer <key>' HTTP Header",
|
||||||
|
}
|
||||||
|
app.Flags = append(app.Flags, &apiSecret)
|
||||||
|
|
||||||
|
|
||||||
/* TLS Flags */
|
/* TLS Flags */
|
||||||
|
|
||||||
|
24
handlers.go
24
handlers.go
@ -193,6 +193,20 @@ func HttpLogHandler2(h http.Handler) http.Handler {
|
|||||||
return http.HandlerFunc(fn)
|
return http.HandlerFunc(fn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func HttpAuthToken(h http.Handler, token string) http.Handler {
|
||||||
|
fn := func(w http.ResponseWriter, r* http.Request) {
|
||||||
|
if token != "" {
|
||||||
|
if r.Header.Get("Authorization") != token {
|
||||||
|
slog.Debug("Invalid api key")
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
}
|
||||||
|
return http.HandlerFunc(fn)
|
||||||
|
}
|
||||||
|
|
||||||
func debugf(format string, reqID uuid.UUID, args ...any) {
|
func debugf(format string, reqID uuid.UUID, args ...any) {
|
||||||
format = format + " " + reqID.String()
|
format = format + " " + reqID.String()
|
||||||
slog.Debug(fmt.Sprintf(format, args...))
|
slog.Debug(fmt.Sprintf(format, args...))
|
||||||
@ -202,3 +216,13 @@ func debug(msg string, reqID uuid.UUID) {
|
|||||||
msg = msg + " " + reqID.String()
|
msg = msg + " " + reqID.String()
|
||||||
debugf("%s", reqID, msg)
|
debugf("%s", reqID, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func infof(format string, reqID uuid.UUID, args ...any) {
|
||||||
|
format = format + " " + reqID.String()
|
||||||
|
slog.Info(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func info(msg string, reqID uuid.UUID) {
|
||||||
|
msg = msg + " " + reqID.String()
|
||||||
|
infof("%s", reqID, msg)
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user