-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.js
More file actions
185 lines (162 loc) · 5.03 KB
/
middleware.js
File metadata and controls
185 lines (162 loc) · 5.03 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
const BaseJoi = require('joi');
const Article = require('./models/article');
const ExpressError = require('./utils/ExpressError');
const Dog = require('./models/pets/dog');
const Cat = require('./models/pets/cat');
const Bird = require('./models/pets/bird');
const Smallandfurry = require('./models/pets/saf');
const Other = require('./models/pets/other');
const sanitizeHTML = require('sanitize-html');
// const
const extension = (joi) => ({
type: 'string',
base: joi.string(),
messages: {
'string.escapeHTML': '{{#label}} must not include HTML!'
},
rules: {
escapeHTML: {
validate(value, helpers) {
const clean = sanitizeHTML(value, {
allowedTags: [],
allowedAttributes: {},
});
if (clean !== value) return helpers.error('string.escapeHTML', { value })
return clean;
}
}
}
})
const Joi = BaseJoi.extend(extension)
const isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl;
req.flash('error', 'You must be signed in first!');
return res.redirect('/adopet/auth')
}
next();
}
const storeReturnTo = (req, res, next)=>{
if(req.session.returnTo){
res.locals.returnTo = req.session.returnTo;
}
next();
}
const validateUser = (req, res, next) => {
const userSchema = Joi.object({
username: Joi.string().required(),
password: Joi.string()
// .min(8)
.required(),
email: Joi.string().required(),
phone: Joi.string()
// .pattern(new RegExp('/^[0-9]{10}$/'))
.required()
.messages({ 'string.pattern.base': 'Invalid phone number. Please provide a 10-digit number.', }),
}).required()
const { error } = userSchema.validate(req.body);
if (error) {
const msg = error.details.map(el => el.message).join(',')
// console.log(error);
// console.log('----------------------');
// console.log(msg);
throw new ExpressError(msg, 400);
} else {
next();
}
}
const validateArticle = (req, res, next) => {
const articleSchema = Joi.object({
title: Joi.string().required(),
content: Joi.string().required(),
author: Joi.string(),
cover: Joi.string(),
}).required()
const { error } = articleSchema.validate(req.body);
if (error) {
const msg = error.details.map(el => el.message).join(',')
throw new ExpressError(msg, 400);
} else {
next();
}
}
const requireLogin = (req, res, next) => {
if (!req.session.user_id) {
res.render('/adopet/auth');
}
}
const isAuthor = async(req, res, next)=>{
const { id } = req.params;
const article = await Article.findById(id);
if(!article.author.equals(req.user._id)) {
req.flash('error', 'You do not have permission to do that!');
return res.redirect(`/adopet/articles/${id}`);
}
next();
}
const isDogOwner = async(req, res, next) =>{
const {id} = req.params;
const dog = await Dog.findById(id);
if(!dog.owner.equals(req.user._id)){
req.flash('error', 'You do not have permission to do that!');
return res.redirect(`/adopet/adopt/dogs/${id}`);
}
next();
}
const isCatOwner = async(req, res, next) =>{
const {id} = req.params;
const cat = await Cat.findById(id);
if(!cat.owner.equals(req.user._id)){
req.flash('error', 'You do not have permission to do that!');
return res.redirect(`/adopet/adopt/cats/${id}`);
}
next();
}
const isBirdOwner = async(req, res, next) =>{
const {id} = req.params;
const bird = await Bird.findById(id);
if(!bird.owner.equals(req.user._id)){
req.flash('error', 'You do not have permission to do that!');
return res.redirect(`/adopet/adopt/birds/${id}`);
}
next();
}
const isOtherOwner = async(req, res, next) =>{
const {id} = req.params;
const other = await Other.findById(id);
if(!other.owner.equals(req.user._id)){
req.flash('error', 'You do not have permission to do that!');
return res.redirect(`/adopet/adopt/others/${id}`);
}
next();
}
const isSmallandfurryOwner = async(req, res, next) =>{
const {id} = req.params;
const smallandfurry = await Smallandfurry.findById(id);
if(!smallandfurry.owner.equals(req.user._id)){
req.flash('error', 'You do not have permission to do that!');
return res.redirect(`/adopet/adopt/smallandfurries/${id}`);
}
next();
}
const isAdmin = (req, res, next) => {
if(req.user.role === 0){
req.flash('error', 'Access denied, you must be an admin to do that!');
return
}next();
}
// Exporting all middleware functions as an object
module.exports = {
isLoggedIn,
requireLogin,
validateUser,
validateArticle,
isAuthor,
storeReturnTo,
isAdmin,
isDogOwner,
isCatOwner,
isBirdOwner,
isOtherOwner,
isSmallandfurryOwner
};