-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddlewares.js
More file actions
55 lines (49 loc) · 1.65 KB
/
middlewares.js
File metadata and controls
55 lines (49 loc) · 1.65 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
const { postSchema, commentSchema } = require("./schema");
const ExpressError = require("./utility/ExpressError");
const Comment = require("./models/comments");
const Post = require("./models/posts");
module.exports.isLoggedIn = (req, res, next) => {
req.session.redirectUrl = req.originalUrl;
if (!req.session.user) {
req.session.redirectUrl = req.originalUrl;
req.flash("error", "You are not logged In")
return res.redirect("/login");
}
next();
}
module.exports.isAuthor = async (req, res, next) => {
let { id, commentId } = req.params;
let comment = await Comment.findById(commentId).populate("author");
if (String(comment.author._id) !== req.session.user._id) {
req.flash("error", "You are not the Owner of the Comment");
return res.redirect(`/posts/${id}`);
}
next();
}
module.exports.isOwner = async (req, res, next) => {
let { id } = req.params;
let post = await Post.findById(id).populate("owner");
let owner = String(post.owner._id);
let sessionUser = req.session.user._id;
if (owner !== sessionUser) {
req.flash("error", "You are not the Owner of the post");
return res.redirect(`/posts/${id}`);
}
next();
}
module.exports.validatePost = (req, res, next) => {
let { error } = postSchema.validate(req.body);
if (error) {
throw new ExpressError(error.details[0].message, 400)
} else {
next();
}
}
module.exports.validateComment = (req, res, next) => {
let { error } = commentSchema.validate(req.body);
if (error) {
throw new ExpressError(error.details[0].message, 400)
} else {
next();
}
}