-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
467 lines (361 loc) · 13.1 KB
/
app.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
const express =require("express");
const app=express();
const mongoose=require("mongoose");
const path=require("path");
const methodOverride=require("method-override");
const ejsMate=require("ejs-mate");
const ExpressError=require("./utils/ExpressError.js");
const wrapAsync=require("./utils/WrapAsync.js");
const session=require("express-session");
const MongoStore = require('connect-mongo');
const flash=require("connect-flash");
const {isLoggedIn}=require("./middleware.js");
const crypto = require('crypto');
const nodemailer = require('nodemailer');
const passport=require("passport");
const localStrategy=require("passport-local");
const USER=require("./models/user.js");
const PROJECT=require("./models/project.js");
const { error } = require("console");
const {saveRedirectUrl }=require("./middleware.js");
if(process.env.NODE_ENV !='production'){
require('dotenv').config()
}
const multer = require('multer');
const {storage}=require("./cloudConfig.js");
const upload = multer({ storage });
app.set("view engine","ejs");
app.set("views",path.join(__dirname,"/views"));
app.use(express.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.engine('ejs', ejsMate);
app.use(express.static(path.join(__dirname,"/public")));
const transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: process.env.GMAIL_USERNAME,
pass: process.env.GMAIL_PASS
}
});
let tokens = {};
const dbUrl=process.env.ATLASDB_URL;
const store=MongoStore.create({
mongoUrl: dbUrl,
crypto:{
secret:process.env.SECRET
},
touchAfter:24*3600,
});
store.on("error",()=>{
console.log("ERROR IN MONGO STORE",err);
});
const sessionOption={
store,
secret:process.env.SECRET,
resave:false,
saveUninitialized:true,
cookie:{
expires: Date.now() + 7 * 24 * 60 * 60 * 1000,
maxAge: 7 * 24 * 60 * 60 * 1000,
httpOnly:true,
}
};
main()
.then(()=>{
console.log("connected to db");
})
.catch((err)=>{
console.log(err);
})
async function main() {
await mongoose.connect(dbUrl);
}
app.listen(8080,()=>{
console.log("server is listening");
});
app.use(session(sessionOption));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrategy({ usernameField: 'name' },USER.authenticate()));
passport.serializeUser(USER.serializeUser());
passport.deserializeUser(USER.deserializeUser());
app.use((req,res,next)=>{
res.locals.success = req.flash("success");
// console.log(res.locals.success);
res.locals.error=req.flash("error");
res.locals.currUser=req.user;
next();
});
// app.get("/demoproject",async(req,res)=>{
// let fakeProject=new PROJECT({
// projectname: 'student',
// github_link: "John Doe",
// thumbnail:"[email protected]",
// });
// fakeProject.save();
// res.send(fakeProject);
// });
function isValidEmail(email) {
return email.endsWith('@lnmiit.ac.in');
};
function isValidPassword(password) {
const minLength = 8;
const uppercasePattern = /[A-Z]/;
const lowercasePattern = /[a-z]/;
const numberPattern = /[0-9]/;
const specialCharPattern = /[!@#$%^&*(),.?":{}|<>]/;
if (password.length < minLength) {
return false;
}
if (!uppercasePattern.test(password)) {
return false;
}
if (!lowercasePattern.test(password)) {
return false;
}
if (!numberPattern.test(password)) {
return false;
}
if (!specialCharPattern.test(password)) {
return false;
}
return true;
}
app.post("/signup", wrapAsync(async(req,res)=>{
try {
let { usertype,name,email,password,confirmPassword}=req.body;
// console.log(req.body);
const adminEmails = [
];
if (usertype === "admin" && !adminEmails.includes(email)) {
throw new Error("You are not authorized to register as an admin.");
}
// if (usertype === "student" && adminEmails.includes(email)) {
// throw new Error("Your Email has privilege to register as an admin Only , So Please select admin");
// }
// console.log(usertype);
// console.log(name);
// console.log(email);
// console.log(password);
// console.log(confirmPassword);
if(!isValidEmail(email))
{
throw new Error("Only institute emails ending with @lnmiit.ac.in are acceptable.");
}
if (!isValidPassword(password)) {
throw new Error("Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character.");
}
if(password!=confirmPassword)
{
throw new Error("Confirm password is not equal to password entered above");
}
const existingUser = await USER.findOne({ email: email, usertype: usertype });
if (existingUser) {
throw new Error("This Usertype and Email is already Registered ,Please Log in to continue");
}
const newUser=new USER({
usertype:usertype,
name:name,
email:email,
});
let registeredUser=await USER.register(newUser,password);
// console.log(registeredUser);
const token = crypto.randomBytes(32).toString('hex');
tokens[email] = { token, password, expires: Date.now() + 3600000 };
const link = `${process.env.BASE_URL}/verify?email=${encodeURIComponent(email)}&token=${token}`;
const mailOptions = {
from: process.env.GMAIL_USERNAME,
to: email,
subject: 'Complete your registration',
text: `Please click the following link to complete your registration: ${link}`
};
await transporter.sendMail(mailOptions);
req.flash("success", "A confirmation email has been sent to your email address.");
res.redirect("/signup");
// else{
// req.flash("success","Confirm Password hogayaaaa");
// res.redirect("/login");
// }
} catch (err) {
req.flash("error",err.message);
res.redirect("/signup");
}
}));
app.get("/verify", (req, res) => {
const { email, token } = req.query;
if (tokens[email] && tokens[email].token === token && tokens[email].expires > Date.now()) {
const { password } = tokens[email];
delete tokens[email];
req.flash("success", "Your registration is complete. Please log in.");
res.redirect("/login");
} else {
req.flash("error", "Invalid or expired token.");
res.redirect("/signup");
}
});
app.get("/signup",(req,res)=>{
res.render("pages/signup.ejs");
});
app.get("/login",(req,res)=>{
res.render("pages/login.ejs");
});
app.post("/login",saveRedirectUrl,passport.authenticate("local",{ failureRedirect:'/login',failureFlash:true}),(req,res)=>{
try{
let { name ,password}=req.body;
// console.log(req.body);
// console.log(email);
// console.log(password);
// if(!isValidEmail(email))
// {
// throw new Error("Only institute emails ending with @lnmiit.ac.in are acceptable.");
// }
if (!isValidPassword(password)) {
throw new Error("Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character.");
}
req.flash("success","User Logged in Successfully");
// res.render("pages/dashboard.ejs");
let redirectUrl=res.locals.redirectUrl || "/dashboard";
res.redirect(redirectUrl);
}catch(err){
req.flash("error",err.message);
res.redirect("/login");
}
});
app.get("/dashboard/new",isLoggedIn,(req,res)=>{
res.render("pages/newproject.ejs");
});
app.post("/dashboard/new",upload.single('thumbnail'),(req,res)=>{
// let url=req.file.path;
// let filename=req.file.filename;
// console.log(url);
// console.log(filename);
let {projectname,github_link,live_link,tech_stack}=req.body;
let newProject=new PROJECT({projectname,github_link,live_link,tech_stack,owner:req.user._id});
if(typeof req.file!=="undefined"){
let url=req.file.path;
let filename=req.file.filename;
// console.log(url);
// console.log(filename);
newProject.thumbnail={url,filename};
}else{
let url="https://images.unsplash.com/photo-1610513320995-1ad4bbf25e55?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D";
let filename="no image";
newProject.thumbnail={url,filename};
}
newProject.save();
// res.send(newProject);
res.redirect("/dashboard");
});
app.get("/dashboard",wrapAsync(async (req,res)=>{
//console.log(currUser);
// console.log(req.user);
if(typeof req.user!=="undefined")
{
if(req.user.usertype==='student')
{
let id=req.user._id;
const projects=await PROJECT.find({owner:id}).populate("owner");
res.render("pages/dashboard.ejs",{projects});
}
else{
const projects=await PROJECT.find({}).populate("owner");
res.render("pages/dashboard.ejs",{projects});
}
}
else{
res.render("pages/home.ejs");
}
}));
app.delete("/dashboard/admin/user/:id",isLoggedIn,wrapAsync(async (req,res)=>{
let {id}=req.params;
if(req.user.usertype==='student'){
req.flash("error"," You don't have permission to DELETE");
return res.redirect(`/dashboard/${id}`);
}
const removeUser=await USER.findByIdAndDelete(`${id}`);
// console.log(removeUser);
req.flash("success","User Deleted");
res.redirect('/dashboard');
}));
app.get("/dashboard/:id",isLoggedIn,wrapAsync(async (req,res)=>{
let {id}=req.params;
const project=await PROJECT.findById(`${id}`).populate("owner");
if((!project.owner._id.equals(res.locals.currUser._id))&&(req.user.usertype==='student')){
req.flash("error"," You don't have permission to edit");
return res.redirect(`/dashboard/${id}`);
}
// console.log(project);
if(!project){
req.flash("error","Project Details you requested does not exist!");
return res.redirect("/dashboard");
}
res.render("pages/show.ejs",{project});
}));
app.get("/dashboard/:id/edit",isLoggedIn,wrapAsync(async (req,res)=>{
let {id}=req.params;
const project=await PROJECT.findById(`${id}`);
if(!project){
req.flash("error","Project you requested does not exist!");
res.redirect("/dashboard");
}
res.render("pages/edit.ejs",{project});
}));
app.put("/dashboard/:id/edit",isLoggedIn,upload.single('thumbnail'),wrapAsync(async (req,res)=>{
let {id}=req.params;
// console.log(req.body);
const project=await PROJECT.findById(`${id}`);
if((!project.owner._id.equals(res.locals.currUser._id))&&(req.user.usertype==='student')){
req.flash("error"," You don't have permission to edit");
return res.redirect(`/dashboard/${id}`);
}
let updateProject=await PROJECT.findByIdAndUpdate(`${id}`,req.body);
if(typeof req.file!=="undefined"){
let url=req.file.path;
let filename=req.file.filename;
// console.log(url);
// console.log(filename);
updateProject.thumbnail={url,filename};
await updateProject.save();
}
req.flash("success"," Project Details Updated");
res.redirect(`/dashboard/${id}`);
}));
app.delete("/dashboard/:id",isLoggedIn,wrapAsync(async (req,res)=>{
let {id}=req.params;
const project=await PROJECT.findById(`${id}`);
if((!project.owner._id.equals(res.locals.currUser._id))&&(req.user.usertype==='student')){
req.flash("error"," You don't have permission to DELETE");
return res.redirect(`/dashboard/${id}`);
}
let delproject=await PROJECT.findByIdAndDelete(`${id}`);
// console.log(delproject);
req.flash("success","Project Deleted");
res.redirect('/dashboard');
}));
app.get("/logout",(req,res,next)=>{
req.logout((err)=>{
if(err){
return next(err);
}
else{
req.flash("success","Logged-Out Successfully");
res.redirect('/dashboard');
}
})
});
app.all("*",(req,res,next)=>{
next(new ExpressError(404,"Page nahi mila"));
});
app.use((err,req,res,next)=>{
let {statusCode=500,message='Kuchh Galat Hogayaaa....'}=err;
// console.log(statusCode,message);
res.status(statusCode);
res.render("error.ejs",{err});
});