-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathipblock.go
More file actions
89 lines (76 loc) · 2.12 KB
/
ipblock.go
File metadata and controls
89 lines (76 loc) · 2.12 KB
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
package main
import (
"context"
"fmt"
"net"
"net/http"
"slices"
"strings"
"fiatjaf.com/nostr/khatru"
"fiatjaf.com/nostr/nip86"
"github.com/fiatjaf/pyramid/global"
"github.com/fiatjaf/pyramid/pyramid"
)
func ipBlockMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(global.Settings.BlockedIPs) > 0 {
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
if slices.Contains(global.Settings.BlockedIPs, strings.Split(ip, ",")[0]) {
http.Error(w, "IP blocked", 403)
return
}
}
if ip := r.Header.Get("CF-Connecting-IP"); ip != "" {
if slices.Contains(global.Settings.BlockedIPs, ip) {
http.Error(w, "IP blocked", 403)
return
}
}
if ip := r.RemoteAddr; ip != "" {
if slices.Contains(global.Settings.BlockedIPs, ip) {
http.Error(w, "IP blocked", 403)
return
}
}
}
next.ServeHTTP(w, r)
})
}
func listBlockedIPsHandler(ctx context.Context) ([]nip86.IPReason, error) {
author, ok := khatru.GetAuthed(ctx)
if !ok {
return nil, fmt.Errorf("not authenticated")
}
if !pyramid.IsRoot(author) {
return nil, fmt.Errorf("unauthorized")
}
var res []nip86.IPReason
for _, ip := range global.Settings.BlockedIPs {
res = append(res, nip86.IPReason{IP: ip, Reason: ""})
}
return res, nil
}
func blockIPHandler(ctx context.Context, ip net.IP, reason string) error {
author, ok := khatru.GetAuthed(ctx)
if !ok {
return fmt.Errorf("not authenticated")
}
if !pyramid.IsRoot(author) {
return fmt.Errorf("unauthorized")
}
if !slices.Contains(global.Settings.BlockedIPs, ip.String()) {
global.Settings.BlockedIPs = append(global.Settings.BlockedIPs, ip.String())
}
return global.SaveUserSettings()
}
func unblockIPHandler(ctx context.Context, ip net.IP, reason string) error {
author, ok := khatru.GetAuthed(ctx)
if !ok {
return fmt.Errorf("not authenticated")
}
if !pyramid.IsRoot(author) {
return fmt.Errorf("unauthorized")
}
global.Settings.BlockedIPs = slices.DeleteFunc(global.Settings.BlockedIPs, func(s string) bool { return s == ip.String() })
return global.SaveUserSettings()
}