-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileController.java
More file actions
500 lines (480 loc) · 20.3 KB
/
FileController.java
File metadata and controls
500 lines (480 loc) · 20.3 KB
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package File;
import static User.UserController.mergeJSON;
import Config.Message;
import Database.File.FileDao;
import Database.Form.FormDao;
import Database.User.UserDao;
import File.Services.*;
import PDF.PdfMessage;
import PDF.Services.CrudServices.ImageToPDFService;
import Security.EncryptionController;
import User.Services.GetUserInfoService;
import User.User;
import User.UserMessage;
import User.UserType;
import com.mongodb.client.MongoDatabase;
import io.javalin.http.Handler;
import io.javalin.http.UploadedFile;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.json.JSONObject;
@Slf4j
public class FileController {
private UserDao userDao;
private FileDao fileDao;
private FormDao formDao;
private EncryptionController encryptionController;
public FileController(
MongoDatabase db,
UserDao userDao,
FileDao fileDao,
FormDao formDao,
EncryptionController encryptionController) {
this.userDao = userDao;
this.fileDao = fileDao;
this.formDao = formDao;
this.encryptionController = encryptionController;
}
/*
Multipart body with following fields:
- "fileType": String giving the file type (see FileType enum)
- if "fileType" is a PDF type
- "toSign": boolean indicating whether or not the PDF needs signing
- if "toSign" is True
- "signature": the signature image to place in file
- if "fileType" is of FORM_PDF
- "annotated": boolean for setting whether the PDF is annotated (default false)
- if "annotated" is True
- "fileID": the fileID to replace
- "file": the file to be uploaded
- "targetUser": the user the file is being uploaded for
*/
public Handler fileUpload =
ctx -> {
log.info("Uploading file...");
String username;
String organizationName;
UserType privilegeLevel;
Message response = null;
UploadedFile file = ctx.uploadedFile("file");
JSONObject req = new JSONObject();
String body = null;
try {
req.put("targetUser", ctx.formParam("targetUser"));
req.put("idCategory", ctx.formParam("idCategory"));
req.put("fileType", ctx.formParam("fileType"));
body = req.toString();
} catch (Exception e) {
System.out.println(e);
req = null;
}
Optional<User> maybeTargetUser = GetUserInfoService.getUserFromRequest(this.userDao, body);
if (maybeTargetUser.isEmpty() && req.has("targetUser")) {
log.info("Target user could not be found in the database");
response = UserMessage.USER_NOT_FOUND;
} else {
boolean orgFlag;
if (req != null && req.has("targetUser") && maybeTargetUser.isPresent()) {
log.info("Target user found, setting parameters.");
username = maybeTargetUser.get().getUsername();
organizationName = maybeTargetUser.get().getOrganization();
privilegeLevel = maybeTargetUser.get().getUserType();
orgFlag = organizationName.equals(ctx.sessionAttribute("orgName"));
} else {
log.info("Checking session for user.");
username = ctx.sessionAttribute("username");
organizationName = ctx.sessionAttribute("orgName");
privilegeLevel = ctx.sessionAttribute("privilegeLevel");
orgFlag = true;
}
if (orgFlag) {
if (file == null) {
log.info("File is null, invalid file!");
response = FileMessage.INVALID_FILE;
} else {
FileType fileType =
FileType.createFromString(Objects.requireNonNull(ctx.formParam("fileType")));
log.info("Received file type of {}", fileType.toString());
boolean annotated = false;
IdCategoryType idCategory = IdCategoryType.NONE;
boolean toSign = false;
if (ctx.formParam("annotated") != null) {
annotated = Boolean.parseBoolean(ctx.formParam("annotated"));
}
if (ctx.formParam("idCategory") != null) {
idCategory = IdCategoryType.createFromString(ctx.formParam("idCategory"));
}
if (ctx.formParam("toSign") != null) {
toSign = Boolean.parseBoolean(ctx.formParam("toSign"));
}
String fileId = null;
UploadedFile signature = null;
Date uploadDate =
Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
InputStream filestreamToUpload = file.content();
String filenameToUpload = file.filename();
switch (fileType) {
case APPLICATION_PDF:
case IDENTIFICATION_PDF:
case FORM:
log.info("Got PDF file to upload!");
if (Objects.requireNonNull(file.contentType()).startsWith("image")) {
ImageToPDFService imageToPDFService = new ImageToPDFService(filestreamToUpload);
Message imageToPdfServiceResponse = imageToPDFService.executeAndGetResponse();
if (imageToPdfServiceResponse == PdfMessage.INVALID_PDF) {
ctx.result(imageToPdfServiceResponse.toResponseString());
return;
}
filestreamToUpload = imageToPDFService.getFileStream();
filenameToUpload =
file.filename().substring(0, file.filename().lastIndexOf("."))
+ ".pdf";
}
if (!Objects.requireNonNull(file.contentType()).startsWith("image")) {
filestreamToUpload = file.content();
}
if (toSign) {
signature = Objects.requireNonNull(ctx.uploadedFile("signature"));
}
if (fileType == FileType.FORM && annotated) {
fileId = Objects.requireNonNull(ctx.formParam("fileID"));
}
File fileToUpload =
new File(
username,
uploadDate,
filestreamToUpload,
fileType,
idCategory,
filenameToUpload,
organizationName,
annotated,
file.contentType());
UploadFileService uploadService =
new UploadFileService(
fileDao,
fileToUpload,
Optional.ofNullable(privilegeLevel),
Optional.ofNullable(fileId),
toSign,
signature == null
? Optional.empty()
: Optional.of(signature.content()),
Optional.ofNullable(encryptionController));
response = uploadService.executeAndGetResponse();
break;
case PROFILE_PICTURE:
log.info("Got profile picture to upload!");
fileToUpload =
new File(
username,
uploadDate,
filestreamToUpload,
fileType,
idCategory,
filenameToUpload,
organizationName,
annotated,
file.contentType());
uploadService =
new UploadFileService(
fileDao,
fileToUpload,
Optional.ofNullable(privilegeLevel),
Optional.ofNullable(fileId),
toSign,
Optional.empty(),
Optional.ofNullable(encryptionController));
response = uploadService.executeAndGetResponse();
break;
case MISC:
log.info("Got miscellaneous file to upload!");
fileToUpload =
new File(
username,
uploadDate,
filestreamToUpload,
fileType,
idCategory,
filenameToUpload,
organizationName,
annotated,
file.contentType());
uploadService =
new UploadFileService(
fileDao,
fileToUpload,
Optional.ofNullable(privilegeLevel),
Optional.ofNullable(fileId),
toSign,
Optional.empty(),
Optional.ofNullable(encryptionController));
response = uploadService.executeAndGetResponse();
break;
}
}
} else {
response = UserMessage.CROSS_ORG_ACTION_DENIED;
}
}
ctx.result(response.toResponseString());
};
/*
REQUIRES JSON Body:
- "fileType": String giving File Type (see FileType enum)
- "fileId": String giving id of file to be downloaded
- OPTIONAL- "targetUser": User whose file you want to access.
- If left empty, defaults to original username.
*/
public Handler fileDownload =
ctx -> {
String username;
String orgName;
UserType userType;
JSONObject req = new JSONObject(ctx.body());
Optional<User> maybeTargetUser =
GetUserInfoService.getUserFromRequest(this.userDao, ctx.body());
if (maybeTargetUser.isEmpty() && req.has("targetUser")) {
log.info("Target User not Found");
ctx.result(UserMessage.USER_NOT_FOUND.toJSON().toString());
} else {
boolean orgFlag;
if (maybeTargetUser.isPresent() && req.has("targetUser")) {
log.info("Target user found");
username = maybeTargetUser.get().getUsername();
orgName = maybeTargetUser.get().getOrganization();
userType = maybeTargetUser.get().getUserType();
// orgFlag = orgName.equals(ctx.sessionAttribute("orgName"));
orgFlag = true;
} else {
username = ctx.sessionAttribute("username");
orgName = ctx.sessionAttribute("orgName");
userType = ctx.sessionAttribute("privilegeLevel");
orgFlag = true;
}
if (orgFlag) {
String fileIDStr = req.getString("fileId");
String fileTypeStr = req.getString("fileType");
FileType fileType = FileType.createFromString(fileTypeStr);
DownloadFileService downloadFileService =
new DownloadFileService(
fileDao,
username,
Optional.ofNullable(orgName),
Optional.ofNullable(userType),
fileType,
Optional.ofNullable(fileIDStr),
Optional.ofNullable(encryptionController),
formDao);
Message response = downloadFileService.executeAndGetResponse();
if (response == FileMessage.SUCCESS) {
ctx.header("Content-Type", downloadFileService.getContentType());
ctx.result(downloadFileService.getInputStream());
} else {
ctx.result(response.toResponseString());
}
} else {
ctx.result(UserMessage.CROSS_ORG_ACTION_DENIED.toResponseString());
}
}
};
/*
REQUIRES JSON Body with:
- "fileType": String giving File Type (see FileType enum)
- "fileId": String giving id of file to be deleted
- OPTIONAL- "targetUser": User whose file you want to access.
- If left empty, defaults to original username.
*/
public Handler fileDelete =
ctx -> {
String username;
String orgName;
UserType userType;
JSONObject req = new JSONObject(ctx.body());
Optional<User> maybeTargetUser =
GetUserInfoService.getUserFromRequest(this.userDao, ctx.body());
if (maybeTargetUser.isEmpty() && req.has("targetUser")) {
ctx.result(UserMessage.USER_NOT_FOUND.toJSON().toString());
} else {
boolean orgFlag;
if (maybeTargetUser.isPresent() && req.has("targetUser")) {
log.info("Target user found");
username = maybeTargetUser.get().getUsername();
orgName = maybeTargetUser.get().getOrganization();
userType = maybeTargetUser.get().getUserType();
orgFlag = orgName.equals(ctx.sessionAttribute("orgName"));
} else {
username = ctx.sessionAttribute("username");
orgName = ctx.sessionAttribute("orgName");
userType = ctx.sessionAttribute("privilegeLevel");
// User is in same org as themselves
orgFlag = true;
}
if (orgFlag) {
String fileIDStr = req.getString("fileId");
String fileTypeStr = req.getString("fileType");
FileType fileType = FileType.createFromString(fileTypeStr);
DeleteFileService deleteFileService =
new DeleteFileService(fileDao, username, orgName, userType, fileType, fileIDStr);
ctx.result(deleteFileService.executeAndGetResponse().toResponseString());
} else {
ctx.result(UserMessage.CROSS_ORG_ACTION_DENIED.toResponseString());
}
}
};
/*
REQUIRES JSON Body:
- Body
- "fileType": String giving File Type (See FileType enum)
- if "fileType" is "FORM_PDF"
- "annotated": boolean for retrieving EITHER annotated forms OR unannotated forms
- OPTIONAL- "targetUser": User whose file you want to access.
- If left empty, defaults to original username.
*/
public Handler getFiles =
ctx -> {
log.info("Starting pdfGetDocuments");
String username;
String orgName;
UserType userType;
String reqBody = ctx.body();
JSONObject req = new JSONObject(reqBody);
JSONObject responseJSON;
System.out.println("REQ: " + req);
Optional<User> maybeTargetUser =
GetUserInfoService.getUserFromRequest(this.userDao, reqBody);
System.out.println("filetype: " + req.getString("fileType"));
if (maybeTargetUser.isEmpty() && req.has("targetUser")) {
log.info("Target User not Found");
responseJSON = UserMessage.USER_NOT_FOUND.toJSON();
} else {
boolean orgFlag;
if (maybeTargetUser.isPresent() && req.has("targetUser")) {
log.info("Target user found");
username = maybeTargetUser.get().getUsername();
orgName = maybeTargetUser.get().getOrganization();
userType = maybeTargetUser.get().getUserType();
orgFlag = orgName.equals(ctx.sessionAttribute("orgName"));
} else {
username = ctx.sessionAttribute("username");
orgName = ctx.sessionAttribute("orgName");
userType = ctx.sessionAttribute("privilegeLevel");
orgFlag = true;
}
if (orgFlag) {
FileType fileType = FileType.createFromString(req.getString("fileType"));
boolean annotated = false;
if (fileType == FileType.FORM) {
annotated = Objects.requireNonNull(req.getBoolean("annotated"));
}
GetFilesInformationService getFilesInformationService =
new GetFilesInformationService(
fileDao, username, orgName, userType, fileType, annotated);
Message response = getFilesInformationService.executeAndGetResponse();
responseJSON = response.toJSON();
if (response == FileMessage.SUCCESS) {
responseJSON.put("documents", getFilesInformationService.getFilesJSON());
}
} else {
responseJSON = UserMessage.CROSS_ORG_ACTION_DENIED.toJSON();
}
}
ctx.result(responseJSON.toString());
};
/*
REQUIRES JSON Body:
- "applicationId": String giving id of application to get questions from
*/
public Handler getApplicationQuestions =
ctx -> {
JSONObject req = new JSONObject(ctx.body());
String applicationId = req.getString("applicationId");
String username = ctx.sessionAttribute("username");
String organizationName = ctx.sessionAttribute("orgName");
UserType privilegeLevel = ctx.sessionAttribute("privilegeLevel");
DownloadFileService downloadFileService =
new DownloadFileService(
fileDao,
username,
Optional.ofNullable(organizationName),
Optional.ofNullable(privilegeLevel),
FileType.FORM,
Optional.ofNullable(applicationId),
Optional.ofNullable(encryptionController),
formDao);
Message responseDownload = downloadFileService.executeAndGetResponse();
if (responseDownload == FileMessage.SUCCESS) {
InputStream inputStream = downloadFileService.getInputStream();
GetQuestionsPDFFileService getQuestionsPDFFileService =
new GetQuestionsPDFFileService(userDao, privilegeLevel, username, inputStream);
Message response = getQuestionsPDFFileService.executeAndGetResponse();
if (response == FileMessage.SUCCESS) {
JSONObject information = getQuestionsPDFFileService.getApplicationInformation();
ctx.result(mergeJSON(response.toJSON(), information).toString());
} else {
ctx.result(response.toJSON().toString());
}
} else {
ctx.result(responseDownload.toResponseString());
}
};
/*
REQUIRES JSON Body:
- "applicationId": String giving id of application to fill out
- "formAnswers": JSON with format
{
"Field1 Name": Field 1's Answer,
"Field2 Name": Field 2's Answer,
...
}
*/
public Handler fillPDFForm =
ctx -> {
JSONObject req = new JSONObject(ctx.body());
String applicationId = req.getString("applicationId");
String username = ctx.sessionAttribute("username");
String organizationName = ctx.sessionAttribute("orgName");
UserType privilegeLevel = ctx.sessionAttribute("privilegeLevel");
JSONObject formAnswers = req.getJSONObject("formAnswers");
DownloadFileService downloadFileService =
new DownloadFileService(
fileDao,
username,
Optional.ofNullable(organizationName),
Optional.ofNullable(privilegeLevel),
FileType.FORM,
Optional.ofNullable(applicationId),
Optional.ofNullable(encryptionController),
formDao);
Message responseDownload = downloadFileService.executeAndGetResponse();
if (responseDownload == FileMessage.SUCCESS) {
InputStream inputStream = downloadFileService.getInputStream();
FillPDFFileService fillPDFFileService =
new FillPDFFileService(privilegeLevel, inputStream, formAnswers);
Message response = fillPDFFileService.executeAndGetResponse();
if (response == FileMessage.SUCCESS) {
ctx.header("Content-Type", "application/pdf");
ctx.result(fillPDFFileService.getCompletedForm());
} else {
ctx.result(response.toResponseString());
}
} else {
ctx.result(responseDownload.toResponseString());
}
};
public static String getPDFTitle(String fileName, PDDocument pdfDocument) {
String title = fileName;
pdfDocument.setAllSecurityToBeRemoved(true);
String titleTmp = pdfDocument.getDocumentInformation().getTitle();
if (titleTmp != null) {
title = titleTmp;
}
return title;
}
}