-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathadmin.js
314 lines (261 loc) · 8.3 KB
/
admin.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
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
const User = require('../models/User');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const passport = require('passport'); // Added passport import
const { validateRegistration, validatePost } = require('../validations/authValidator');
const adminLayout = '../views/layouts/admin';
const jwtSecret = process.env.JWT_SECRET;
const multer = require('multer');
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const storage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'post',
format: async (req, file) => 'jpeg', // Supports promises as well
public_id: (req, file) =>
Date.now() +
'-' +
file.originalname.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 100),
},
});
const upload = multer({ storage });
/**
* Check whether the user is signed in or not
* and makes the /admin route available only those users who are NOT logged
*/
const restrictAuthRouteMiddleware = (req, res, next) => {
const token = req.cookies.token;
if (!token) return next();
return res.status(200).redirect('/')
}
/**
* Authentication Middleware
*/
const authMiddleware = (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}
try {
const decoded = jwt.verify(token, jwtSecret);
req.userId = decoded.userId;
next();
} catch (error) {
res.status(401).json({ message: 'Unauthorized' });
}
};
/**
* GET /
* Admin - Login Page
*/
router.use((req, res, next) => {
res.locals.layout = './layouts/admin'; // Set the layout for the response
next(); // Call the next middleware or route handler
});
router.get('/admin', restrictAuthRouteMiddleware, async (req, res) => {
try {
const locals = {
title: 'Admin',
description: 'Simple Blog created with NodeJs, Express & MongoDb.',
};
res.render('admin/index', { locals, layout: adminLayout });
} catch (error) {
console.log(error);
}
});
/**
* POST /admin
* Admin Login Route with Passport Authentication
*/
router.post('/admin', async (req, res, next) => {
passport.authenticate('local', async (err, user, info) => {
if (err) {
return res.status(500).json({ message: 'Internal server error' });
}
if (!user) {
return res.status(401).json({ message: 'Unauthorized' });
}
req.logIn(user, async (err) => {
if (err) {
return res.status(500).json({ message: 'Error logging in' });
}
const token = jwt.sign({ userId: user._id }, jwtSecret, { expiresIn: '1h' });
res.cookie('token', token, { httpOnly: true });
return res.redirect('/dashboard'); // Now redirect to dashboard
});
})(req, res, next);
});
/**
* GET /dashboard
* Admin Dashboard Route
*/
router.get('/dashboard', authMiddleware, async (req, res) => {
const locals = {
title: 'Dashboard',
user: req.cookies.token,
description: 'Simple Blog created with NodeJs, Express & MongoDb.',
};
const posts = await Post.find(); // Fetch all posts
res.render('admin/dashboard', { locals, posts }); // Pass 'posts' to the template
});
/**
* GET /add-post
* Admin Add Post Route
*/
router.get('/add-post', authMiddleware, async (req, res) => {
const token = req.cookies.token;
try {
const locals = {
title: 'Add Post',
user: token,
description: 'Simple Blog created with NodeJs, Express & MongoDb.',
};
res.render('admin/add-post', {locals, layout: adminLayout });
} catch (error) {
console.log(error);
}
});
/**
* POST /add-post
* Admin Create New Post Route
*/
router.post('/add-post', upload.single('poster'), authMiddleware, validatePost, async (req, res) => {
try {
const token = req.cookies.token
const newPost = new Post({
title: req.body.title,
user: token,
body: req.body.body,
author: req.body.author,
poster: req.file ? await cloudinary.uploader.upload(req.file.path).then(r => r.secure_url) : null
});
await Post.create(newPost);
res.redirect('/dashboard');
} catch (error) {
console.log(error);
}
});
/**
* GET /edit-post/:id
* Admin Edit Post Route
*/
router.get('/edit-post/:id', authMiddleware, async (req, res) => {
try {
const locals = {
title: 'Edit Post',
user : req.cookies.token,
description: 'Free NodeJs User Management System',
};
const data = await Post.findOne({ _id: req.params.id });
res.render('admin/edit-post', { locals, data, layout: adminLayout });
} catch (error) {
console.log(error);
}
});
/**
* PUT /edit-post/:id
* Admin Update Post Route
*/
router.put('/edit-post/:id', upload.single('poster'), authMiddleware, validatePost, async (req, res) => {
try {
await Post.findByIdAndUpdate(req.params.id, {
title: req.body.title,
body: req.body.body,
author: req.body.author,
...(req.file ? { poster: await cloudinary.uploader.upload(req.file.path).then(r => r.secure_url) } : {}),
updatedAt: Date.now(),
});
res.redirect(`/edit-post/${req.params.id}`);
} catch (error) {
console.log(error);
}
});
/**
* DELETE /delete-post/:id
* Admin Delete Post Route
*/
router.delete('/delete-post/:id', authMiddleware, async (req, res) => {
try {
await Post.deleteOne({ _id: req.params.id });
res.redirect('/dashboard');
} catch (error) {
console.log(error);
}
});
/**
* POST /register
* Admin Registration Route
*/
/**
* GET /register
* Admin - Registration Page
*/
// Example of admin.js route handling
router.get('/register',restrictAuthRouteMiddleware, (req, res) => {
// Initialize messages object, you can adjust it according to your error handling logic
const locals = {
title: 'Admin',
description: 'Simple Blog created with NodeJs, Express & MongoDb.',
};
res.render('admin/register', { locals, layout: adminLayout }); // Pass messages to the template
});
router.post('/register',validateRegistration, async (req, res) => {
const { username, password } = req.body;
// Simple validation
if (!username || !password) {
req.flash('error', 'All fields are required');
return res.redirect('/register'); // Change to '/register'
}
if (!/^[a-zA-Z0-9]+$/.test(username) || username.length < 3) {
req.flash('error', 'Username must be at least 3 characters long and contain only alphanumeric characters.');
return res.redirect('/register');
}
if (password.length < 8 || !/\d/.test(password) || !/[!@#$%^&*]/.test(password)) {
req.flash('error', 'Password must be at least 8 characters long, contain a number, and a special character.');
return res.redirect('/register');
}
try {
const existingUser = await User.findOne({ username });
if (existingUser) {
req.flash('error', 'Username already taken');
return res.redirect('/register'); // Change to '/register'
}
// Hash password and create new user
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, password: hashedPassword });
await user.save();
// Automatically log the user in
req.login(user, (err) => {
if (err) return res.status(500).json({ message: 'Error logging in after registration' });
const token = jwt.sign({ userId: user._id }, jwtSecret, { expiresIn: '1h' });
res.cookie('token', token, { httpOnly: true });
return res.redirect('/dashboard');
});
} catch (error) {
console.log(error);
res.status(500).json({ message: 'Internal server error' });
}
});
/**
* GET /logout
* Admin Logout Route
*/
router.get('/logout', (req, res) => {
req.logout((err) => {
if (err) {
return next(err);
}
res.clearCookie('token');
res.redirect('/');
});
});
module.exports = router;