forked from bokwoon95/notebrew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deletesite.go
333 lines (322 loc) · 9.19 KB
/
deletesite.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package notebrew
import (
"database/sql"
"encoding/json"
"errors"
"html/template"
"io/fs"
"mime"
"net/http"
"net/url"
"strings"
"github.com/bokwoon95/notebrew/sq"
)
func (nbrew *Notebrew) deletesite(w http.ResponseWriter, r *http.Request, user User) {
type Request struct {
SiteName string `json:"siteName"`
ConfirmSiteName string `json:"confirmSiteName"`
}
type Response struct {
UserID ID `json:"userID"`
Username string `json:"username"`
DisableReason string `json:"disableReason"`
SiteName string `json:"siteName"`
ConfirmSiteName string `json:"confirmSiteName"`
Error string `json:"error"`
FormErrors url.Values `json:"formErrors"`
}
validateSiteName := func(siteName string) bool {
if len(siteName) > 30 {
return false
}
for _, char := range siteName {
if (char < 'a' && char > 'z') && (char < '0' && char > '9') && char != '-' && char != '.' {
return false
}
}
return true
}
getSitePermissions := func(siteName, username string) (siteNotFound, userIsAuthorized bool, err error) {
if nbrew.DB == nil {
return false, true, nil
}
userIsAuthorized, err = sq.FetchOne(r.Context(), nbrew.DB, sq.Query{
Dialect: nbrew.Dialect,
Format: "SELECT {*}" +
" FROM site" +
" LEFT JOIN site_owner ON site_owner.site_id = site.site_id" +
" LEFT JOIN users ON users.user_id = site_owner.user_id" +
" WHERE site.site_name = {siteName}" +
" AND users.username = {username}",
Values: []any{
sq.StringParam("siteName", siteName),
sq.StringParam("username", username),
},
}, func(row *sq.Row) bool {
return row.Bool("users.user_id IS NOT NULL")
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return true, false, nil
}
return false, false, err
}
return siteNotFound, userIsAuthorized, nil
}
switch r.Method {
case "GET", "HEAD":
writeResponse := func(w http.ResponseWriter, r *http.Request, response Response) {
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if r.Method == "HEAD" {
w.WriteHeader(http.StatusOK)
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(&response)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return
}
referer := nbrew.GetReferer(r)
funcMap := map[string]any{
"trimPrefix": strings.TrimPrefix,
"contains": strings.Contains,
"stylesCSS": func() template.CSS { return template.CSS(StylesCSS) },
"baselineJS": func() template.JS { return template.JS(BaselineJS) },
"referer": func() string { return referer },
"username": func() string { return user.Username },
}
tmpl, err := template.New("deletesite.html").Funcs(funcMap).ParseFS(RuntimeFS, "embed/deletesite.html")
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
w.Header().Set("Content-Security-Policy", nbrew.ContentSecurityPolicy)
nbrew.ExecuteTemplate(w, r, tmpl, &response)
}
var response Response
_, err := nbrew.GetFlashSession(w, r, &response)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
response.UserID = user.UserID
response.Username = user.Username
response.DisableReason = user.DisableReason
if response.Error != "" {
writeResponse(w, r, response)
return
}
response.SiteName = r.Form.Get("name")
if response.SiteName == "" {
response.Error = "SiteNameNotProvided"
writeResponse(w, r, response)
return
}
valid := validateSiteName(response.SiteName)
if !valid {
response.Error = "InvalidSiteName"
writeResponse(w, r, response)
return
}
siteNotFound, userIsAuthorized, err := getSitePermissions(response.SiteName, user.Username)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
if siteNotFound {
response.Error = "SiteNotFound"
writeResponse(w, r, response)
return
}
if !userIsAuthorized {
response.Error = "NotAuthorized"
writeResponse(w, r, response)
return
}
writeResponse(w, r, response)
case "POST":
if user.DisableReason != "" {
nbrew.AccountDisabled(w, r, user.DisableReason)
return
}
writeResponse := func(w http.ResponseWriter, r *http.Request, response Response) {
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
b, err := json.Marshal(&response)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
w.Write(b)
return
}
if response.Error != "" {
err := nbrew.SetFlashSession(w, r, &response)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
http.Redirect(w, r, "/files/deletesite/?name="+url.QueryEscape(response.SiteName), http.StatusFound)
return
}
err := nbrew.SetFlashSession(w, r, map[string]any{
"postRedirectGet": map[string]any{
"from": "deletesite",
"siteName": response.SiteName,
},
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
http.Redirect(w, r, "/files/", http.StatusFound)
}
var request Request
r.Body = http.MaxBytesReader(w, r.Body, 1<<20 /* 1 MB */)
contentType, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
switch contentType {
case "application/json":
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
nbrew.BadRequest(w, r, err)
return
}
case "application/x-www-form-urlencoded", "multipart/form-data":
if contentType == "multipart/form-data" {
err := r.ParseMultipartForm(1 << 20 /* 1 MB */)
if err != nil {
nbrew.BadRequest(w, r, err)
return
}
} else {
err := r.ParseForm()
if err != nil {
nbrew.BadRequest(w, r, err)
return
}
}
request.SiteName = r.Form.Get("siteName")
request.ConfirmSiteName = r.Form.Get("confirmSiteName")
default:
nbrew.UnsupportedContentType(w, r)
return
}
response := Response{
FormErrors: make(url.Values),
SiteName: request.SiteName,
ConfirmSiteName: request.ConfirmSiteName,
}
if response.SiteName == "" {
response.Error = "SiteNameNotProvided"
writeResponse(w, r, response)
return
}
ok := validateSiteName(response.SiteName)
if !ok {
response.Error = "InvalidSiteName"
writeResponse(w, r, response)
return
}
siteNotFound, userIsAuthorized, err := getSitePermissions(response.SiteName, user.Username)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
if siteNotFound {
response.Error = "SiteNotFound"
writeResponse(w, r, response)
return
}
if !userIsAuthorized {
response.Error = "NotAuthorized"
writeResponse(w, r, response)
return
}
if response.ConfirmSiteName != response.SiteName {
response.FormErrors.Add("confirmSiteName", "site name does not match")
response.Error = "FormErrorsPresent"
writeResponse(w, r, response)
return
}
var sitePrefix string
if strings.Contains(response.SiteName, ".") {
sitePrefix = response.SiteName
} else {
sitePrefix = "@" + response.SiteName
}
err = nbrew.FS.RemoveAll(sitePrefix)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
if nbrew.DB != nil {
tx, err := nbrew.DB.Begin()
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
defer tx.Rollback()
_, err = sq.Exec(r.Context(), tx, sq.Query{
Dialect: nbrew.Dialect,
Format: "DELETE FROM site_owner WHERE EXISTS (" +
"SELECT 1 FROM site WHERE site.site_id = site_owner.site_id AND site.site_name = {siteName}" +
")",
Values: []any{
sq.StringParam("siteName", request.SiteName),
},
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
_, err = sq.Exec(r.Context(), tx, sq.Query{
Dialect: nbrew.Dialect,
Format: "DELETE FROM site_user WHERE EXISTS (" +
"SELECT 1 FROM site WHERE site.site_id = site_user.site_id AND site.site_name = {siteName}" +
")",
Values: []any{
sq.StringParam("siteName", request.SiteName),
},
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
_, err = sq.Exec(r.Context(), tx, sq.Query{
Dialect: nbrew.Dialect,
Format: "DELETE FROM site WHERE site_name = {siteName}",
Values: []any{
sq.StringParam("siteName", request.SiteName),
},
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
err = tx.Commit()
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
}
writeResponse(w, r, response)
default:
nbrew.MethodNotAllowed(w, r)
}
}