diff --git a/app.js b/app.js index 2ecc9f2220..697add6c27 100644 --- a/app.js +++ b/app.js @@ -5,16 +5,32 @@ require('dotenv/config'); // ℹ️ Connects to the database require('./db'); +const { sessionConfig, loggedUser } = require("./config/session.config") + + // Handles http requests (express is node js framework) // https://www.npmjs.com/package/express const express = require('express'); // Handles the handlebars // https://www.npmjs.com/package/hbs +const path = require("path"); const hbs = require('hbs'); const app = express(); +app.use(express.json()); +app.use(express.urlencoded({ extended: false })); + +// Normalizes the path to the views folder +app.set("views", path.join(__dirname, "views")); +// Sets the view engine to handlebars +app.set("view engine", "hbs"); +// Handles access to the public folder +app.use(express.static(path.join(__dirname, "public"))); + +hbs.registerPartials(__dirname + "/views/partials"); + // ℹ️ This function is getting exported from the config folder. It runs most middlewares require('./config')(app); @@ -25,8 +41,10 @@ const capitalized = string => string[0].toUpperCase() + string.slice(1).toLowerC app.locals.title = `${capitalized(projectName)}- Generated with Ironlauncher`; // 👇 Start handling routes here -const index = require('./routes/index'); -app.use('/', index); +app.use(sessionConfig); +app.use(loggedUser) +const routes = require('./routes/router'); +app.use('/', routes); // ❗ To handle errors. Routes that don't exist or errors that you handle in specific routes require('./error-handling')(app); diff --git a/config/session.config.js b/config/session.config.js new file mode 100644 index 0000000000..c71b59425d --- /dev/null +++ b/config/session.config.js @@ -0,0 +1,41 @@ +const User = require("../models/User.model"); +const expressSession = require("express-session"); +const MongoStore = require("connect-mongo"); +const mongoose = require("mongoose"); + +const MAX_AGE = 7; + +module.exports.sessionConfig = expressSession({ + name: "express-cookie", + secret: "super-secret", + resave: false, + saveUninitialized: false, + cookie: { + secure: false, + httpOnly: true, + maxAge: 24 * 3600 * 1000 * MAX_AGE, + }, + store: new MongoStore({ + mongoUrl: mongoose.connection._connectionString, + ttl: 24 * 3600 * MAX_AGE, + }), +}); + +module.exports.loggedUser = (req, res, next) => { + const userId = req.session.userId; + if (userId) { + User.findById(userId) + .then((userFound) => { + if (userFound) { + req.currentUser = userFound; + res.locals.currentUser = userFound; + next(); + } else { + next(); + } + }) + .catch((err) => next(err)); + } else { + next(); + } +}; diff --git a/controllers/auth.controller.js b/controllers/auth.controller.js new file mode 100644 index 0000000000..cd3b2b119e --- /dev/null +++ b/controllers/auth.controller.js @@ -0,0 +1,71 @@ +// routes/auth.routes.js +const { Router } = require('express'); +const User = require("../models/User.model") +const { default: mongoose } = require('mongoose'); +const router = new Router(); + +// GET route ==> to display the signup form to users +module.exports.signUp = (req, res, next) => { + res.render('auth/signup') +} + + +// POST route ==> to process form data + +module.exports.doSignUp = (req, res, next) => { + User.create(req.body) + .then((user) => { + user.checkPassword(req.body.passwordHash) + res.redirect("/logIn"); + }) + .catch((err) => { + if (err instanceof mongoose.Error.ValidationError) { + res.render("signup", { + user: { + email: req.body.email, + }, + errors: err.errors, + }); + } else { + next(err); + } + }) +} + +module.exports.logIn = (req, res, next) => { + res.render("auth/logIn") +} + +module.exports.doLogIn = (req, res, next) => { + const { email, passwordHash } = req.body; + + const renderWithErrors = () => { + res.render("auth/login", { + email, + error: "Email o constraseña incorrectos" + }) + } + User.findOne({ email }) + .then((user) => { + if(user) { + return user.checkPassword(passwordHash) + .then((match) => { + if(match) { + req.session.userId = user.id; + res.redirect("/profile"); + } else { + renderWithErrors(); + } + }) + } else { + renderWithErrors(); + } + }) + .catch((err) => next(err)) +} + +module.exports.logOut = (req, res, next) => { + req.session.destroy(); + res.clearCookie("express-cookie"); + res.redirect("/login") +} \ No newline at end of file diff --git a/controllers/user.controller.js b/controllers/user.controller.js new file mode 100644 index 0000000000..8a3420b8c9 --- /dev/null +++ b/controllers/user.controller.js @@ -0,0 +1,13 @@ +const User = require("../models/User.model"); + +module.exports.profile = (req, res, next) => { + res.render("users/profile") +} + +module.exports.funnyCat = (req, res, next) => { + res.render("main") +} + +module.exports.private = (req, res, next) => { + res.render("private") +} \ No newline at end of file diff --git a/middlewares/auth.middleware.js b/middlewares/auth.middleware.js new file mode 100644 index 0000000000..53d1119b79 --- /dev/null +++ b/middlewares/auth.middleware.js @@ -0,0 +1,15 @@ +module.exports.isAuthenticated = (req, res, next) => { + if(req.currentUser) { + next(); + } else { + res.redirect("/logIn") + } +} + +module.exports.isNotAuthenticated = (req, res, next) => { + if(!req.currentUser) { + next(); + } else { + res.redirect("/profile") + } +} \ No newline at end of file diff --git a/models/User.model.js b/models/User.model.js index 9cdd3a3ce4..714692de66 100644 --- a/models/User.model.js +++ b/models/User.model.js @@ -1,14 +1,52 @@ -const { Schema, model } = require("mongoose"); +// models/User.model.js +const { Schema, model } = require('mongoose'); +const bcrypt = require("bcrypt"); -// TODO: Please make sure you edit the user model to whatever makes sense in this case -const userSchema = new Schema({ - username: { - type: String, - unique: true +const EMAIL_PATTERN = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; + +const userSchema = new Schema( + { + username: { + type: String, + trim: true, + required: [true, 'Username is required.'], + unique: true + }, + email: { + type: String, + required: [true, 'Email is required.'], + unique: true, + match: [EMAIL_PATTERN, "Email is invalid"], + lowercase: true, + trim: true, + match: [EMAIL_PATTERN, "Email is invalid"] + }, + passwordHash: { + type: String, + required: [true, 'Password is required.'] + } }, - password: String + { + timestamps: true + } +); + +userSchema.pre("save", function (next) { + const user = this; + + if (user.isModified("passwordHash")) { + bcrypt.hash(user.passwordHash, 10) + .then ((hash) => { + user.passwordHash = hash; + next(); + }); + } else { + next(); + } }); -const User = model("User", userSchema); +userSchema.methods.checkPassword = function (password) { + return bcrypt.compare(password, this.passwordHash) +} -module.exports = User; +module.exports = model('User', userSchema); diff --git a/package.json b/package.json index 19489d9695..7a08f67ec8 100644 --- a/package.json +++ b/package.json @@ -7,9 +7,13 @@ "dev": "nodemon server.js" }, "dependencies": { + "bcrypt": "^5.1.1", + "bcryptjs": "^2.4.3", + "connect-mongo": "^5.1.0", "cookie-parser": "^1.4.5", "dotenv": "^8.2.0", "express": "^4.17.1", + "express-session": "^1.18.1", "hbs": "^4.1.1", "mongoose": "^6.1.2", "morgan": "^1.10.0", diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 9453385b99..301783d551 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,8 +1,108 @@ +/* public/stylesheets/style.css */ body { padding: 50px; - font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; + font: 14px 'Lucida Grande', Helvetica, Arial, sans-serif; } a { - color: #00B7FF; + color: #00b7ff; + text-decoration: none; + font-size: 1.5em; +} + +form { + margin: 30px auto; + width: 380px; +} + +form label { + color: #666; + display: inline-block; + margin-bottom: 10px; + text-align: center; + width: 100%; +} + +form input, +form button { + box-sizing: border-box; + font-size: 14px; + outline: 0; + padding: 4px; + width: 100%; + margin-bottom: 20px; +} + +form button { + background: #43a3e6; + border: 1px solid #43a3e6; + border-radius: 4px; + color: #fff; + cursor: pointer; + display: inline-block; + font-size: 14px; + padding: 8px 16px; + text-decoration: none; + text-transform: uppercase; + transition: 0.3s ease background; + width: 100%; +} + +form button:hover { + background: #fff; + color: #43a3e6; + transition: 0.3s ease background; +} + +.error { + background: #f02b63; + box-sizing: border-box; + color: #fff; + margin: 20px auto; + padding: 20px; + width: 100%; +} + +ul { + border-bottom: 2px solid #43a3e6; + height: 30px; + padding: 1em 0; + list-style-type: none; +} + +ul li { + line-height: 20px; +} + +#to-right { + padding: 1em; + float: right; +} + +#to-right span { + color: #43a3e6; + font-size: 1.5em; +} + +#form h2 { + display: flex; + justify-content: center; +} + +#to-left { + float: left; +} + +#to-left p a { + color: #000; + font-weight: bold; + font-size: 2em; +} + +#logout-form { + display: inline; +} + +#logout-form button { + width: 120px; } diff --git a/routes/index.js b/routes/index.js deleted file mode 100644 index 81c2396ceb..0000000000 --- a/routes/index.js +++ /dev/null @@ -1,8 +0,0 @@ -const router = require("express").Router(); - -/* GET home page */ -router.get("/", (req, res, next) => { - res.render("index"); -}); - -module.exports = router; diff --git a/routes/router.js b/routes/router.js new file mode 100644 index 0000000000..330a3b66ed --- /dev/null +++ b/routes/router.js @@ -0,0 +1,24 @@ +const { signUp, doSignUp, logIn, doLogIn, logOut } = require("../controllers/auth.controller"); +const { profile, funnyCat, private } = require("../controllers/user.controller") +const { isAuthenticated, isNotAuthenticated } = require("../middlewares/auth.middleware") +const router = require("express").Router(); + +/* GET home page */ +router.get("/", (req, res, next) => { + res.render("index"); +}); + +router.get('/signup', isNotAuthenticated, signUp) +router.post('/signup', isNotAuthenticated, doSignUp) + +router.get('/logIn', isNotAuthenticated, logIn) +router.post('/logIn', isNotAuthenticated, doLogIn) + +router.get('/profile', isAuthenticated, profile) + +router.get('/main', isAuthenticated, funnyCat) +router.get('/private', isAuthenticated, private) + +router.get('/logout', logOut) + +module.exports = router; diff --git a/views/auth/logIn.hbs b/views/auth/logIn.hbs new file mode 100644 index 0000000000..b34c5ef905 --- /dev/null +++ b/views/auth/logIn.hbs @@ -0,0 +1,16 @@ +
+

LogIn

+
+ + + + + + + +
+
diff --git a/views/auth/signup.hbs b/views/auth/signup.hbs new file mode 100644 index 0000000000..01be5b160d --- /dev/null +++ b/views/auth/signup.hbs @@ -0,0 +1,23 @@ +{{!-- views/auth/signup.hbs --}} + +
+

Signup

+
+ + + + + + + + + + {{!-- error message will be added here --}} +
+
diff --git a/views/layout.hbs b/views/layout.hbs index 73199c166b..308b0a0e49 100644 --- a/views/layout.hbs +++ b/views/layout.hbs @@ -1,19 +1,27 @@ + - - - + + + {{title}} + + - - {{{body}}} + {{> nav}} +
+ {{{body}}} +
- \ No newline at end of file + diff --git a/views/main.hbs b/views/main.hbs new file mode 100644 index 0000000000..0d4d058ca6 --- /dev/null +++ b/views/main.hbs @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/views/partials/nav.hbs b/views/partials/nav.hbs new file mode 100644 index 0000000000..35987873ec --- /dev/null +++ b/views/partials/nav.hbs @@ -0,0 +1,39 @@ + diff --git a/views/private.hbs b/views/private.hbs new file mode 100644 index 0000000000..a5067509e4 --- /dev/null +++ b/views/private.hbs @@ -0,0 +1,3 @@ +

THIS IS A PRIVATE PAGE FOR {{currentUser.username}}

+ + \ No newline at end of file diff --git a/views/users/profile.hbs b/views/users/profile.hbs new file mode 100644 index 0000000000..9917a48125 --- /dev/null +++ b/views/users/profile.hbs @@ -0,0 +1,5 @@ +

PROFILE

+ +
+

{{currentUser.email}}

+