-
Notifications
You must be signed in to change notification settings - Fork 2
/
permissions.go
90 lines (80 loc) · 2.66 KB
/
permissions.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"log"
"net/http"
"github.com/mdbot/wiki/config"
)
type PermissionChecker struct {
requireAuthForWrites bool
requireAuthForReads bool
}
func (p *PermissionChecker) CanRead(user *config.User) bool {
if p.requireAuthForReads {
return user != nil && user.Has(config.PermissionRead)
} else {
return true
}
}
func (p *PermissionChecker) CanWrite(user *config.User) bool {
if p.requireAuthForWrites {
return user != nil && user.Has(config.PermissionWrite)
} else {
return true
}
}
func (p *PermissionChecker) CanAdmin(user *config.User) bool {
return user != nil && user.Has(config.PermissionAdmin)
}
func (p *PermissionChecker) RequireRead(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUserForRequest(r)
if p.CanRead(user) {
next.ServeHTTP(w, r)
} else if user == nil {
log.Printf("Anonymous user tried to access read-protected resource %s", r.URL)
w.WriteHeader(http.StatusUnauthorized)
} else {
log.Printf("User %s (permissions: %s) tried to access read-protected resource %s", user.Name, user.Permissions.String(), r.URL)
w.WriteHeader(http.StatusForbidden)
}
})
}
func (p *PermissionChecker) RequireWrite(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUserForRequest(r)
if p.CanWrite(user) {
next.ServeHTTP(w, r)
} else if user == nil {
log.Printf("Anonymous user tried to access write-protected resource %s", r.URL)
w.WriteHeader(http.StatusUnauthorized)
} else {
log.Printf("User %s (permissions: %s) tried to access write-protected resource %s", user.Name, user.Permissions.String(), r.URL)
w.WriteHeader(http.StatusForbidden)
}
})
}
func (p *PermissionChecker) RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUserForRequest(r)
if p.CanAdmin(user) {
next.ServeHTTP(w, r)
} else if user == nil {
log.Printf("Anonymous user tried to access admin-protected resource %s", r.URL)
w.WriteHeader(http.StatusUnauthorized)
} else {
log.Printf("User %s (permissions: %s) tried to access admin-protected resource %s", user.Name, user.Permissions.String(), r.URL)
w.WriteHeader(http.StatusForbidden)
}
})
}
func (p *PermissionChecker) RequireAccount(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUserForRequest(r)
if user == nil {
log.Printf("Anonymous user tried to access account-protected resource %s", r.URL)
w.WriteHeader(http.StatusUnauthorized)
} else {
next.ServeHTTP(w, r)
}
})
}