diff --git a/.env b/.env index c0c68b1ca0..93f0090623 100644 --- a/.env +++ b/.env @@ -1 +1,2 @@ -PORT=3000 \ No newline at end of file +PORT=3000 +SESS_SECRET=123 \ No newline at end of file diff --git a/app.js b/app.js index 2ecc9f2220..177218cbb0 100644 --- a/app.js +++ b/app.js @@ -18,6 +18,8 @@ const app = express(); // ℹ️ This function is getting exported from the config folder. It runs most middlewares require('./config')(app); +require('./config/session.config')(app); + // default value for title local const projectName = 'lab-express-basic-auth'; const capitalized = string => string[0].toUpperCase() + string.slice(1).toLowerCase(); diff --git a/config/session.config.js b/config/session.config.js new file mode 100644 index 0000000000..14ee760f24 --- /dev/null +++ b/config/session.config.js @@ -0,0 +1,29 @@ +const session = require('express-session'); +const MongoStore = require('connect-mongo'); + +// since we are going to USE this middleware in the app.js, +// let's export it and have it receive a parameter +module.exports = app => { + // <== app is just a placeholder here + // but will become a real "app" in the app.js + // when this file gets imported/required there + + // required for the app when deployed to Heroku (in production) + app.set('trust proxy', 1); + + // use session + app.use( + session({ + secret: process.env.SESS_SECRET, + resave: true, + saveUninitialized: true, + store: MongoStore.create({ mongoUrl: process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/basic-auth" }), + cookie: { + sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax', + secure: process.env.NODE_ENV === 'production', + httpOnly: true, + maxAge: 600000 // 600 * 1000 ms === 10 min + } + }) + ); +}; diff --git a/error-handling/index.js b/error-handling/index.js index 5d6e74bc1c..e6f510b84f 100644 --- a/error-handling/index.js +++ b/error-handling/index.js @@ -4,6 +4,7 @@ module.exports = (app) => { res.status(404).render("not-found"); }); + app.use((err, req, res, next) => { // whenever you call next(err), this middleware will handle the error // always logs the error diff --git a/middlewares/route-guard.js b/middlewares/route-guard.js new file mode 100644 index 0000000000..c333c72afc --- /dev/null +++ b/middlewares/route-guard.js @@ -0,0 +1,22 @@ +// checks if the user is logged in when trying to access a specific page +const isLoggedIn = (req, res, next) => { + if (!req.session.currentUser) { + return res.redirect('/login'); + } + next(); + }; + + // if an already logged in user tries to access the login page it + // redirects the user to the home page + const isLoggedOut = (req, res, next) => { + console.log(req.session) + if (req.session.currentUser) { + return res.redirect('/'); + } + next(); + }; + + module.exports = { + isLoggedIn, + isLoggedOut + }; \ No newline at end of file diff --git a/models/User.model.js b/models/User.model.js index 9cdd3a3ce4..d2fea81324 100644 --- a/models/User.model.js +++ b/models/User.model.js @@ -6,6 +6,17 @@ const userSchema = new Schema({ type: String, unique: true }, + email: { + type: String, + required: [true, 'Email is required.'], + unique: true, + lowercase: true, + trim: true + }, + passwordHash: { + type: String, + required: [true, 'Password is required.'] + }, password: String }); diff --git a/package.json b/package.json index 19489d9695..d86da07c94 100644 --- a/package.json +++ b/package.json @@ -7,9 +7,12 @@ "dev": "nodemon server.js" }, "dependencies": { + "bcrypt": "^5.1.1", + "connect-mongo": "^5.1.0", "cookie-parser": "^1.4.5", "dotenv": "^8.2.0", "express": "^4.17.1", + "express-session": "^1.18.0", "hbs": "^4.1.1", "mongoose": "^6.1.2", "morgan": "^1.10.0", diff --git a/routes/index.js b/routes/index.js index 81c2396ceb..5a4b1f8c82 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,8 +1,84 @@ +const User = require("../models/User.model"); +const bcryptjs = require('bcrypt'); +const saltRounds = 10; const router = require("express").Router(); +const { isLoggedIn, isLoggedOut } = require('../middlewares/route-guard.js'); + /* GET home page */ router.get("/", (req, res, next) => { res.render("index"); }); +/* GET signup page */ +router.get("/signup", isLoggedOut, (req, res, next) => { + console.log('req.session', req.session) + res.render("auth/signup"); +}); + +router.post('/signup', isLoggedOut, (req, res, next) => { + // console.log("The form data: ", req.body); + const { username, email, password } = req.body; + + bcryptjs + .genSalt(saltRounds) + .then(salt => bcryptjs.hash(password, salt)) + .then(hashedPassword => { + return User.create({ + username: username, + email: email, + passwordHash: hashedPassword + }); + }) + .then(userFromDB => { + res.redirect('/usersProfile'); + console.log(userFromDB, `this is the new user`) + }) + .catch(error => next(error)); +}); + +router.get('/usersProfile', (req, res) => res.render('users/user-profile')); + +router.get('/login', isLoggedOut, (req, res)=>{ + res.render('auth/login') +}) + +router.post('/login', isLoggedOut, (req, res)=>{ + const { email, password } = req.body; + + if (email === '' || password === '') { + res.render('auth/login', { + errorMessage: 'Please enter both, email and password to login.' + }); + return; + } + + User.findOne({ email }) + .then(user => { + console.log('user', user) + if (!user) { + + console.log("Email not registered. "); + res.render('auth/login', { errorMessage: 'User not found and/or incorrect password.' }); + return; + } + else if (bcryptjs.compareSync(password, user.passwordHash)) { + req.session.currentUser = user; + res.render('users/user-profile', { user }); + } + else { + console.log("Incorrect password. "); + res.render('auth/login', { errorMessage: 'User not found and/or incorrect password.' }); + } + }) + .catch(error => next(error)); +}) + +router.get('/main', isLoggedIn, (req, res) => { + res.render('main', { user: req.session.currentUser }); +}); + +router.get('/private', isLoggedIn, (req, res) => { + res.render('private', { user: req.session.currentUser }); +}); module.exports = router; diff --git a/views/auth/login.hbs b/views/auth/login.hbs new file mode 100644 index 0000000000..1dc3b2d018 --- /dev/null +++ b/views/auth/login.hbs @@ -0,0 +1,22 @@ + +{{!-- views/auth/signup.hbs --}} + +
Here is a funny picture of a cat:
+Here is my favorite gif:
+
+