-
Notifications
You must be signed in to change notification settings - Fork 2
/
upload_evidence.go
337 lines (270 loc) · 8.47 KB
/
upload_evidence.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
334
335
336
337
package donor
import (
"bufio"
"bytes"
"errors"
"html"
"io"
"net/http"
"slices"
"github.com/gabriel-vasile/mimetype"
"github.com/ministryofjustice/opg-go-common/template"
"github.com/ministryofjustice/opg-modernising-lpa/internal/actor"
"github.com/ministryofjustice/opg-modernising-lpa/internal/page"
"github.com/ministryofjustice/opg-modernising-lpa/internal/pay"
"github.com/ministryofjustice/opg-modernising-lpa/internal/validation"
)
type uploadError int
func (uploadError) Error() string { return "err" }
const (
peekSize = 2000 // to account for detecting MS Office files
maxFileSize = 20 << 20 // 20Mb
numberOfAllowedFiles = 5
errEmptyFile = uploadError(1)
errUnexpectedContentType = uploadError(2)
errFileTooBig = uploadError(3)
errTooManyFiles = uploadError(4)
errFileNotSelected = uploadError(5)
)
func acceptedMimeTypes() []string {
return []string{
"application/pdf",
"image/png",
"image/jpeg",
"image/tiff",
"image/heic",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.oasis.opendocument.text",
"application/vnd.oasis.opendocument.spreadsheet",
"application/vnd.oasis.opendocument.spreadsheet",
}
}
type uploadEvidenceData struct {
App page.AppData
Errors validation.List
NumberOfAllowedFiles int
FeeType pay.FeeType
Documents page.Documents
MimeTypes []string
Deleted string
StartScan string
}
func UploadEvidence(tmpl template.Template, logger Logger, payer Payer, documentStore DocumentStore) Handler {
return func(appData page.AppData, w http.ResponseWriter, r *http.Request, donor *actor.DonorProvidedDetails) error {
if donor.Tasks.PayForLpa.IsPending() {
return page.Paths.TaskList.Redirect(w, r, appData, donor)
}
documents, err := documentStore.GetAll(r.Context())
if err != nil {
return err
}
data := &uploadEvidenceData{
App: appData,
NumberOfAllowedFiles: numberOfAllowedFiles,
FeeType: donor.FeeType,
Documents: documents,
MimeTypes: acceptedMimeTypes(),
}
if r.Method == http.MethodPost {
r.Body = http.MaxBytesReader(w, r.Body, numberOfAllowedFiles*maxFileSize+512)
form := readUploadEvidenceForm(r)
data.Errors = form.Validate()
if data.Errors.None() {
switch form.Action {
case "upload":
var uploadedDocuments []page.Document
for _, file := range form.Files {
document, err := documentStore.Create(r.Context(), donor, file.Filename, file.Data)
if err != nil {
return err
}
uploadedDocuments = append(uploadedDocuments, document)
}
data.Documents = uploadedDocuments
data.StartScan = "1"
case "scanResults":
infectedFilenames := documents.InfectedFilenames()
if len(infectedFilenames) > 0 {
if err := documentStore.DeleteInfectedDocuments(r.Context(), documents); err != nil {
return err
}
refreshedDocuments, err := documentStore.GetAll(r.Context())
if err != nil {
return err
}
data.Errors = validation.With("upload", validation.FilesInfectedError{Label: "upload", Filenames: infectedFilenames})
data.Documents = refreshedDocuments
return tmpl(w, data)
}
case "pay":
if len(documents.NotScanned()) > 0 {
logger.Print("attempt to pay with unscanned documents on lpa:", donor.LpaUID)
data.Errors = validation.With("upload", validation.CustomError{Label: "errorGenericUploadProblem"})
return tmpl(w, data)
}
if err := documentStore.Submit(r.Context(), donor, documents); err != nil {
return err
}
return payer.Pay(appData, w, r, donor)
case "delete":
document := documents.Get(form.DeleteKey)
if document.Key != "" {
data.Deleted = document.Filename
if err := documentStore.Delete(r.Context(), document); err != nil {
return err
}
documents.Delete(document.Key)
data.Documents = documents
}
case "closeConnection", "cancelUpload":
for _, d := range documents {
if d.Key != "" && !d.Scanned {
if err := documentStore.Delete(r.Context(), d); err != nil {
return err
}
documents.Delete(d.Key)
}
}
data.Documents = documents
if form.Action == "closeConnection" {
data.Errors = validation.With("upload", validation.CustomError{Label: "errorGenericUploadProblem"})
}
return tmpl(w, data)
default:
return errors.New("unexpected action")
}
}
}
return tmpl(w, data)
}
}
type File struct {
Data []byte
Filename string
Error error
}
type uploadEvidenceForm struct {
Files []File
Action string
DeleteKey string
Error error
}
func readUploadEvidenceForm(r *http.Request) *uploadEvidenceForm {
form := &uploadEvidenceForm{}
reader, err := r.MultipartReader()
if err != nil {
return &uploadEvidenceForm{Error: err}
}
// first part will be csrf, so skip
part, err := reader.NextPart()
if err != nil && err != io.EOF {
return &uploadEvidenceForm{Error: err}
}
if part.FormName() != "csrf" {
return &uploadEvidenceForm{Error: errors.New("unexpected field name")}
}
part, err = reader.NextPart()
if err != nil && err != io.EOF {
return &uploadEvidenceForm{Error: err}
}
if part.FormName() != "action" {
return &uploadEvidenceForm{Error: errors.New("unexpected field name")}
}
buf := new(bytes.Buffer)
buf.ReadFrom(part)
form.Action = buf.String()
if form.Action == "upload" {
// upload part
files := make([]File, 0, 5)
for {
part, err = reader.NextPart()
if err == io.EOF {
break
}
if err != nil {
return &uploadEvidenceForm{Error: err}
}
if part.FormName() != "upload" {
return &uploadEvidenceForm{Error: errors.New("unexpected field name"), Action: "upload"}
}
if len(files) >= numberOfAllowedFiles {
return &uploadEvidenceForm{Error: errTooManyFiles, Action: "upload"}
}
buf := bufio.NewReader(part)
sniff, _ := buf.Peek(peekSize)
filename := html.EscapeString(part.FileName())
if len(sniff) == 0 {
if filename == "" {
files = append(files, File{Error: errFileNotSelected})
} else {
files = append(files, File{Error: errEmptyFile, Filename: filename})
}
continue
}
mimetype.SetLimit(peekSize)
contentType := mimetype.Detect(sniff)
if !slices.Contains(acceptedMimeTypes(), contentType.String()) {
files = append(files, File{Error: errUnexpectedContentType, Filename: filename})
continue
}
var f bytes.Buffer
lmt := io.MultiReader(buf, io.LimitReader(part, maxFileSize-peekSize+1))
copied, err := io.Copy(&f, lmt)
if err != nil && err != io.EOF {
return &uploadEvidenceForm{Error: err, Action: "upload"}
}
if copied > maxFileSize {
files = append(files, File{Error: errFileTooBig, Filename: filename})
continue
}
files = append(files, File{
Data: f.Bytes(),
Filename: filename,
})
}
form.Files = files
}
if form.Action == "delete" {
part, err = reader.NextPart()
if part.FormName() != "delete" {
return &uploadEvidenceForm{Error: errors.New("unexpected field name"), Action: "delete"}
}
buf := new(bytes.Buffer)
buf.ReadFrom(part)
form.DeleteKey = buf.String()
}
return form
}
func (f *uploadEvidenceForm) Validate() validation.List {
var errors validation.List
if f.Error != nil {
field := "upload"
if f.Action != "" {
field = f.Action
}
switch f.Error {
case errTooManyFiles:
errors.Add("upload", validation.CustomError{Label: "errorTooManyFiles"})
default:
errors.Add(field, validation.CustomError{Label: "errorGenericUploadProblem"})
}
}
for _, file := range f.Files {
if file.Error != nil {
switch file.Error {
case errUnexpectedContentType:
errors.Add("upload", validation.FileError{Label: "errorFileIncorrectType", Filename: file.Filename})
case errFileTooBig:
errors.Add("upload", validation.FileError{Label: "errorFileTooBig", Filename: file.Filename})
case errEmptyFile:
errors.Add("upload", validation.FileError{Label: "errorFileEmpty", Filename: file.Filename})
case errFileNotSelected:
errors.Add("upload", validation.FileError{Label: "errorFileNotSelected"})
default:
errors.Add("upload", validation.FileError{Label: "errorGenericUploadProblemFile", Filename: file.Filename})
}
}
}
return errors
}