From 25884db8ab259379ba8ecb94cd472b4e103c03fe Mon Sep 17 00:00:00 2001 From: Viacheslav Slinko Date: Mon, 1 Apr 2024 19:24:36 +0300 Subject: [PATCH] initial commit --- .traefik.yml | 9 +++++++++ go.mod | 3 +++ main.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 .traefik.yml create mode 100644 go.mod create mode 100644 main.go diff --git a/.traefik.yml b/.traefik.yml new file mode 100644 index 0000000..d2d2590 --- /dev/null +++ b/.traefik.yml @@ -0,0 +1,9 @@ +displayName: Secret Auth +type: middleware + +import: github.com/vslinko/secret-auth + +summary: 'Authorise requests by secret cookie' + +testData: + secretKey: "123" diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..453ac22 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/vslinko/secret-auth + +go 1.19 diff --git a/main.go b/main.go new file mode 100644 index 0000000..1f30c41 --- /dev/null +++ b/main.go @@ -0,0 +1,48 @@ +package secret_auth + +import ( + "context" + "fmt" + "net/http" +) + +type Config struct { + CookieName string `json:"cookieName,omitempty"` + SecretKey string `json:"secretKey,omitempty"` +} + +func CreateConfig() *Config { + return &Config{ + CookieName: "secret", + SecretKey: "", + } +} + +type SecretAuthPlugin struct { + next http.Handler + cookieName string + secretKey string +} + +func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { + if len(config.SecretKey) == 0 { + return nil, fmt.Errorf("secret key cannot be empty") + } + + return &SecretAuthPlugin{ + next: next, + cookieName: config.CookieName, + secretKey: config.SecretKey, + }, nil +} + +func (a *SecretAuthPlugin) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + cookie, err := req.Cookie(a.cookieName) + + if err != nil || cookie.Value != a.secretKey { + http.Error(rw, "Forbidden", http.StatusForbidden) + return + } + + a.next.ServeHTTP(rw, req) +}