Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
404 lines (347 loc) · 11.7 KB
/
Copy pathapp.js
File metadata and controls
404 lines (347 loc) · 11.7 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
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
require("dotenv").config();
const express = require("express");
const ejs = require("ejs");
const mongoose = require("mongoose")
const bodyParser = require("body-parser");
const _ = require("lodash");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const MongoStore = require("connect-mongo")(session);
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require("mongoose-findorcreate");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static(__dirname + "/public"));
app.use(session({
secret: "This is my little secret",
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection, ttl: 90*24*60*60})
}))
app.use(passport.initialize());
app.use(passport.session());
//mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser:true, useUnifiedTopology:true, useFindAndModify: false});
mongoose.connect(`mongodb+srv://admin-genesis:${process.env.DB_PASSWORD}@cluster0.vnfjt.mongodb.net/todolistDB`, {useNewUrlParser:true, useUnifiedTopology:true, useFindAndModify: false});
mongoose.set("useCreateIndex", true);
const options = {month: "long", day: "numeric"}
const day = new Date().toLocaleDateString("en-US", options)
const images = 23;
let port = process.env.PORT;
const itemsSchema = new mongoose.Schema({
name: String
});
const listsSchema = new mongoose.Schema({
name: String,
items: [itemsSchema],
bgimg: Number
});
const usersSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
lists: [listsSchema],
googleId: String
});
usersSchema.plugin(passportLocalMongoose, {usernameField: "email"});
usersSchema.plugin(findOrCreate);
const Item = mongoose.model("Item", itemsSchema);
const List = mongoose.model("List", listsSchema);
const User = mongoose.model("User", usersSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "https://damp-ocean-76119.herokuapp.com/auth/google/todolist",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
User.findOrCreate({ googleId: profile.id, name: profile.name.givenName}, function (err, user) {
return cb(err, user);
});
}
));
/* --------------- Inicial List ------------------------- */
const item1 = new Item({
name: "Welcome to your To Do list!"
});
const item2 = new Item({
name: "Hit the top plus button to add a list"
});
const item3 = new Item({
name: "And the trash can button to remove a list"
});
const item4 = new Item({
name: "<-- Here to remove an item"
});
const item5 = new Item({
name: "Enjoy 😀"
});
const defaultItems = [item1, item2, item3, item4, item5];
const inicialList = new List({
_id: mongoose.Types.ObjectId("000000000000000000000000"),
name: day,
items: defaultItems,
bgimg: 1
});
/* --------------- Inicial List ------------------------- */
app.get("/", function(req, res){
if(req.isAuthenticated()){
res.redirect("/user/login/" + req.user._id);
}else{
res.render("home")
}
})
app.get("/login", function(req, res){
res.render("login")
})
app.get("/register", function(req, res){
res.render("register")
})
//Login user
app.post("/login", function(req, res){
const email = req.body.email;
const password = req.body.password;
const user = new User({
email: email,
password: password
})
req.login(user, function(err){
if(!err){
passport.authenticate("local")(req, res, function(){
res.redirect("/user/login/" + req.user._id);
})
}else{
console.log(err);
res.redirect("/");
}
})
})
//Register User
app.post("/register", function(req, res){
const name = _.capitalize(req.body.name);
const email = req.body.email;
const password = req.body.password;
User.register({name: name, email: email, lists: inicialList}, password, function(err, user){
if(!err){
passport.authenticate("local")(req, res, function(){
res.redirect("/user/register/" + user._id);
})
}else{
console.log(err)
res.redirect("/register");
}
})
})
//Register with Google //////
app.get("/auth/google", passport.authenticate("google", {scope: ["profile"]}));
app.get("/auth/google/todolist", passport.authenticate("google" , {failureRedirect: "/login"}),
function(req, res){
User.findById(req.user._id, function(err, foundUserList){
if(foundUserList.lists.length > 0){
res.redirect("/user/login/" + req.user._id);
}else{
User.findByIdAndUpdate(req.user._id, {$push: {lists: inicialList}},
function(err, foundUser){
if(!err){
res.redirect("/user/login/" + req.user._id);
}else{
console.log(err)
}
});
}
})
});
//Load default items for registered user
app.get("/user/register/:userId", function(req, res){
const userId = req.params.userId;
if(req.isAuthenticated() && (JSON.stringify(req.user._id) === `"${userId}"`)){
User.findById(userId, function(err, foundUser){
if(!err){
res.render("list", {
name: foundUser.name,
userId : foundUser._id,
listTitle : day,
items: foundUser.lists[0].items,
lists: foundUser.lists,
listId : foundUser.lists[0]._id,
bgimg : 1
});
}else{
console.log(err);
}
})
}else{
res.redirect("/")
}
})
//Load items for logim user
app.get("/user/login/:userId", function(req, res){
const userId = req.params.userId;
if(req.isAuthenticated() && (JSON.stringify(req.user._id) === `"${userId}"`)){
User.findById(userId, function(err, foundUser){
if(!err){
if(foundUser.lists[0].items === undefined){
foundUser.lists[0].items = [];
res.render("list", {
name: foundUser.name,
userId : foundUser._id,
listTitle : day,
items: foundUser.lists[0].items,
lists: foundUser.lists,
listId : foundUser.lists[0]._id,
bgimg : 1
})
}else{
res.render("list", {
name: foundUser.name,
userId : foundUser._id,
listTitle : day,
items: foundUser.lists[0].items,
lists: foundUser.lists,
listId : foundUser.lists[0]._id,
bgimg : 1
})
}
}else{
console.log(err)
}
})
}else{
res.redirect("/")
}
})
//Add new Item
app.post("/addItem", function(req, res){
if(req.isAuthenticated()){
const item = req.body.newItem;
const listId = req.body.listIdAddBtn;
const userId = req.body.userIdAddBtn;
User.findOneAndUpdate({_id: userId, "lists._id": listId}, {$push: {"lists.$.items": {name: item}}}, function(err, foundUser){
if(!err){
res.redirect(`/user/${userId}/lists/${listId}`)
}else{
console.log(err)
}
})
}else{
res.redirect("/")
}
})
//Delete item
app.post("/deleteItem", function(req, res){
if(req.isAuthenticated()){
const idItem = req.body.checkbox;
const listId = req.body.listIdDeleteItem;
const userId = req.body.userIdDeleteItem;
User.findOneAndUpdate({_id: userId, "lists._id": listId}, {$pull: {"lists.$.items": {_id: idItem}}}, function(err, foundUser){
if(!err){
res.redirect(`/user/${userId}/lists/${listId}`)
}else{
console.log(err);
}
})
}else{
res.redirect("/")
}
})
//Create new custom List
app.post("/addList", function(req, res){
if(req.isAuthenticated()){
const newList = req.body.addNewList;
const userId = req.body.userIdAddList;
const bgimgaux = Math.ceil(Math.random()*images);
User.findByIdAndUpdate(userId, {$push: {lists: {name: newList, bgimg: bgimgaux}}}, function(err, foundUser){
if(!err){
console.log("Succesfully added new list!")
}else{
console.log(err)
}
})
User.findById(userId, function(err, foundUser){
if(!err){
const listId = foundUser.lists[foundUser.lists.length -1]._id;
res.redirect(`/user/${userId}/lists/${listId}`)
}else{
console.log(err)
}
})
}else{
res.redirect("/")
}
})
//Access custom list
app.get("/user/:userId/lists/:listId", function(req, res){
if(req.isAuthenticated()){
const userId = req.params.userId;
const listId = req.params.listId;
User.findById(userId, function(err, foundUser){
if(!err){
User.findById(userId, {lists: {$elemMatch: {_id: listId}}}, function(err, foundUserList){
if(!err){
res.render("list", {
name: foundUser.name,
userId : foundUserList._id,
listTitle : foundUserList.lists[0].name,
items: foundUserList.lists[0].items,
lists: foundUser.lists,
listId : foundUserList.lists[0]._id,
bgimg : foundUserList.lists[0].bgimg
});
}else{
console.log(err);
}
})
}else{
console.log(err);
}
})
}else{
res.redirect("/")
}
})
//Delete List
app.post("/deleteList", function(req, res){
if(req.isAuthenticated()){
const userId = req.body.userIdDeleteList;
const listId = req.body.deleteListBtn;
if(listId === "000000000000000000000000"){
console.log("You can not delete main list!");
res.redirect("/user/login/" + userId);
}else{
User.findByIdAndUpdate(userId, {$pull: {lists: {_id: listId}}}, function(err, foundUser){
if(!err){
console.log("Succesfully deleted list!");
res.redirect("/user/login/" + foundUser._id);
}else{
console.log(err)
}
})
}
}else{
res.redirect("/");
}
})
//Logout user
app.post("/logout", function(req, res){
req.logout();
req.session.destroy(function(err){
if(err){
console.log(err);
}
})
res.redirect("/")
})
if (port == null || port == "") {
port = 8000;
}
app.listen(port, () => console.log(`Server open on port ${port}`));