-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
228 lines (201 loc) · 5.79 KB
/
base.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
package handlers
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"html/template"
"net/http"
"net/url"
"strings"
"time"
"github.com/gorilla/csrf"
"github.com/gorilla/sessions"
"github.com/leonelquinteros/gotext"
"github.com/nics/ich"
"github.com/oklog/ulid/v2"
"github.com/ugent-library/biblio-backoffice/backends"
"github.com/ugent-library/biblio-backoffice/models"
"github.com/ugent-library/biblio-backoffice/render"
"github.com/ugent-library/biblio-backoffice/render/flash"
"github.com/unrolled/secure"
"go.uber.org/zap"
)
// TODO handlers should only have access to a url builder,
// the session and maybe the localizer
type BaseHandler struct {
Router *ich.Mux
Logger *zap.SugaredLogger
SessionName string
SessionStore sessions.Store
UserService backends.UserService
Timezone *time.Location
Loc *gotext.Locale
BaseURL *url.URL
FrontendBaseUrl string
ErrorHandlers map[error]func(http.ResponseWriter, *http.Request, BaseContext)
}
// also add fields to Yield method
type BaseContext struct {
CurrentURL *url.URL
Flash []flash.Flash
Timezone *time.Location
Loc *gotext.Locale
User *models.Person
UserRole string
OriginalUser *models.Person
CSRFToken string
CSRFTag template.HTML
CSPNonce string
FrontendBaseUrl string
}
func (c BaseContext) Yield(pairs ...any) map[string]any {
yield := map[string]any{
"CurrentURL": c.CurrentURL,
"Flash": c.Flash,
"Timezone": c.Timezone,
"Loc": c.Loc,
"User": c.User,
"UserRole": c.UserRole,
"OriginalUser": c.OriginalUser,
"CSRFToken": c.CSRFToken,
"CSRFTag": c.CSRFTag,
"FrontendBaseUrl": c.FrontendBaseUrl,
}
n := len(pairs)
for i := 0; i < n; i += 2 {
key := pairs[i].(string)
val := pairs[i+1]
yield[key] = val
}
return yield
}
func (h BaseHandler) Wrap(fn func(http.ResponseWriter, *http.Request, BaseContext)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, err := h.NewContext(r, w)
if err != nil {
if fn, ok := h.ErrorHandlers[err]; ok {
fn(w, r, ctx)
return
}
h.Logger.Errorw("could not create new context.", err)
render.InternalServerError(w, r, err)
return
}
fn(w, r, ctx)
}
}
func (h BaseHandler) NewContext(r *http.Request, w http.ResponseWriter) (BaseContext, error) {
session, err := h.SessionStore.Get(r, h.SessionName)
if err != nil {
return BaseContext{}, err
}
user, err := h.getUserFromSession(session, r, UserIDKey)
if errors.Is(err, models.ErrUserNotFound) {
return BaseContext{}, err
}
if err != nil {
return BaseContext{}, fmt.Errorf("could not get user from session: %w", err)
}
originalUser, err := h.getUserFromSession(session, r, OriginalUserIDKey)
if errors.Is(err, models.ErrUserNotFound) {
return BaseContext{}, err
}
if err != nil {
return BaseContext{}, fmt.Errorf("could not get original user from session: %w", err)
}
flash, err := h.getFlashFromCookies(r, w)
if err != nil {
return BaseContext{}, fmt.Errorf("could not get flash message from session: %w", err)
}
return BaseContext{
CurrentURL: r.URL,
Flash: flash,
Timezone: h.Timezone,
Loc: h.Loc,
User: user,
UserRole: h.getUserRoleFromSession(session),
OriginalUser: originalUser,
CSRFToken: csrf.Token(r),
CSRFTag: csrf.TemplateField(r),
CSPNonce: secure.CSPNonce(r.Context()),
FrontendBaseUrl: h.FrontendBaseUrl,
}, nil
}
func (h BaseHandler) AddFlash(r *http.Request, w http.ResponseWriter, f flash.Flash) error {
j, err := json.Marshal(f)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: FlashCookiePrefix + ulid.Make().String(),
Value: base64.URLEncoding.EncodeToString(j),
Expires: time.Now().Add(3 * time.Minute),
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
return nil
}
func (h BaseHandler) getFlashFromCookies(r *http.Request, w http.ResponseWriter) ([]flash.Flash, error) {
flashes := []flash.Flash{}
for _, cookie := range r.Cookies() {
if !strings.HasPrefix(cookie.Name, FlashCookiePrefix) {
continue
}
// delete cookie
http.SetCookie(w, &http.Cookie{
Name: cookie.Name,
Value: "",
Expires: time.Now(),
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
j, err := base64.URLEncoding.DecodeString(cookie.Value)
if err != nil {
continue
}
f := flash.Flash{}
if err = json.Unmarshal(j, &f); err == nil {
flashes = append(flashes, f)
}
}
return flashes, nil
}
func (h BaseHandler) getUserFromSession(session *sessions.Session, r *http.Request, sessionKey string) (*models.Person, error) {
userID := session.Values[sessionKey]
if userID == nil {
return nil, nil
}
user, err := h.UserService.GetUser(userID.(string))
if errors.Is(err, models.ErrNotFound) {
return nil, models.ErrUserNotFound
}
if err != nil {
return nil, err
}
return user, nil
}
func (h BaseHandler) getUserRoleFromSession(session *sessions.Session) string {
role := session.Values[UserRoleKey]
if role == nil {
return ""
}
return role.(string)
}
func (h BaseHandler) PathFor(name string, pairs ...string) *url.URL {
return h.Router.PathTo(name, pairs...)
}
func (h BaseHandler) URLFor(name string, pairs ...string) *url.URL {
u := h.Router.PathTo(name, pairs...)
u.Scheme = h.BaseURL.Scheme
u.Host = h.BaseURL.Host
return u
}
func (h BaseHandler) ActionError(w http.ResponseWriter, r *http.Request, ctx BaseContext, msg string, err error, ID string) {
errID := ulid.Make().String()
errMsg := fmt.Sprintf("[error: %s] %s", errID, msg)
h.Logger.Errorw(errMsg, "errors", err, "publication", ID, "user", ctx.User.ID)
h.ErrorModal(w, r, errID, ctx)
}