-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 25884db
Showing
3 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
module github.com/vslinko/secret-auth | ||
|
||
go 1.19 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |