Browse Source

Add builder function to create AuthenticationMiddleware objects

feature/add-authorization
Fabian Vowie 2 years ago
parent
commit
6ac87dc7dc
No known key found for this signature in database GPG Key ID: C27317C33B27C410
  1. 10
      auth/authorization.go
  2. 25
      auth/authorization_test.go
  3. 4
      main.go

10
auth/authorization.go

@ -6,17 +6,23 @@ import (
)
type AuthenticationMiddleware struct {
Secret string
secret string
}
func (middleware AuthenticationMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authToken := r.Header.Get("Authorization")
if authToken == "" || strings.HasPrefix(authToken, "Bearer ") == false || authToken[7:] != middleware.Secret {
if authToken == "" || strings.HasPrefix(authToken, "Bearer ") == false || authToken[7:] != middleware.secret {
http.Error(w, "Forbidden", http.StatusForbidden)
} else {
next.ServeHTTP(w, r)
}
})
}
func CreateAuthenticationMiddleware(secret string) AuthenticationMiddleware {
return AuthenticationMiddleware{
secret: secret,
}
}

25
auth/authorization_test.go

@ -11,18 +11,15 @@ import (
func TestAuthorizationMiddleware(t *testing.T) {
token := faker.Word()
middleware := CreateAuthenticationMiddleware(token)
t.Run("AuthorizationMiddleware returns 403 response when authorization header is incorrect", func(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
middleware := AuthenticationMiddleware{
Secret: token,
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
middlewareHandler := middleware.Middleware(handler)
middlewareHandler := middleware.Middleware(handler)
t.Run("AuthorizationMiddleware returns 403 response when authorization header is incorrect", func(t *testing.T) {
request, _ := http.NewRequest("GET", "/", nil)
responseRecorder := httptest.NewRecorder()
@ -32,16 +29,6 @@ func TestAuthorizationMiddleware(t *testing.T) {
})
t.Run("AuthorizationMiddleware continues when authorization header is correct", func(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
middleware := AuthenticationMiddleware{
Secret: token,
}
middlewareHandler := middleware.Middleware(handler)
request, _ := http.NewRequest("GET", "/", nil)
request.Header.Set("Authorization", "Bearer "+token)
responseRecorder := httptest.NewRecorder()

4
main.go

@ -57,9 +57,7 @@ func main() {
pipes := pipelines.LoadPipelines()
authMiddleware := auth.AuthenticationMiddleware{
Secret: settings.Token,
}
authMiddleware := auth.CreateAuthenticationMiddleware(settings.Token)
r := mux.NewRouter()
r.Use(authMiddleware.Middleware)

Loading…
Cancel
Save