-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
47 lines (36 loc) · 1.23 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
const ExpressError = require("./utilities/ExpressError")
const { flatSchema, aptSchema } = require("./schemas");
const Flat = require("./models/flat");
module.exports.isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl;
req.flash("error", "Niste ulogovani.");
return res.redirect("/login");
} next();
}
module.exports.validateFlat = (req, res, next) => {
const { error } = flatSchema.validate(req.body)
if (error) {
const msg = error.details.map(el => el.message).join(",")
throw new ExpressError(msg, 400)
} else {
next()
}
}
module.exports.isAuthor = async (req, res, next) => {
const { id } = req.params;
const flat = await Flat.findById(id);
if (!flat.author.equals(req.user._id)) {
req.flash("error", "Korisnik nije autor nekretnine")
return res.redirect("/flats")
} next();
}
module.exports.validateApt = (req, res, next) => {
const { error } = aptSchema.validate(req.body)
if (error) {
const msg = error.details.map(el => el.message).join(",")
throw new ExpressError(msg, 400)
} else {
next()
}
}