Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
vslinko committed Apr 1, 2024
0 parents commit 25884db
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .traefik.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
displayName: Secret Auth
type: middleware

import: github.com/vslinko/secret-auth

summary: 'Authorise requests by secret cookie'

testData:
secretKey: "123"
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/vslinko/secret-auth

go 1.19
48 changes: 48 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 25884db

Please sign in to comment.