From a397341ad471cc761f7fb930d77e53cf7eb40a2a Mon Sep 17 00:00:00 2001 From: Max Resnick Date: Sun, 8 Nov 2020 11:45:16 -0800 Subject: adds casbin and accounts --- internal/auth/middleware.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 internal/auth/middleware.go (limited to 'internal/auth/middleware.go') diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go new file mode 100644 index 0000000..0be033c --- /dev/null +++ b/internal/auth/middleware.go @@ -0,0 +1,45 @@ +package auth + +import ( + "net/http" + + "github.com/alexedwards/scs/v2" + "github.com/apex/log" +) + +const ( + loginURL = "/login" +) + +func AuthOnly(s Servicer, ses *scs.SessionManager) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + userID := ses.GetString(r.Context(), "profid") + if userID == "" { + userID = "anon" + } + resource := r.URL.Path + // set the action to something that will never match + action := "forbidden" + switch r.Method { + case "POST", "PUT", "PATCH": + action = "write" + case "HEAD", "GET": + action = "read" + } + // TODO determine action + enforced, err := s.Enf().EnforceSafe(userID, resource, action) + if err != nil { + log.Errorf("%s", err) + return + } + if !enforced { + // TODO probably need to do something about suggesting to login + http.Error(w, "not found, are you signed in?", http.StatusNotFound) + return + } + next.ServeHTTP(w, r) + } + return http.HandlerFunc(fn) + } +} -- cgit v1.2.3