Skip to content

Commit

Permalink
feat: Add authentication middleware.
Browse files Browse the repository at this point in the history
  • Loading branch information
gowizzard committed Apr 12, 2024
1 parent f245589 commit c56afff
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
64 changes: 64 additions & 0 deletions internal/middleware/authentication.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Package middleware is to define the different middleware for the http server.
package middleware

import (
"github.com/gowizzard/mobyspulse/internal/write"
"net/http"
"os"
"reflect"
)

// config is to define the configuration for the basic auth.
type config struct {
Username string
Password string
Ok bool
}

// environment is to define the configuration for the basic auth.
var (
environment config
)

// init is to initialize the basic auth configuration. If the environment variables BASIC_AUTH_USERNAME and
// BASIC_AUTH_PASSWORD are set, then the basic auth is enabled. If the environment variables are not set, then the
// basic auth is disabled.
func init() {

environment.Username, environment.Ok = os.LookupEnv("BASIC_AUTH_USERNAME")
environment.Password, environment.Ok = os.LookupEnv("BASIC_AUTH_PASSWORD")

if environment.Ok {
write.Logger.Info("Basic auth is enabled.")
}

}

// Authentication is to authenticate the request with basic auth. If the environment variables BASIC_AUTH_USERNAME and
// BASIC_AUTH_PASSWORD are set, then the request will be authenticated with basic auth. If the environment variables are
// not set, then the request will be passed to the next handler.
func Authentication(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

if environment.Ok {

username, password, ok := r.BasicAuth()
if ok {

if reflect.DeepEqual(environment.Username, username) && reflect.DeepEqual(environment.Password, password) {
next.ServeHTTP(w, r)
return
}

}

w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return

}

next.ServeHTTP(w, r)

})
}
3 changes: 2 additions & 1 deletion internal/router/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package router

import (
"github.com/gowizzard/mobyspulse/internal/handler"
"github.com/gowizzard/mobyspulse/internal/middleware"
"github.com/gowizzard/mobyspulse/internal/redirect"
"net/http"
)
Expand All @@ -11,5 +12,5 @@ import (
func Handler(mux *http.ServeMux) {
mux.HandleFunc(http.MethodGet+" /", redirect.Metrics)
mux.HandleFunc(http.MethodGet+" /favicon.ico", handler.Favicon)
mux.HandleFunc(http.MethodGet+" /metrics", handler.Metrics)
mux.HandleFunc(http.MethodGet+" /metrics", middleware.Authentication(handler.Metrics))
}

0 comments on commit c56afff

Please sign in to comment.