aboutsummaryrefslogtreecommitdiff
path: root/internal/auth/middleware.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/auth/middleware.go')
-rw-r--r--internal/auth/middleware.go45
1 files changed, 45 insertions, 0 deletions
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)
+ }
+}