forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent_request.go
195 lines (161 loc) · 4.92 KB
/
event_request.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package core
import (
"maps"
"net/netip"
"strings"
"sync"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/router"
)
// Common request store keys used by the middlewares and api handlers.
const (
RequestEventKeyInfoContext = "infoContext"
)
// RequestEvent defines the PocketBase router handler event.
type RequestEvent struct {
App App
cachedRequestInfo *RequestInfo
Auth *Record
router.Event
mu sync.Mutex
}
// RealIP returns the "real" IP address from the configured trusted proxy headers.
//
// If Settings.TrustedProxy is not configured or the found IP is empty,
// it fallbacks to e.RemoteIP().
//
// NB!
// Be careful when used in a security critical context as it relies on
// the trusted proxy to be properly configured and your app to be accessible only through it.
// If you are not sure, use e.RemoteIP().
func (e *RequestEvent) RealIP() string {
settings := e.App.Settings()
for _, h := range settings.TrustedProxy.Headers {
headerValues := e.Request.Header.Values(h)
if len(headerValues) == 0 {
continue
}
// extract the last header value as it is expected to be the one controlled by the proxy
ipsList := headerValues[len(headerValues)-1]
if ipsList == "" {
continue
}
ips := strings.Split(ipsList, ",")
if settings.TrustedProxy.UseLeftmostIP {
for _, ip := range ips {
parsed, err := netip.ParseAddr(strings.TrimSpace(ip))
if err == nil {
return parsed.StringExpanded()
}
}
} else {
for i := len(ips) - 1; i >= 0; i-- {
parsed, err := netip.ParseAddr(strings.TrimSpace(ips[i]))
if err == nil {
return parsed.StringExpanded()
}
}
}
}
return e.RemoteIP()
}
// HasSuperuserAuth checks whether the current RequestEvent has superuser authentication loaded.
func (e *RequestEvent) HasSuperuserAuth() bool {
return e.Auth != nil && e.Auth.IsSuperuser()
}
// RequestInfo parses the current request into RequestInfo instance.
//
// Note that the returned result is cached to avoid copying the request data multiple times
// but the auth state and other common store items are always refreshed in case they were changed my another handler.
func (e *RequestEvent) RequestInfo() (*RequestInfo, error) {
e.mu.Lock()
defer e.mu.Unlock()
if e.cachedRequestInfo != nil {
e.cachedRequestInfo.Auth = e.Auth
infoCtx, _ := e.Get(RequestEventKeyInfoContext).(string)
if infoCtx != "" {
e.cachedRequestInfo.Context = infoCtx
} else {
e.cachedRequestInfo.Context = RequestInfoContextDefault
}
} else {
// (re)init e.cachedRequestInfo based on the current request event
if err := e.initRequestInfo(); err != nil {
return nil, err
}
}
return e.cachedRequestInfo, nil
}
func (e *RequestEvent) initRequestInfo() error {
infoCtx, _ := e.Get(RequestEventKeyInfoContext).(string)
if infoCtx == "" {
infoCtx = RequestInfoContextDefault
}
info := &RequestInfo{
Context: infoCtx,
Method: e.Request.Method,
Query: map[string]string{},
Headers: map[string]string{},
Body: map[string]any{},
}
if err := e.BindBody(&info.Body); err != nil {
return err
}
// extract the first value of all query params
query := e.Request.URL.Query()
for k, v := range query {
if len(v) > 0 {
info.Query[k] = v[0]
}
}
// extract the first value of all headers and normalizes the keys
// ("X-Token" is converted to "x_token")
for k, v := range e.Request.Header {
if len(v) > 0 {
info.Headers[inflector.Snakecase(k)] = v[0]
}
}
info.Auth = e.Auth
e.cachedRequestInfo = info
return nil
}
// -------------------------------------------------------------------
const (
RequestInfoContextDefault = "default"
RequestInfoContextExpand = "expand"
RequestInfoContextRealtime = "realtime"
RequestInfoContextProtectedFile = "protectedFile"
RequestInfoContextOAuth2 = "oauth2"
RequestInfoContextBatch = "batch"
)
// RequestInfo defines a HTTP request data struct, usually used
// as part of the `@request.*` filter resolver.
//
// The Query and Headers fields contains only the first value for each found entry.
type RequestInfo struct {
Query map[string]string `json:"query"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
Auth *Record `json:"auth"`
Method string `json:"method"`
Context string `json:"context"`
}
// HasSuperuserAuth checks whether the current RequestInfo instance
// has superuser authentication loaded.
func (info *RequestInfo) HasSuperuserAuth() bool {
return info.Auth != nil && info.Auth.IsSuperuser()
}
// Clone creates a new shallow copy of the current RequestInfo and its Auth record (if any).
func (info *RequestInfo) Clone() *RequestInfo {
clone := &RequestInfo{
Method: info.Method,
Context: info.Context,
Query: maps.Clone(info.Query),
Body: maps.Clone(info.Body),
Headers: maps.Clone(info.Headers),
}
if info.Auth != nil {
clone.Auth = info.Auth.Fresh()
}
return clone
}