1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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)
}
}
|