From b8ff753a92adf8953cbbe49b0cbe8778df1e849f Mon Sep 17 00:00:00 2001 From: Egle Libby Date: Mon, 17 Apr 2017 12:47:18 -0400 Subject: [PATCH 01/13] basic setup, start sessions routing --- .gitignore | 1 + app.js | 133 ++++++++++++++++++++++++++++++++++ package.json | 32 ++++++++ repl.js | 13 ++++ routers/sessions.js | 37 ++++++++++ routers/users.js | 5 ++ views/layouts/main.handlebars | 39 ++++++++++ views/sessions/new.handlebars | 18 +++++ views/shared/_nav.handlebars | 31 ++++++++ 9 files changed, 309 insertions(+) create mode 100644 .gitignore create mode 100644 app.js create mode 100644 package.json create mode 100644 repl.js create mode 100644 routers/sessions.js create mode 100644 routers/users.js create mode 100644 views/layouts/main.handlebars create mode 100644 views/sessions/new.handlebars create mode 100644 views/shared/_nav.handlebars diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..30bc162 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/node_modules \ No newline at end of file diff --git a/app.js b/app.js new file mode 100644 index 0000000..f1bcd3e --- /dev/null +++ b/app.js @@ -0,0 +1,133 @@ +var express = require("express"); +var app = express(); + +// ---------------------------------------- +// Body Parser +// ---------------------------------------- +var bodyParser = require("body-parser"); +app.use(bodyParser.urlencoded({ extended: true })); + +// ---------------------------------------- +// Sessions/Cookies +// ---------------------------------------- +var cookieSession = require("cookie-session"); + +app.use( + cookieSession({ + name: "session", + keys: ["asdf1234567890qwer"] + }) +); + +app.use((req, res, next) => { + res.locals.session = req.session; + res.locals.currentUser = req.session.currentUser; + next(); +}); + +// ---------------------------------------- +// Method Override +// ---------------------------------------- +app.use((req, res, next) => { + var method; + if (req.query._method) { + method = req.query._method; + delete req.query._method; + for (let key in req.query) { + req.body[key] = decodeURIComponent(req.query[key]); + } + } else if (typeof req.body === "object" && req.body._method) { + method = req.body._method; + delete req.body._method; + } + + if (method) { + method = method.toUpperCase(); + req.method = method; + } + + next(); +}); + +// ---------------------------------------- +// Referrer +// ---------------------------------------- +app.use((req, res, next) => { + req.session.backUrl = req.header("Referer") || "/"; + next(); +}); + +// ---------------------------------------- +// Public +// ---------------------------------------- +app.use(express.static(`${__dirname}/public`)); + +// ---------------------------------------- +// Logging +// ---------------------------------------- +var morgan = require("morgan"); +app.use(morgan("tiny")); +app.use((req, res, next) => { + ["query", "params", "body"].forEach(key => { + if (req[key]) { + var capKey = key[0].toUpperCase() + key.substr(1); + var value = JSON.stringify(req[key], null, 2); + console.log(`${capKey}: ${value}`); + } + }); + next(); +}); + +// ---------------------------------------- +// Mongoose +// ---------------------------------------- +var mongoose = require("mongoose"); +app.use((req, res, next) => { + if (mongoose.connection.readyState) { + next(); + } else { + require("./mongo")(req).then(() => next()); + } +}); + +// ---------------------------------------- +// Routes +// ---------------------------------------- +var sessionsRouter = require("./routers/sessions")(app); +app.use("/", sessionsRouter); + +// var usersRouter = require('./routers/users'); +// app.use('/users', usersRouter); + +// var ratablesRouter = require('./routers/ratables'); +// app.use('/ratables', ratablesRouter); + +// ---------------------------------------- +// Template Engine +// ---------------------------------------- +var expressHandlebars = require("express-handlebars"); + +var hbs = expressHandlebars.create({ + partialsDir: "views/", + defaultLayout: "main" +}); + +app.engine("handlebars", hbs.engine); +app.set("view engine", "handlebars"); + +// ---------------------------------------- +// Server +// ---------------------------------------- +var port = process.env.PORT || process.argv[2] || 3000; +var host = "localhost"; + +var args; +process.env.NODE_ENV === "production" ? (args = [port]) : (args = [port, host]); + +args.push(() => { + console.log(`Listening: http://${host}:${port}`); +}); + +app.listen.apply(app, args); + +module.exports = app; diff --git a/package.json b/package.json new file mode 100644 index 0000000..1149e6b --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "assignment_thorredit", + "version": "1.0.0", + "description": "A social news web application for Viking thunder Gods", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "nodemon app.js", + "c": "node repl.js", + "seed": "node seeds", + "seeds": "node seeds" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eglital/assignment_thorredit.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/eglital/assignment_thorredit/issues" + }, + "homepage": "https://github.com/eglital/assignment_thorredit#readme", + "dependencies": { + "bluebird": "^3.5.0", + "body-parser": "^1.17.1", + "cookie-session": "^2.0.0-beta.1", + "express": "^4.15.2", + "express-handlebars": "^3.0.0", + "mongoose": "^4.9.5", + "morgan": "^1.8.1" + } +} diff --git a/repl.js b/repl.js new file mode 100644 index 0000000..f3e3c51 --- /dev/null +++ b/repl.js @@ -0,0 +1,13 @@ +var mongoose = require("mongoose"); +var repl = require("repl").start({}); +var models = require("./models"); + +require("./mongo")().then(() => { + repl.context.models = models; + + Object.keys(models).forEach(modelName => { + repl.context[modelName] = mongoose.model(modelName); + }); + + repl.context.lg = data => console.log(data); +}); diff --git a/routers/sessions.js b/routers/sessions.js new file mode 100644 index 0000000..6414997 --- /dev/null +++ b/routers/sessions.js @@ -0,0 +1,37 @@ +var url = require("url"); +var express = require("express"); +var router = express.Router(); +var mongoose = require("mongoose"); +// var models = require('./../models'); +// var User = mongoose.model('User'); + +app.get("/", function(req, res) { + // invoked when localhost:3000 is visited + if (req.session.visited) { + // to send user to logged page if already signed in on different browser tab, per the specification + res.send("Hello Theoreddit!"); + } else { + res.render("sessions/new"); + } +}); + +app.get("/logged", (req, res) => { + if (req.session.visited) { + // to prevent unauthorized direct access to the 'logged' private page + res.render("logged"); + } else { + res.redirect("/"); + } +}); + +app.post("/login", (req, res) => { + // invoked when '/login' action called on index.hbs page + req.session.visited = true; + res.redirect("/logged"); +}); + +app.post("/logout", (req, res) => { + // invoked when '/logout' action called on logged.hbs page + req.session.destroy(); // to prevent unauthorized direct access to the 'logged' private page + res.redirect("/"); +}); diff --git a/routers/users.js b/routers/users.js new file mode 100644 index 0000000..fd35b24 --- /dev/null +++ b/routers/users.js @@ -0,0 +1,5 @@ +var express = require("express"); +var router = express.Router(); +var mongoose = require("mongoose"); +// var models = require('./../models'); +// var User = mongoose.model('User'); diff --git a/views/layouts/main.handlebars b/views/layouts/main.handlebars new file mode 100644 index 0000000..e559eb5 --- /dev/null +++ b/views/layouts/main.handlebars @@ -0,0 +1,39 @@ + + + + + + + + Thoreddit + {{#if title }} + | {{ title }} + {{/if }} + + + + + + + + + + + + + + + + + + + {{> shared/_nav }} +
+ {{{ body }}} +
+ + + + diff --git a/views/sessions/new.handlebars b/views/sessions/new.handlebars new file mode 100644 index 0000000..9b295e7 --- /dev/null +++ b/views/sessions/new.handlebars @@ -0,0 +1,18 @@ + + + +
+
+ + +
+
+ + +
+
+ +
+
diff --git a/views/shared/_nav.handlebars b/views/shared/_nav.handlebars new file mode 100644 index 0000000..a64070b --- /dev/null +++ b/views/shared/_nav.handlebars @@ -0,0 +1,31 @@ + \ No newline at end of file From 1957d6a390d2cebedd4ce608719ee26aa8476b34 Mon Sep 17 00:00:00 2001 From: deven1 Date: Mon, 17 Apr 2017 13:12:11 -0400 Subject: [PATCH 02/13] completed login page --- app.js | 18 ++++++------- routers/sessions.js | 27 +++++++++++-------- .../{new.handlebars => login.handlebars} | 4 +-- 3 files changed, 27 insertions(+), 22 deletions(-) rename views/sessions/{new.handlebars => login.handlebars} (77%) diff --git a/app.js b/app.js index f1bcd3e..3af74d8 100644 --- a/app.js +++ b/app.js @@ -81,19 +81,19 @@ app.use((req, res, next) => { // ---------------------------------------- // Mongoose // ---------------------------------------- -var mongoose = require("mongoose"); -app.use((req, res, next) => { - if (mongoose.connection.readyState) { - next(); - } else { - require("./mongo")(req).then(() => next()); - } -}); +// var mongoose = require("mongoose"); +// app.use((req, res, next) => { +// if (mongoose.connection.readyState) { +// next(); +// } else { +// require("./mongo")(req).then(() => next()); +// } +// }); // ---------------------------------------- // Routes // ---------------------------------------- -var sessionsRouter = require("./routers/sessions")(app); +var sessionsRouter = require("./routers/sessions"); app.use("/", sessionsRouter); // var usersRouter = require('./routers/users'); diff --git a/routers/sessions.js b/routers/sessions.js index 6414997..b946a9d 100644 --- a/routers/sessions.js +++ b/routers/sessions.js @@ -5,33 +5,38 @@ var mongoose = require("mongoose"); // var models = require('./../models'); // var User = mongoose.model('User'); -app.get("/", function(req, res) { +//var app = express(); + +router.get("/", function(req, res) { // invoked when localhost:3000 is visited - if (req.session.visited) { + if (req.session.currentUser) { // to send user to logged page if already signed in on different browser tab, per the specification res.send("Hello Theoreddit!"); } else { - res.render("sessions/new"); + res.redirect("/login"); } }); -app.get("/logged", (req, res) => { - if (req.session.visited) { +router.get("/login", (req, res) => { + if (req.session.currentUser) { // to prevent unauthorized direct access to the 'logged' private page - res.render("logged"); - } else { res.redirect("/"); + } else { + res.render("sessions/login"); } }); -app.post("/login", (req, res) => { +router.post("/login", (req, res) => { // invoked when '/login' action called on index.hbs page - req.session.visited = true; - res.redirect("/logged"); + //req.session.visited = true; + req.session.currentUser = { name: req.body.username, email: req.body.email }; + res.redirect("/"); }); -app.post("/logout", (req, res) => { +router.post("/logout", (req, res) => { // invoked when '/logout' action called on logged.hbs page req.session.destroy(); // to prevent unauthorized direct access to the 'logged' private page res.redirect("/"); }); + +module.exports = router; diff --git a/views/sessions/new.handlebars b/views/sessions/login.handlebars similarity index 77% rename from views/sessions/new.handlebars rename to views/sessions/login.handlebars index 9b295e7..1d0af1e 100644 --- a/views/sessions/new.handlebars +++ b/views/sessions/login.handlebars @@ -3,14 +3,14 @@

Login

-
+
- +
From c663b0477c0ca2025cd1dae3b9dd35239fff065f Mon Sep 17 00:00:00 2001 From: Egle Libby Date: Mon, 17 Apr 2017 13:41:28 -0400 Subject: [PATCH 03/13] created seeds --- config/mongo.json | 13 +++++ models/index.js | 14 +++++ models/user.js | 37 +++++++++++++ mongo.js | 10 ++++ seeds/clean.js | 16 ++++++ seeds/index.js | 19 +++++++ seeds/seeds.js | 104 +++++++++++++++++++++++++++++++++++ views/users/index.handlebars | 59 ++++++++++++++++++++ 8 files changed, 272 insertions(+) create mode 100644 config/mongo.json create mode 100644 models/index.js create mode 100644 models/user.js create mode 100644 mongo.js create mode 100644 seeds/clean.js create mode 100644 seeds/index.js create mode 100644 seeds/seeds.js create mode 100644 views/users/index.handlebars diff --git a/config/mongo.json b/config/mongo.json new file mode 100644 index 0000000..6231649 --- /dev/null +++ b/config/mongo.json @@ -0,0 +1,13 @@ +{ + "development": { + "database": "thoreddit_development", + "host": "localhost" + }, + "test": { + "database": "thoreddit_test", + "host": "localhost" + }, + "production": { + "use_env_variable": "MONGODB_URI" + } +} \ No newline at end of file diff --git a/models/index.js b/models/index.js new file mode 100644 index 0000000..a4e2137 --- /dev/null +++ b/models/index.js @@ -0,0 +1,14 @@ +var mongoose = require("mongoose"); +var bluebird = require("bluebird"); + +// Set bluebird as the promise +// library for mongoose +mongoose.Promise = bluebird; + +var models = {}; + +// Load models and attach to models here +models.User = require("./user"); +//... more models + +module.exports = models; diff --git a/models/user.js b/models/user.js new file mode 100644 index 0000000..eee0235 --- /dev/null +++ b/models/user.js @@ -0,0 +1,37 @@ +var mongoose = require("mongoose"); +var Schema = mongoose.Schema; + +var UserSchema = new Schema( + { + fname: String, + lname: String, + username: String, + email: String + }, + { + timestamps: true + } +); + +// UserSchema.methods.name = function() { +// return `${ this.fname } ${ this.lname }`; +// }; + +// UserSchema.statics.findByFirstName = function (fname) { +// return User.find({ fname: fname }); +// }; + +// UserSchema.virtual('fullname').set(function(name) { +// console.log('Setting the name of the user'); +// name = name.toString(); +// var splat = name.split(' '); +// var fname = splat[0] || this.fname; +// var lname = splat[1] || this.lname; +// this.fname = fname; +// this.lname = lname; +// return this.name; +// }); + +var User = mongoose.model("User", UserSchema); + +module.exports = User; diff --git a/mongo.js b/mongo.js new file mode 100644 index 0000000..65e7e96 --- /dev/null +++ b/mongo.js @@ -0,0 +1,10 @@ +var mongoose = require("mongoose"); +var env = process.env.NODE_ENV || "development"; +var config = require("./config/mongo")[env]; + +module.exports = () => { + var envUrl = process.env[config.use_env_variable]; + var localUrl = `mongodb://${config.host}/${config.database}`; + var mongoUrl = envUrl ? envUrl : localUrl; + return mongoose.connect(mongoUrl); +}; diff --git a/seeds/clean.js b/seeds/clean.js new file mode 100644 index 0000000..28565fb --- /dev/null +++ b/seeds/clean.js @@ -0,0 +1,16 @@ +var mongoose = require("mongoose"); + +module.exports = () => { + var collections = mongoose.connection.collections; + + var collectionKeys = Object.keys(collections); + + var promises = []; + + collectionKeys.forEach(key => { + var promise = collections[key].remove(); + promises.push(promise); + }); + + return Promise.all(promises); +}; diff --git a/seeds/index.js b/seeds/index.js new file mode 100644 index 0000000..22f19d4 --- /dev/null +++ b/seeds/index.js @@ -0,0 +1,19 @@ +var mongoose = require("mongoose"); +var models = require("./../models"); + +Object.keys(models).forEach(modelName => { + global[modelName] = mongoose.model(modelName); +}); + +require("./../mongo")() + .then(() => console.log("Cleaning Database...")) + .then(() => { + return require("./clean")(); + }) + .then(() => console.log("Seeding...")) + .then(() => { + return require("./seeds")(); + }) + .then(() => console.log("Done")) + .catch(e => console.error(e)) + .then(() => mongoose.disconnect()); diff --git a/seeds/seeds.js b/seeds/seeds.js new file mode 100644 index 0000000..3c92a4c --- /dev/null +++ b/seeds/seeds.js @@ -0,0 +1,104 @@ +// var faker = require('faker'); +// var voca = require('voca'); + +// const MULTIPLIER = 1; + +// function randomRating() { +// return Math.floor(Math.random() * 6); +// } + +// function randomLodgingName(type) { +// type = voca.titleCase(type); +// var randomWord = faker.random.word(); +// randomWord = voca.titleCase(randomWord); +// var names = [ +// `The ${ randomWord } Inn`, +// `${ type } ${ randomWord }`, +// `${ randomWord } ${ type }` +// ]; +// var index = Math.floor(Math.random() * names.length); +// return names[index]; +// } + +module.exports = () => { + // ---------------------------------------- + // Create Users + // ---------------------------------------- + console.log("Creating Users"); + var users = []; + for (let i = 0; i < 6; i++) { + var user = new User({ + fname: "Foo", + lname: "Bar", + username: `foobar${i}`, + email: `foobar${i}@gmail.com` + }); + users.push(user); + } + + // // ---------------------------------------- + // // Hotels + // // ---------------------------------------- + // console.log('Creating Hotels'); + // var hotels = []; + // for (let i = 0; i < MULTIPLIER * 100; i++) { + // var hotel = new Hotel({ + // name: randomLodgingName('hotel') + // }); + // hotels.push(hotel); + // } + + // // ---------------------------------------- + // // Motels + // // ---------------------------------------- + // console.log('Creating Motels'); + // var motels = []; + // for (let i = 0; i < MULTIPLIER * 100; i++) { + // var motel = new Motel({ + // name: randomLodgingName('motel') + // }); + // motels.push(motel); + // } + + // // ---------------------------------------- + // // Ratings + // // ---------------------------------------- + // console.log('Creating Ratings'); + // var ratings = []; + // for (let i = 0; i < MULTIPLIER * 1000; i++) { + // var hotel = hotels[i % hotels.length]; + // var motel = motels[i % motels.length]; + // var user = users[1]; + // var hotelRating = new Rating({ + // ratable: hotel, + // user: user, + // value: randomRating() + // }); + // var motelRating = new Rating({ + // ratable: motel, + // user: user, + // value: randomRating() + // }); + // hotel.ratings.push(hotelRating); + // motel.ratings.push(motelRating); + // ratings.push(hotelRating); + // ratings.push(motelRating); + // } + + // ---------------------------------------- + // Finish + // ---------------------------------------- + console.log("Saving..."); + var promises = []; + [ + users + // hotels, + // motels, + // ratings + ].forEach(collection => { + collection.forEach(model => { + promises.push(model.save()); + }); + }); + return Promise.all(promises); +}; diff --git a/views/users/index.handlebars b/views/users/index.handlebars new file mode 100644 index 0000000..204235f --- /dev/null +++ b/views/users/index.handlebars @@ -0,0 +1,59 @@ + + + + + +{{#if users.length }} + + + + + + + + + + + + + {{#each users as |user| }} + + + + + + + + + {{/each }} + +
First NameLast NameUsernameEmail
+ {{ user.fname }} + + {{ user.lname }} + + {{ user.username }} + + {{ user.email }} + + Edit + + Delete +
+{{else }} +

No users

+{{/if }} + + + + + + + + + + + From 8741f678c81e48443e1589eb0298df325656e51d Mon Sep 17 00:00:00 2001 From: deven1 Date: Mon, 17 Apr 2017 14:02:33 -0400 Subject: [PATCH 04/13] added Users module --- app.js | 20 +++---- routers/sessions.js | 10 ---- routers/users.js | 109 ++++++++++++++++++++++++++++++++++- views/users/index.handlebars | 15 +---- 4 files changed, 119 insertions(+), 35 deletions(-) diff --git a/app.js b/app.js index 3af74d8..8e7ea54 100644 --- a/app.js +++ b/app.js @@ -81,14 +81,14 @@ app.use((req, res, next) => { // ---------------------------------------- // Mongoose // ---------------------------------------- -// var mongoose = require("mongoose"); -// app.use((req, res, next) => { -// if (mongoose.connection.readyState) { -// next(); -// } else { -// require("./mongo")(req).then(() => next()); -// } -// }); +var mongoose = require("mongoose"); +app.use((req, res, next) => { + if (mongoose.connection.readyState) { + next(); + } else { + require("./mongo")(req).then(() => next()); + } +}); // ---------------------------------------- // Routes @@ -96,8 +96,8 @@ app.use((req, res, next) => { var sessionsRouter = require("./routers/sessions"); app.use("/", sessionsRouter); -// var usersRouter = require('./routers/users'); -// app.use('/users', usersRouter); +var usersRouter = require("./routers/users"); +app.use("/users", usersRouter); // var ratablesRouter = require('./routers/ratables'); // app.use('/ratables', ratablesRouter); diff --git a/routers/sessions.js b/routers/sessions.js index b946a9d..f277d8c 100644 --- a/routers/sessions.js +++ b/routers/sessions.js @@ -7,16 +7,6 @@ var mongoose = require("mongoose"); //var app = express(); -router.get("/", function(req, res) { - // invoked when localhost:3000 is visited - if (req.session.currentUser) { - // to send user to logged page if already signed in on different browser tab, per the specification - res.send("Hello Theoreddit!"); - } else { - res.redirect("/login"); - } -}); - router.get("/login", (req, res) => { if (req.session.currentUser) { // to prevent unauthorized direct access to the 'logged' private page diff --git a/routers/users.js b/routers/users.js index fd35b24..b6a5095 100644 --- a/routers/users.js +++ b/routers/users.js @@ -1,5 +1,110 @@ var express = require("express"); var router = express.Router(); var mongoose = require("mongoose"); -// var models = require('./../models'); -// var User = mongoose.model('User'); +var models = require("./../models"); +var User = mongoose.model("User"); + +var userCallBack = (req, res) => { + if (req.session.currentUser) { + User.find({}) // 'User' is the collection in database, find() is mongoose method + .then(users => { + res.render("users/index", { users }); + }) + .catch(e => res.status(500).send(e.stack)); + } else { + res.redirect("/login"); + } +}; + +// ---------------------------------------- +// Index +// ---------------------------------------- +router.get("/", userCallBack); + +router.get("/users", userCallBack); + +// ---------------------------------------- +// New +// ---------------------------------------- +// router.get("/new", (req, res) => { +// res.render("users/new"); +// }); + +// ---------------------------------------- +// Edit +// ---------------------------------------- +// router.get("/:id/edit", (req, res) => { +// User.findById(req.params.id) +// .then(user => { +// res.render("users/edit", { user }); +// }) +// .catch(e => res.status(500).send(e.stack)); +// }); + +// ---------------------------------------- +// Show +// ---------------------------------------- +// router.get("/:id", (req, res) => { +// User.findById(req.params.id) +// .then(user => { +// res.render("users/show", { user }); +// }) +// .catch(e => res.status(500).send(e.stack)); +// }); + +// ---------------------------------------- +// Create +// ---------------------------------------- +// router.post("/", (req, res) => { +// var user = new User({ +// fname: req.body.user.fname, +// lname: req.body.user.lname, +// username: req.body.user.username, +// email: req.body.user.email +// }); +// +// user +// .save() +// .then(user => { +// res.redirect(`/users/${user.id}`); +// }) +// .catch(e => res.status(500).send(e.stack)); +// }); + +// ---------------------------------------- +// Update +// ---------------------------------------- +// router.put("/:id", (req, res) => { +// var userParams = { +// fname: req.body.user.fname, +// lname: req.body.user.lname, +// username: req.body.user.username, +// email: req.body.user.email +// }; +// +// User.findByIdAndUpdate(req.params.id, userParams) +// .then(user => { +// req.method = "GET"; +// res.redirect(`/users/${user.id}`); +// }) +// .catch(e => res.status(500).send(e.stack)); +// }); + +// ---------------------------------------- +// Destroy +// ---------------------------------------- +// router.delete("/:id", (req, res) => { +// var currentUser = req.session.currentUser; +// User.findByIdAndRemove(req.params.id) +// .then(() => { +// req.method = "GET"; +// if (currentUser.id === req.params.id) { +// res.redirect("/logout"); +// } else { +// res.redirect("/users"); +// } +// }) +// .catch(e => res.status(500).send(e.stack)); +// }); + +module.exports = router; diff --git a/views/users/index.handlebars b/views/users/index.handlebars index 204235f..504ee75 100644 --- a/views/users/index.handlebars +++ b/views/users/index.handlebars @@ -14,8 +14,8 @@ Last Name Username Email - - + Edit + Delete @@ -46,14 +46,3 @@ {{else }}

No users

{{/if }} - - - - - - - - - - - From 0080627d59ca77175737726335f3d7e5d55322b8 Mon Sep 17 00:00:00 2001 From: deven1 Date: Mon, 17 Apr 2017 15:53:48 -0400 Subject: [PATCH 05/13] small change --- app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.js b/app.js index 8e7ea54..e917f73 100644 --- a/app.js +++ b/app.js @@ -97,7 +97,7 @@ var sessionsRouter = require("./routers/sessions"); app.use("/", sessionsRouter); var usersRouter = require("./routers/users"); -app.use("/users", usersRouter); +app.use("/", usersRouter); // var ratablesRouter = require('./routers/ratables'); // app.use('/ratables', ratablesRouter); From 23485dbb26acf5bf22f063e19bb63253eeddd52a Mon Sep 17 00:00:00 2001 From: Egle Libby Date: Mon, 17 Apr 2017 15:54:41 -0400 Subject: [PATCH 06/13] change --- app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.js b/app.js index 8e7ea54..e917f73 100644 --- a/app.js +++ b/app.js @@ -97,7 +97,7 @@ var sessionsRouter = require("./routers/sessions"); app.use("/", sessionsRouter); var usersRouter = require("./routers/users"); -app.use("/users", usersRouter); +app.use("/", usersRouter); // var ratablesRouter = require('./routers/ratables'); // app.use('/ratables', ratablesRouter); From 7aa1124d4027a06a318a8b3665eafa64d8b13444 Mon Sep 17 00:00:00 2001 From: Egle Libby Date: Mon, 17 Apr 2017 16:21:28 -0400 Subject: [PATCH 07/13] finish user page --- app.js | 2 +- models/comment.js | 14 ++++++++++++++ models/commentable.js | 27 +++++++++++++++++++++++++++ models/index.js | 4 ++++ models/post.js | 16 ++++++++++++++++ package.json | 1 + routers/sessions.js | 19 ++++++++++++++++++- routers/users.js | 22 ++++++++++------------ seeds/seeds.js | 6 +++++- views/users/show.handlebars | 37 +++++++++++++++++++++++++++++++++++++ 10 files changed, 133 insertions(+), 15 deletions(-) create mode 100644 models/comment.js create mode 100644 models/commentable.js create mode 100644 models/post.js create mode 100644 views/users/show.handlebars diff --git a/app.js b/app.js index e917f73..8e7ea54 100644 --- a/app.js +++ b/app.js @@ -97,7 +97,7 @@ var sessionsRouter = require("./routers/sessions"); app.use("/", sessionsRouter); var usersRouter = require("./routers/users"); -app.use("/", usersRouter); +app.use("/users", usersRouter); // var ratablesRouter = require('./routers/ratables'); // app.use('/ratables', ratablesRouter); diff --git a/models/comment.js b/models/comment.js new file mode 100644 index 0000000..b23a314 --- /dev/null +++ b/models/comment.js @@ -0,0 +1,14 @@ +var mongoose = require("mongoose"); +var Schema = mongoose.Schema; +var Commentable = require("./commentable"); + +let CommentSchema = new Schema( + {}, + { + discriminatorKey: "kind" + } +); + +const Comment = Commentable.discriminator("Comment", CommentSchema); + +module.exports = Comment; diff --git a/models/commentable.js b/models/commentable.js new file mode 100644 index 0000000..8fa10d8 --- /dev/null +++ b/models/commentable.js @@ -0,0 +1,27 @@ +var mongoose = require("mongoose"); +var Schema = mongoose.Schema; + +let CommentableSchema = new Schema( + { + body: String, + score: Number, + author: { + type: Schema.Types.ObjectId, + ref: "User" + }, + comments: [ + { + type: Schema.Types.ObjectId, + ref: "Comment" + } + ] + }, + { + timestamps: true, + discriminatorKey: "kind" + } +); + +const Commentable = mongoose.model("Commentable", CommentableSchema); + +module.exports = Commentable; diff --git a/models/index.js b/models/index.js index a4e2137..09e6204 100644 --- a/models/index.js +++ b/models/index.js @@ -9,6 +9,10 @@ var models = {}; // Load models and attach to models here models.User = require("./user"); +models.Commentable = require("./commentable"); +models.Comment = require("./comment"); +models.Post = require("./post"); + //... more models module.exports = models; diff --git a/models/post.js b/models/post.js new file mode 100644 index 0000000..a93d6e9 --- /dev/null +++ b/models/post.js @@ -0,0 +1,16 @@ +var mongoose = require("mongoose"); +var Schema = mongoose.Schema; +var Commentable = require("./commentable"); + +let PostSchema = new Schema( + { + title: String + }, + { + discriminatorKey: "kind" + } +); + +const Post = Commentable.discriminator("Post", PostSchema); + +module.exports = Post; diff --git a/package.json b/package.json index 1149e6b..dfa1a39 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "cookie-session": "^2.0.0-beta.1", "express": "^4.15.2", "express-handlebars": "^3.0.0", + "faker": "^4.1.0", "mongoose": "^4.9.5", "morgan": "^1.8.1" } diff --git a/routers/sessions.js b/routers/sessions.js index f277d8c..790741f 100644 --- a/routers/sessions.js +++ b/routers/sessions.js @@ -7,10 +7,19 @@ var mongoose = require("mongoose"); //var app = express(); +router.get("/", (req, res) => { + if (req.session.currentUser) { + // to prevent unauthorized direct access to the 'logged' private page + res.redirect("/users"); + } else { + res.redirect("/login"); + } +}); + router.get("/login", (req, res) => { if (req.session.currentUser) { // to prevent unauthorized direct access to the 'logged' private page - res.redirect("/"); + res.redirect("/users"); } else { res.render("sessions/login"); } @@ -29,4 +38,12 @@ router.post("/logout", (req, res) => { res.redirect("/"); }); +// Destroy +var onDestroy = (req, res) => { + req.session.currentUser = null; + res.redirect("/login"); +}; +router.get("/logout", onDestroy); +router.delete("/logout", onDestroy); + module.exports = router; diff --git a/routers/users.js b/routers/users.js index b6a5095..08c7ec8 100644 --- a/routers/users.js +++ b/routers/users.js @@ -21,8 +21,6 @@ var userCallBack = (req, res) => { // ---------------------------------------- router.get("/", userCallBack); -router.get("/users", userCallBack); - // ---------------------------------------- // New // ---------------------------------------- @@ -41,16 +39,16 @@ router.get("/users", userCallBack); // .catch(e => res.status(500).send(e.stack)); // }); -// ---------------------------------------- -// Show -// ---------------------------------------- -// router.get("/:id", (req, res) => { -// User.findById(req.params.id) -// .then(user => { -// res.render("users/show", { user }); -// }) -// .catch(e => res.status(500).send(e.stack)); -// }); +//---------------------------------------- +//Show +//---------------------------------------- +router.get("/:id", (req, res) => { + User.findById(req.params.id) + .then(user => { + res.render("users/show", { user }); + }) + .catch(e => res.status(500).send(e.stack)); +}); // ---------------------------------------- // Create diff --git a/seeds/seeds.js b/seeds/seeds.js index 3c92a4c..bb3d028 100644 --- a/seeds/seeds.js +++ b/seeds/seeds.js @@ -1,4 +1,4 @@ -// var faker = require('faker'); +var faker = require("faker"); // var voca = require('voca'); // const MULTIPLIER = 1; @@ -20,6 +20,10 @@ // return names[index]; // } +function randomText() { + return faker.lorem.sentence(); +} + module.exports = () => { // ---------------------------------------- // Create Users diff --git a/views/users/show.handlebars b/views/users/show.handlebars new file mode 100644 index 0000000..6e92033 --- /dev/null +++ b/views/users/show.handlebars @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyValue
First Name{{ user.fname }}
Last Name{{ user.lname }}
Username{{ user.username }}
Email{{ user.email }}
+ + From 21958d1f7a31ed31d934490d1576a4368855466b Mon Sep 17 00:00:00 2001 From: deven1 Date: Mon, 17 Apr 2017 16:50:18 -0400 Subject: [PATCH 08/13] pushing changes --- seeds/seeds.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/seeds/seeds.js b/seeds/seeds.js index bb3d028..b8ef207 100644 --- a/seeds/seeds.js +++ b/seeds/seeds.js @@ -40,17 +40,17 @@ module.exports = () => { users.push(user); } - // // ---------------------------------------- - // // Hotels - // // ---------------------------------------- - // console.log('Creating Hotels'); - // var hotels = []; - // for (let i = 0; i < MULTIPLIER * 100; i++) { - // var hotel = new Hotel({ - // name: randomLodgingName('hotel') - // }); - // hotels.push(hotel); - // } + // ---------------------------------------- + // Posts + // ---------------------------------------- + console.log("Creating Posts"); + var posts = []; + for (let i = 0; i < 20; i++) { + var post = new Post({ + text: randomText() + }); + posts.push(post); + } // // ---------------------------------------- // // Motels From 3978f140704cac0ea202d1f570d69916cc0d6348 Mon Sep 17 00:00:00 2001 From: Egle Libby Date: Mon, 17 Apr 2017 17:23:25 -0400 Subject: [PATCH 09/13] create posts index --- app.js | 3 +++ routers/posts.js | 39 +++++++++++++++++++++++++++++++++++ seeds/seeds.js | 22 +++++++++++++++----- views/posts/index.handlebars | 40 ++++++++++++++++++++++++++++++++++++ 4 files changed, 99 insertions(+), 5 deletions(-) create mode 100644 routers/posts.js create mode 100644 views/posts/index.handlebars diff --git a/app.js b/app.js index 8e7ea54..104e6bd 100644 --- a/app.js +++ b/app.js @@ -99,6 +99,9 @@ app.use("/", sessionsRouter); var usersRouter = require("./routers/users"); app.use("/users", usersRouter); +var postsRouter = require("./routers/posts"); +app.use("/posts", postsRouter); + // var ratablesRouter = require('./routers/ratables'); // app.use('/ratables', ratablesRouter); diff --git a/routers/posts.js b/routers/posts.js new file mode 100644 index 0000000..cfcf447 --- /dev/null +++ b/routers/posts.js @@ -0,0 +1,39 @@ +var express = require("express"); +var router = express.Router(); +var mongoose = require("mongoose"); +var models = require("./../models"); +var User = mongoose.model("User"); +var Post = mongoose.model("Post"); + +// ---------------------------------------- +// Index +// ---------------------------------------- +router.get("/", (req, res) => { + if (req.session.currentUser) { + var posts; + Post.find({}) + .then(postsProm => { + posts = postsProm; + var promiseArr = []; + posts.forEach(post => { + promiseArr.push(User.findById(post.author)); + }); + return Promise.all(promiseArr); + }) + .then(users => { + posts.forEach(post => { + users.forEach(user => { + if (post.author == user._id) { + post.user = user; + } + }); + }); + res.render("posts/index", { posts }); + }) + .catch(e => res.status(500).send(e.stack)); + } else { + res.redirect("/login"); + } +}); + +module.exports = router; diff --git a/seeds/seeds.js b/seeds/seeds.js index b8ef207..005f7db 100644 --- a/seeds/seeds.js +++ b/seeds/seeds.js @@ -3,9 +3,9 @@ var faker = require("faker"); // const MULTIPLIER = 1; -// function randomRating() { -// return Math.floor(Math.random() * 6); -// } +function randomRating() { + return Math.floor(Math.random() * 6); +} // function randomLodgingName(type) { // type = voca.titleCase(type); @@ -23,6 +23,9 @@ var faker = require("faker"); function randomText() { return faker.lorem.sentence(); } +function randomWord() { + return faker.random.word(); +} module.exports = () => { // ---------------------------------------- @@ -40,6 +43,10 @@ module.exports = () => { users.push(user); } + function randomUserIndex() { + return Math.floor(Math.random() * users.length); + } + // ---------------------------------------- // Posts // ---------------------------------------- @@ -47,7 +54,11 @@ module.exports = () => { var posts = []; for (let i = 0; i < 20; i++) { var post = new Post({ - text: randomText() + title: randomWord(), + body: randomText(), + score: randomRating(), + author: users[randomUserIndex()], + comments: [] }); posts.push(post); } @@ -95,7 +106,8 @@ module.exports = () => { console.log("Saving..."); var promises = []; [ - users + users, + posts // hotels, // motels, // ratings diff --git a/views/posts/index.handlebars b/views/posts/index.handlebars new file mode 100644 index 0000000..3a20d7f --- /dev/null +++ b/views/posts/index.handlebars @@ -0,0 +1,40 @@ + + + + + +{{#if posts.length }} + + + + + + + + + + + {{#each posts as |post| }} + + + + + + + {{/each }} + +
Posted AtTitleBodyUsername
+ {{ post.createdAt }} + + {{ post.title }} + + {{ post.body}} + + {{ post.user.username }} +
+{{else }} +

No users

+{{/if }} From cbc7d1403b7f6e90895443659d4c1d34d36f8960 Mon Sep 17 00:00:00 2001 From: deven1 Date: Mon, 17 Apr 2017 17:37:17 -0400 Subject: [PATCH 10/13] posts completed --- routers/posts.js | 4 +++- views/posts/index.handlebars | 2 +- views/shared/_nav.handlebars | 5 +++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/routers/posts.js b/routers/posts.js index cfcf447..8539845 100644 --- a/routers/posts.js +++ b/routers/posts.js @@ -23,7 +23,9 @@ router.get("/", (req, res) => { .then(users => { posts.forEach(post => { users.forEach(user => { - if (post.author == user._id) { + //console.log("user " + user + "\n" + "post " + post); + if (post.author == user.id) { + console.log("inside if statement ......."); post.user = user; } }); diff --git a/views/posts/index.handlebars b/views/posts/index.handlebars index 3a20d7f..4e59b2f 100644 --- a/views/posts/index.handlebars +++ b/views/posts/index.handlebars @@ -29,7 +29,7 @@ {{ post.body}} - {{ post.user.username }} + {{ post.user.username }} {{/each }} diff --git a/views/shared/_nav.handlebars b/views/shared/_nav.handlebars index a64070b..fbbebb6 100644 --- a/views/shared/_nav.handlebars +++ b/views/shared/_nav.handlebars @@ -8,7 +8,7 @@ - Theoreddit + Thoreddit
@@ -20,6 +20,7 @@
  • Logout
  • @@ -28,4 +29,4 @@ - \ No newline at end of file + From 5ba828d260451c05946efa7a77c59be3f415d14b Mon Sep 17 00:00:00 2001 From: Egle Libby Date: Mon, 17 Apr 2017 18:19:47 -0400 Subject: [PATCH 11/13] add seeds for posts --- routers/users.js | 12 +++++------- seeds/seeds.js | 23 +++++++++++++++++++++-- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/routers/users.js b/routers/users.js index 08c7ec8..d4b2eae 100644 --- a/routers/users.js +++ b/routers/users.js @@ -4,7 +4,10 @@ var mongoose = require("mongoose"); var models = require("./../models"); var User = mongoose.model("User"); -var userCallBack = (req, res) => { +// ---------------------------------------- +// Index +// ---------------------------------------- +router.get("/", (req, res) => { if (req.session.currentUser) { User.find({}) // 'User' is the collection in database, find() is mongoose method .then(users => { @@ -14,12 +17,7 @@ var userCallBack = (req, res) => { } else { res.redirect("/login"); } -}; - -// ---------------------------------------- -// Index -// ---------------------------------------- -router.get("/", userCallBack); +}); // ---------------------------------------- // New diff --git a/seeds/seeds.js b/seeds/seeds.js index 005f7db..75183fe 100644 --- a/seeds/seeds.js +++ b/seeds/seeds.js @@ -46,6 +46,24 @@ module.exports = () => { function randomUserIndex() { return Math.floor(Math.random() * users.length); } + function randomCommentIndex() { + return Math.floor(Math.random() * comments.length) + 2; + } + + // -------------------------------------------- + // Comments + // -------------------------------------------- + console.log("Creating Comments"); + var comments = []; + for (let i = 0; i < 100; i++) { + var comment = new Comment({ + body: randomText(), + score: randomRating(), + author: users[randomUserIndex()], + comments: i === 0 || i === 1 ? [] : [comments[0], comments[1]] + }); + comments.push(comment); + } // ---------------------------------------- // Posts @@ -58,7 +76,7 @@ module.exports = () => { body: randomText(), score: randomRating(), author: users[randomUserIndex()], - comments: [] + comments: [comments[randomCommentIndex()], comments[randomCommentIndex()]] }); posts.push(post); } @@ -107,7 +125,8 @@ module.exports = () => { var promises = []; [ users, - posts + posts, + comments // hotels, // motels, // ratings From 4a81da839b64c56354727520adf64d33859ffec4 Mon Sep 17 00:00:00 2001 From: deven1 Date: Mon, 17 Apr 2017 18:52:45 -0400 Subject: [PATCH 12/13] almost there --- routers/posts.js | 18 ++++++++++++++++++ views/posts/show.handlebars | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 views/posts/show.handlebars diff --git a/routers/posts.js b/routers/posts.js index 8539845..a86a914 100644 --- a/routers/posts.js +++ b/routers/posts.js @@ -38,4 +38,22 @@ router.get("/", (req, res) => { } }); +router.get("/:id", (req, res) => { + Post.findOne({ id: req.params.id }) + .populate({ + path: "comments author score", + populate: { + path: "comments author score", + populate: { + path: "author score" + } + } + }) + .then(post => { + console.log("inside router.get ", post); + res.render("posts/show", { post }); + }) + .catch(e => res.status(500).send(e.stack)); +}); + module.exports = router; diff --git a/views/posts/show.handlebars b/views/posts/show.handlebars new file mode 100644 index 0000000..680331d --- /dev/null +++ b/views/posts/show.handlebars @@ -0,0 +1,21 @@ + +
    + {{#each post.comments as |comment| }} + {{comment.author}}   said: +
    + {{comment.body}} + Comment + {{#each comment.comments as |nestedComment| }} + {{nestedComment.author}}   said: +
    + {{nestedComment.body}} + Comment + {{/each}} + {{/each }} +
    From 071bc896c1ef69857919b2f56caedbaa137de296 Mon Sep 17 00:00:00 2001 From: Egle Libby Date: Mon, 17 Apr 2017 19:43:57 -0400 Subject: [PATCH 13/13] update --- routers/posts.js | 8 ++++---- seeds/seeds.js | 8 ++++---- views/posts/show.handlebars | 6 +++--- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/routers/posts.js b/routers/posts.js index a86a914..f1603c6 100644 --- a/routers/posts.js +++ b/routers/posts.js @@ -39,13 +39,13 @@ router.get("/", (req, res) => { }); router.get("/:id", (req, res) => { - Post.findOne({ id: req.params.id }) + Post.findOne({ _id: req.params.id }) .populate({ - path: "comments author score", + path: "comments author", populate: { - path: "comments author score", + path: "comments author", populate: { - path: "author score" + path: "author" } } }) diff --git a/seeds/seeds.js b/seeds/seeds.js index 75183fe..6ea950f 100644 --- a/seeds/seeds.js +++ b/seeds/seeds.js @@ -46,9 +46,9 @@ module.exports = () => { function randomUserIndex() { return Math.floor(Math.random() * users.length); } - function randomCommentIndex() { - return Math.floor(Math.random() * comments.length) + 2; - } + // function randomCommentIndex() { + // return Math.floor(Math.random() * comments.length) + 2; + // } // -------------------------------------------- // Comments @@ -76,7 +76,7 @@ module.exports = () => { body: randomText(), score: randomRating(), author: users[randomUserIndex()], - comments: [comments[randomCommentIndex()], comments[randomCommentIndex()]] + comments: [comments[2], comments[3]] }); posts.push(post); } diff --git a/views/posts/show.handlebars b/views/posts/show.handlebars index 680331d..aaa15ef 100644 --- a/views/posts/show.handlebars +++ b/views/posts/show.handlebars @@ -1,18 +1,18 @@
    {{#each post.comments as |comment| }} - {{comment.author}}   said: + {{comment.author.username}} said:
    {{comment.body}} Comment {{#each comment.comments as |nestedComment| }} - {{nestedComment.author}}   said: + {{nestedComment.author}} said:
    {{nestedComment.body}} Comment