From 5d4a0ca7c30a870543c5843f0fd463be83edc514 Mon Sep 17 00:00:00 2001 From: Milo Schwartz Date: Sun, 29 Sep 2024 11:45:41 -0400 Subject: [PATCH] rename to badger --- .gitignore | 1 + .traefik.yml | 10 ++++++++ README.md | 2 ++ go.mod | 3 +++ main.go | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 85 insertions(+) create mode 100644 .gitignore create mode 100644 .traefik.yml create mode 100644 go.mod create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..08cb523 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +go.sum diff --git a/.traefik.yml b/.traefik.yml new file mode 100644 index 0000000..fc947a6 --- /dev/null +++ b/.traefik.yml @@ -0,0 +1,10 @@ +displayName: gerbil +type: middleware + +import: github.com/fosrl/gerbil + +summary: Middleware auth bouncer for Fossorial + +testData: + apiAddress: http://pangolin:3001 + validToken: abc123 diff --git a/README.md b/README.md index 3b0a525..d732979 100644 --- a/README.md +++ b/README.md @@ -1 +1,3 @@ # badger + +Custom Traefik plugin middleware for auth diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..be57ca4 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/fosrl/badger + +go 1.21.5 diff --git a/main.go b/main.go new file mode 100644 index 0000000..0c5c106 --- /dev/null +++ b/main.go @@ -0,0 +1,69 @@ +package badger + +import ( + "context" + "net/http" + "time" +) + +type Config struct { + APIAddress string `json:"apiAddress"` + ValidToken string `json:"validToken"` +} + +func CreateConfig() *Config { + return &Config{} +} + +type Badger struct { + next http.Handler + name string + apiAdress string + validToken string +} + +func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { + return &Badger{ + next: next, + name: name, + apiAdress: config.APIAddress, + validToken: config.ValidToken, + }, nil +} + +// THIS IS AN EAXMPLE FOR TESTING + +var usedTokens = make(map[string]bool) + +const cookieName = "access_token" +const cookieDuration = 1 * time.Minute + +func (p *Badger) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + if _, err := req.Cookie(cookieName); err == nil { + p.next.ServeHTTP(rw, req) + return + } + + queryToken := req.URL.Query().Get("token") + if queryToken == "" { + http.Error(rw, "Missing token", http.StatusUnauthorized) + return + } + + if queryToken != p.validToken || usedTokens[queryToken] { + http.Error(rw, "Invalid or already used token", http.StatusUnauthorized) + return + } + + usedTokens[queryToken] = true + + expiration := time.Now().Add(cookieDuration) + http.SetCookie(rw, &http.Cookie{ + Name: cookieName, + Value: "temporary-access", + Expires: expiration, + Path: "/", + }) + + p.next.ServeHTTP(rw, req) +}