-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.js
86 lines (78 loc) · 2.09 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
82
83
84
85
86
import multer from "multer";
const rewriteUnsupportedBrowserMethods = (req, res, next) => {
if (req.body && req.body._method) {
req.method = req.body._method;
delete req.body._method;
}
next();
};
function loggingMiddleware(req, res, next) {
let time = new Date().toUTCString();
let method = req.method;
let originalUrl = req.originalUrl;
let reqBody = JSON.stringify(req.body);
let isAuth = "Authenticated User";
if (!req.session.user) isAuth = "Non-Authenticated User";
console.log(`\[${time}\]: ${method} ${originalUrl} (${isAuth}) | ${reqBody}`);
next();
}
function noAuthRedirect(req, res, next) {
if (req.path === "/favicon.ico") return next();
if (!req.path.trim().startsWith("/public")) {
if (
!req.session.user &&
(req.path.trim() === "/" ||
(!req.path.trim().startsWith("/login") &&
!req.path.trim().startsWith("/register")))
) {
return res.redirect("/login");
}
}
next();
}
function authRedirect(req, res, next) {
if (req.path === "/favicon.ico") return next();
if (!req.path.trim().startsWith("/public")) {
if (
req.session.user &&
(req.path.trim().startsWith("/login") ||
req.path.trim().startsWith("/register") ||
req.path.trim() === "/")
) {
return res.redirect("/profile");
}
}
next();
}
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./public/images/profilepics/");
},
filename: (req, file, cb) => {
// console.log(file);
cb(null, `${Date.now()}-${file.originalname}`);
},
}),
// limits: { fileSize: 1 * 1024 * 1024 },
});
const itemUpload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./public/images/items/");
},
filename: (req, file, cb) => {
// console.log(file);
cb(null, `${Date.now()}-${file.originalname}`);
},
}),
// limits: { fileSize: 1 * 1024 * 1024 },
});
export default {
rewriteUnsupportedBrowserMethods,
loggingMiddleware,
noAuthRedirect,
authRedirect,
upload,
itemUpload,
};