-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
313 lines (250 loc) · 6.82 KB
/
handler.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package auth
import (
"context"
"encoding/json"
"io"
"log/slog"
"net"
"net/http"
"time"
"github.com/hashicorp/golang-lru/v2/expirable"
"github.com/yaitoo/sqle/shardid"
)
type ctxKey string
var (
currentUser ctxKey = "cu"
)
type CurrentUser struct {
UserID shardid.ID
// IP user's ip address
UserIP string
// UserAgent user's device info
UserAgent string
}
type Handler struct {
db *Auth
permissions []Perm
getUserIP func(*http.Request) string
getAccessToken func(*http.Request) string
cachedUserPerms *expirable.LRU[int64, map[string]bool]
cachedUserPermsTTL time.Duration
cachedUserPermsSize int
}
type HandlerOption func(h *Handler)
type LoginForm struct {
Email string `json:"email,omitempty"`
Passwd string `json:"passwd,omitempty"`
}
func NewHandler(db *Auth, options ...HandlerOption) *Handler {
h := &Handler{
db: db,
cachedUserPermsTTL: 1 * time.Minute,
cachedUserPermsSize: 1024,
getUserIP: func(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
},
getAccessToken: func(r *http.Request) string {
return r.Header.Get("X-Access-Token")
},
}
for _, opt := range options {
opt(h)
}
h.cachedUserPerms = expirable.NewLRU[int64, map[string]bool](h.cachedUserPermsSize, nil, h.cachedUserPermsTTL)
return h
}
func WithGetUserIP(fn func(*http.Request) string) HandlerOption {
return func(h *Handler) {
h.getUserIP = fn
}
}
func WithGetAccessToken(fn func(*http.Request) string) HandlerOption {
return func(h *Handler) {
h.getAccessToken = fn
}
}
func WithUserPermsCache(ttl time.Duration, size int) HandlerOption {
return func(h *Handler) {
h.cachedUserPermsTTL = ttl
h.cachedUserPermsSize = size
}
}
// WithAuthn returns a middleware that checks the user is authenticated.
func (h *Handler) WithAuthn(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
s, err := h.getCurrentUser(ctx, r)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
handler(context.WithValue(ctx, currentUser, s), w, r)
}
}
// WithAuthz returns a middleware that checks the user's permissions.
func (h *Handler) WithAuthz(ctx context.Context, tag, code string, handler func(context.Context, http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
h.permissions = append(h.permissions, Perm{Tag: tag, Code: code})
return func(w http.ResponseWriter, r *http.Request) {
s := &CurrentUser{}
s.UserAgent = r.UserAgent()
s.UserIP = h.getUserIP(r)
accessToken := h.getAccessToken(r)
id, err := h.db.IsAuthenticated(ctx, accessToken)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
s.UserID = id
perms := h.getUserPerms(ctx, id.Int64)
ok := perms[code]
if !ok {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
handler(context.WithValue(ctx, currentUser, s), w, r)
}
}
func (h *Handler) Login(ctx context.Context, w http.ResponseWriter, r *http.Request) {
form, err := BindJSON[LoginForm](r)
if err != nil {
WriteClientError(w, err)
return
}
session, err := h.db.Login(ctx, form.Email, form.Passwd, LoginOption{
UserIP: h.getUserIP(r),
UserAgent: r.UserAgent(),
CreateIfNotExists: false,
})
if err != nil {
WriteClientError(w, err)
return
}
perms, err := h.db.GetUserPerms(ctx, session.UserID)
if err == nil {
go h.cacheUserPerms(session.UserID, perms)
} else {
h.db.logger.Error("auth: login", slog.String("tag", "db"), slog.Any("err", err))
}
WriteJSON(w, struct {
Session
Perms []string `json:"perms,omitempty"`
}{
Session: session,
Perms: perms,
})
}
func (h *Handler) Logout(ctx context.Context, w http.ResponseWriter, r *http.Request) {
user, ok := GetCurrentUser(ctx)
if !ok {
WriteClientError(w, ErrBadRequest)
return
}
err := h.db.Logout(ctx, user.UserID)
if err != nil {
WriteServerError(w, err)
return
}
WriteEmpty(w)
}
func (h *Handler) RegisterPerms() {
for _, it := range h.permissions {
h.db.RegisterPerm(context.TODO(), it.Code, it.Tag)
}
}
func (h *Handler) getUserPerms(ctx context.Context, uid int64) map[string]bool {
perms, ok := h.cachedUserPerms.Get(uid)
if ok {
return perms
}
perms = map[string]bool{}
items, err := h.db.GetUserPerms(ctx, uid)
if err != nil {
h.db.logger.Error("auth: getUserPerms ", slog.Int64("uid", uid), slog.Any("err", err))
} else {
for _, it := range items {
perms[it] = true
}
h.cachedUserPerms.Add(uid, perms)
}
return perms
}
func (h *Handler) cacheUserPerms(uid int64, items []string) {
perms := make(map[string]bool)
for _, it := range items {
perms[it] = true
}
h.cachedUserPerms.Add(uid, perms)
}
func (h *Handler) getCurrentUser(ctx context.Context, r *http.Request) (CurrentUser, error) {
s := CurrentUser{}
s.UserAgent = r.UserAgent()
s.UserIP = h.getUserIP(r)
accessToken := h.getAccessToken(r)
id, err := h.db.IsAuthenticated(ctx, accessToken)
if err != nil {
return s, err
}
s.UserID = id
return s, nil
}
func GetCurrentUser(ctx context.Context) (CurrentUser, bool) {
cu, ok := ctx.Value(currentUser).(CurrentUser)
return cu, ok
}
func BindJSON[T any](req *http.Request, options ...Option) (T, error) {
var i T
buf, err := io.ReadAll(req.Body)
if err != nil {
return i, ErrBadRequest
}
defer req.Body.Close()
err = json.Unmarshal(buf, &i)
if err != nil {
return i, ErrBadRequest
}
return i, nil
}
func Write[T any](w http.ResponseWriter, statusCode int, result T, err error) {
w.WriteHeader(statusCode)
w.Header().Set("Content-Type", "application/json")
jr := JsonResult[T]{
Code: statusCode,
Result: result,
}
if err != nil {
jr.ErrorCode = err.Error()
// TODO: added i18n for error
jr.ErrorMessage = err.Error()
}
//nolint: errcheck
json.NewEncoder(w).Encode(jr)
}
func WriteEmpty(w http.ResponseWriter) {
Write[any](w, http.StatusOK, nil, nil)
}
func WriteJSON[T any](w http.ResponseWriter, result T) {
Write(w, http.StatusOK, result, nil)
}
func WriteError(w http.ResponseWriter, statusCode int, err error) {
Write[any](w, statusCode, nil, err)
}
func WriteServerError(w http.ResponseWriter, err error) {
Write[any](w, http.StatusInternalServerError, nil, err)
}
func WriteClientError(w http.ResponseWriter, err error) {
Write[any](w, http.StatusBadRequest, nil, err)
}
type JsonResult[T any] struct {
Code int `json:"code,omitempty"`
Result T `json:"result,omitempty"`
ErrorCode string `json:"errorCode,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
type JsonMessage struct {
Code int `json:"code,omitempty"`
ErrorCode string `json:"errorCode,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}