-
Notifications
You must be signed in to change notification settings - Fork 3
/
page.go
316 lines (260 loc) · 6.54 KB
/
page.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
314
315
316
package server
import (
"bytes"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"strings"
"github.com/gorilla/mux"
"github.com/knoebber/dotfile/db"
"github.com/knoebber/dotfile/dotfile"
"github.com/knoebber/dotfile/usererror"
"github.com/pkg/errors"
)
// Titles of pages that have links on the nav bar.
// Important these stay constant as they are referenced in setLinks()
const (
indexTitle = "Dotfilehub"
aboutTitle = "About"
settingsTitle = "Settings"
signupTitle = "Signup"
loginTitle = "Login"
)
var (
baseTemplate *template.Template
pageTemplates *template.Template
)
// Page renders pages and tracks request state.
// Exported fields/methods may be used within templates.
type Page struct {
Title string
SuccessMessage string
ErrorMessage string
Links []Link
Vars map[string]string
Data map[string]interface{}
Table *db.HTMLTable
Session *db.UserSession
templateName string
htmlFile string
// Page access is restricted to their owners when true.
protected bool
}
// Dark returns whether dark mode is turned on.
func (p *Page) Dark() bool {
return p.Session != nil && p.Session.Theme == db.UserThemeDark
}
// Owned returns whether the logged in user owns the page.
// Pages without the {username} var are owned by every user.
func (p *Page) Owned() bool {
pageOwner := p.Vars["username"]
return pageOwner == "" ||
(p.Session != nil && strings.EqualFold(p.Session.Username, pageOwner))
}
// Timezone returns the logged in user's timezone.
func (p *Page) Timezone() *string {
if p.Session != nil {
return p.Session.Timezone
}
return nil
}
// Username returns the logged in user's username.
func (p *Page) Username() string {
if p.Session != nil {
return p.Session.Username
}
return ""
}
// Email returns the logged in user's email.
func (p *Page) Email() string {
if p.Session != nil && p.Session.Email != nil {
return *p.Session.Email
}
return ""
}
// Theme returns the logged in user's theme.
func (p *Page) Theme() db.UserTheme {
if p.Session != nil {
return p.Session.Theme
}
return ""
}
// CLIToken returns the logged in user's CLI token.
func (p *Page) CLIToken() string {
if p.Session != nil {
return p.Session.CLIToken
}
return ""
}
// UserCreatedAt returns the logged in user's creation date.
func (p *Page) UserCreatedAt() string {
if p.Session != nil {
return p.Session.UserCreatedAt
}
return ""
}
func (p *Page) session() string {
if p.Session != nil {
return p.Session.Session
}
return ""
}
func (p *Page) userID() int64 {
if p.Session != nil {
return p.Session.UserID
}
return -1
}
func (p *Page) flashSuccess(msg string) {
p.SuccessMessage = msg
}
func (p *Page) setError(w http.ResponseWriter, err error) (done bool) {
var usererr *usererror.Error
if db.NotFound(err) {
log.Printf("resource not found: %s", err)
w.WriteHeader(http.StatusNotFound)
p.htmlFile = "404.html"
if err := p.writeFromHTML(w); err != nil {
staticError(w, "404", err)
}
return true
}
if errors.As(err, &usererr) {
log.Printf("flashing %s error: %s", usererr.Reason, err)
p.ErrorMessage = usererr.Message
} else {
log.Print("flashing fallback from unexpected error: ", err)
p.ErrorMessage = "Unexpected error - if this continues please contact an admin."
}
return false
}
// Sets p.Session when session cookie exists.
func (p *Page) setSession(w http.ResponseWriter, r *http.Request) error {
cookie, err := r.Cookie(sessionCookie)
if errors.Is(err, http.ErrNoCookie) {
return nil
} else if err != nil {
return err
}
p.Session, err = db.Session(db.Connection, cookie.Value)
if db.NotFound(err) {
// Session in cookie does not exist in DB.
// Unset it.
http.SetCookie(w, &http.Cookie{
Name: sessionCookie,
MaxAge: -1,
})
return nil
} else if err != nil {
return err
}
return nil
}
func (p *Page) setLinks() {
var (
userLink Link
settingsLink Link
)
if p.Session != nil {
username := p.Session.Username
userLink = newLink("/"+username, username, p.Title)
settingsLink = newLink("/settings", settingsTitle, p.Title)
} else {
userLink = newLink("/login", loginTitle, p.Title)
settingsLink = newLink("/signup", signupTitle, p.Title)
}
p.Links = []Link{
newLink("/", indexTitle, p.Title),
userLink,
newLink("/README.org", aboutTitle, p.Title),
settingsLink,
}
}
// Writes content from the templates/ directory.
func (p *Page) writeFromTemplate(w io.Writer) error {
p.setLinks()
baseClone, err := baseTemplate.Clone()
if err != nil {
return err
}
baseClone.Funcs(template.FuncMap{
"content": func() (template.HTML, error) {
buf := new(bytes.Buffer)
err := pageTemplates.ExecuteTemplate(buf, p.templateName, p)
if err != nil {
return "", err
}
return template.HTML(buf.String()), nil
},
})
return baseClone.Execute(w, p)
}
// Writes content from the html/ directory.
func (p *Page) writeFromHTML(w io.Writer) error {
p.setLinks()
baseClone, err := baseTemplate.Clone()
if err != nil {
return err
}
baseClone.Funcs(template.FuncMap{
"content": func() (template.HTML, error) {
html, err := ioutil.ReadFile(filepath.Join("html", p.htmlFile))
if err != nil {
return "", err
}
return template.HTML(html), err
},
})
return baseClone.Execute(w, p)
}
// Returns a page that will use a go template for content.
func pageFromTemplate(w http.ResponseWriter, r *http.Request, templateName, title string, protected bool) (*Page, error) {
p := &Page{
Title: title,
Vars: mux.Vars(r),
Data: make(map[string]interface{}),
templateName: templateName,
protected: protected,
}
if err := p.setSession(w, r); err != nil {
return nil, err
}
return p, nil
}
// Returns a page that will use a HTML file for content.
func pageFromHTML(w http.ResponseWriter, r *http.Request, title, htmlFile string) (*Page, error) {
p := &Page{
Title: title,
htmlFile: htmlFile,
}
if err := p.setSession(w, r); err != nil {
return nil, err
}
return p, nil
}
func loadTemplates() (err error) {
defaultContentFunction := template.FuncMap{
"content": func() (string, error) {
return "", errors.New("content is not set")
},
}
baseTemplate, err = template.
New("base").
Funcs(defaultContentFunction).
ParseFiles("templates/base.tmpl")
if err != nil {
return
}
pageFunctions := template.FuncMap{
// Global functions that page templates can call.
"shortenHash": dotfile.ShortenHash,
}
pageTemplates, err = template.
New("pages").
Funcs(pageFunctions).
ParseGlob("templates/*/*.tmpl")
return
}