commit 5ec9353fa413b3df30762c9c35ea4077d12bbe9f
parent 6ff06aa8ea1168aa9fd8f3ad553c873a071edc76
Author: Vetle Haflan <vetle@haflan.dev>
Date: Sun, 12 Apr 2020 07:01:57 +0200
Simplify auth middleware for use with HandlerFunctions
Diffstat:
2 files changed, 19 insertions(+), 22 deletions(-)
diff --git a/internal/http/auth.go b/internal/http/auth.go
@@ -34,18 +34,16 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Logged out"))
}
-
-// Thanks: https://github.com/mastertinner/adapters/blob/master/basicauth/basicauth.go
-func AuthHandler(store *sessions.CookieStore) func(http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- session, _ := store.Get(r, "session")
- if !authorized(session) {
- status := http.StatusUnauthorized
- http.Error(w, http.StatusText(status), status)
- return
- }
- next.ServeHTTP(w, r)
- })
- }
+// Middleware for the simple sermoni authentication scheme
+func auth(handler http.HandlerFunc) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Store is the global CookieStore
+ session, _ := store.Get(r, "session")
+ if !authorized(session) {
+ status := http.StatusUnauthorized
+ http.Error(w, http.StatusText(status), status)
+ return
+ }
+ handler.ServeHTTP(w, r)
+ })
}
diff --git a/internal/http/http.go b/internal/http/http.go
@@ -20,20 +20,19 @@ func StartServer(port int) {
conf = config.GetConfig()
store = sessions.NewCookieStore(conf.SessionKey)
- auth := AuthHandler(store)
router := mux.NewRouter()
router.HandleFunc("/", homeHandler)
router.HandleFunc("/login", loginHandler)
//router.HandleFunc("/logout", logoutHandler)
- router.Handle("/logout", auth(http.HandlerFunc(logoutHandler)))
+ router.Handle("/logout", auth(logoutHandler))
- router.Handle("/services", auth(http.HandlerFunc(getServices))).Methods("GET")
- router.Handle("/services", auth(http.HandlerFunc(postService))).Methods("POST")
- router.HandleFunc("/services/{id:[0-9]+}", deleteService).Methods("DELETE")
- //router.HandleFunc("/services/{id:[0-9]+}", putService).Methods("PUT") (TODO)
+ router.Handle("/services", auth(getServices)).Methods("GET")
+ router.Handle("/services", auth(postService)).Methods("POST")
+ router.Handle("/services/{id:[0-9]+}", auth(deleteService)).Methods("DELETE")
+ //router.Handle("/services/{id:[0-9]+}", putService).Methods("PUT") (TODO)
- router.HandleFunc("/events", getEvents).Methods("GET")
- router.HandleFunc("/events/{id:[0-9]+}", deleteEvent).Methods("DELETE")
+ router.Handle("/events", auth(getEvents)).Methods("GET")
+ router.Handle("/events/{id:[0-9]+}", auth(deleteEvent)).Methods("DELETE")
router.HandleFunc("/report", reportEvent).Methods("POST")
http.Handle("/", router)