Skip to content

Commit

Permalink
add path authentification
Browse files Browse the repository at this point in the history
  • Loading branch information
MakMuftic committed May 23, 2024
1 parent 09a8f7b commit f977b0e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
8 changes: 5 additions & 3 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ package auth

import (
"net/http"
"strings"
)

func URLTokenAuth(token string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authToken := r.URL.Query().Get("auth_token")
if authToken == "" || authToken != token {
pathParts := strings.Split(r.URL.Path, "/")
if len(pathParts) < 2 || pathParts[len(pathParts)-1] != token {
w.WriteHeader(http.StatusUnauthorized)

return
}
// Remove the token part from the path to forward the request to the next handler
r.URL.Path = strings.Join(pathParts[:len(pathParts)-1], "/")
next.ServeHTTP(w, r)
})
}
Expand Down
9 changes: 5 additions & 4 deletions internal/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import (
"testing"
)

func TestUrlTokenAuth(t *testing.T) {
func TestURLTokenAuth(t *testing.T) {
validToken := "valid_token"
invalidToken := "invalid_token"
middleware := URLTokenAuth(validToken)

tests := []struct {
Expand All @@ -17,17 +18,17 @@ func TestUrlTokenAuth(t *testing.T) {
}{
{
name: "Valid token",
url: "/?auth_token=valid_token",
url: "/some/path/valid_token",
expectedStatus: http.StatusOK,
},
{
name: "Invalid token",
url: "/?auth_token=invalid_token",
url: "/some/path/invalid_token",
expectedStatus: http.StatusUnauthorized,
},
{
name: "Missing token",
url: "/",
url: "/some/path/",
expectedStatus: http.StatusUnauthorized,
},
}
Expand Down

0 comments on commit f977b0e

Please sign in to comment.