-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
81 lines (77 loc) · 2.25 KB
/
middleware.js
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
const multer = require("multer");
const { multerConfig } = require("./config/general.config");
const upload = multer(multerConfig);
const fs = require("fs");
module.exports.isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl;
req.user = false;
req.flash("error", "You must be logged in to view this page!");
return res.redirect("/");
} else {
next();
}
};
module.exports.isAdminAuthenticated = (req, res, next) => {
if (process.env.NODE_ENV === "development") {
// bypass admin auth in development mode
next();
} else {
if (
req.user === undefined ||
!req.user.is_admin ||
!req.isAuthenticated()
) {
req.session.returnTo = req.originalUrl;
req.user = false;
req.flash("error", "You do not have permission to view this page!");
return res.redirect("/");
} else {
next();
}
}
};
module.exports.upload = (id) => {
const impl = upload.single(id);
return async (req, res, next) => {
impl(req, res, async (err) => {
if (err instanceof multer.MulterError) {
req.flash(
"error",
"Please upload a valid image. Only JPEG, JPG, and PNG files are allowed, and they must be under 5MB.",
);
res.redirect(req.url);
} else if (err) {
req.flash(
"error",
"An error occurred while trying to upload your image! Please try again. If the issue persists, contact us.",
);
res.redirect(req.url);
} else {
next();
}
});
};
};
module.exports.fallible = (block) => {
return async (req, res, next) => {
try {
await block(req, res);
} catch (e) {
// If any upload middleware was used, we will need to remove the
// newly-uploaded image as it's unlikely to be referenced anywhere
// in the database.
if (req.file) {
try {
fs.unlinkSync("uploads/" + req.file.filename);
} catch (e) {
// Letting this error be thrown would crash the server, and
// routing it to next would override the original error we
// wanted to catch and make debugging more difficult. Thus,
// we ignore the error.
}
}
next(e);
}
};
};