Skip to content
Open

done #2129

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
PORT=3000
PORT=3000
SESSION_SECRET='keyboard cat'
5 changes: 5 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require('./db');
// https://www.npmjs.com/package/express
const express = require('express');


// Handles the handlebars
// https://www.npmjs.com/package/hbs
const hbs = require('hbs');
Expand All @@ -27,6 +28,10 @@ app.locals.title = `${capitalized(projectName)}- Generated with Ironlauncher`;
// 👇 Start handling routes here
const index = require('./routes/index');
app.use('/', index);
const userPage = require('./routes/user.routes');
app.use('/user', userPage);
const protectedPages = require('./routes/protected.routes');
app.use('/auth', protectedPages);

// ❗ To handle errors. Routes that don't exist or errors that you handle in specific routes
require('./error-handling')(app);
Expand Down
30 changes: 28 additions & 2 deletions config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ const favicon = require("serve-favicon");
// https://www.npmjs.com/package/path
const path = require("path");

// ℹ️ Session middleware for authentication
// https://www.npmjs.com/package/express-session
const session = require("express-session");

// ℹ️ MongoStore in order to save the user session in the database
// https://www.npmjs.com/package/connect-mongo
const MongoStore = require("connect-mongo");

// Connects the mongo uri to maintain the same naming structure
const MONGO_URI =
process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/lab-express-basic-auth";

// Middleware configuration
module.exports = (app) => {
// In development environment the app logs
Expand All @@ -31,9 +43,23 @@ module.exports = (app) => {
app.set("views", path.join(__dirname, "..", "views"));
// Sets the view engine to handlebars
app.set("view engine", "hbs");
// Handles access to the public folder
// AHandles access to the public folder
app.use(express.static(path.join(__dirname, "..", "public")));

// Handles access to the favicon
app.use(favicon(path.join(__dirname, "..", "public", "images", "favicon.ico")));
app.use(
favicon(path.join(__dirname, "..", "public", "images", "favicon.ico"))
);

// ℹ️ Middleware that adds a "req.session" information and later to check that you are who you say you are 😅
app.use(
session({
secret: process.env.SESSION_SECRET || "super hyper secret key",
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: MONGO_URI,
}),
})
);
};
8 changes: 8 additions & 0 deletions middleware/isLoggedIn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = (req, res, next) => {
// checks if the user is logged in when trying to access a specific page
if (!req.session.currentUser) {
return res.redirect("/user/login");
}

next();
};
8 changes: 8 additions & 0 deletions middleware/isLoggedOut.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = (req, res, next) => {
// if an already logged in user tries to access the login page it
// redirects the user to the home page
if (req.session.currentUser) {
return res.redirect("/auth/main");
}
next();
};
7 changes: 5 additions & 2 deletions models/User.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ const { Schema, model } = require("mongoose");
const userSchema = new Schema({
username: {
type: String,
unique: true
unique: true,
},
password: String
password: {
type: String,
required: true,
}
});

const User = model("User", userSchema);
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
"dev": "nodemon server.js"
},
"dependencies": {
"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.0",
"hbs": "^4.1.1",
"mongoose": "^6.1.2",
"morgan": "^1.10.0",
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/OIP.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 17 additions & 0 deletions routes/protected.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const router = require("express").Router();
const User = require("../models/User.model");

const isLoggedOut = require("../middleware/isLoggedOut");
const isLoggedIn = require("../middleware/isLoggedIn");

router.get("/main", isLoggedIn, (req, res, next) => {
res.render("../views/protected/main.hbs");
});

router.get("/private", isLoggedIn, (req, res, next) => {
res.render('../views/protected/private.hbs');
});


module.exports = router;

52 changes: 52 additions & 0 deletions routes/user.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const router = require("express").Router();
const User = require("../models/User.model");
const bcrypt = require("bcryptjs");

const isLoggedOut = require("../middleware/isLoggedOut");
const isLoggedIn = require("../middleware/isLoggedIn");

/* GET home page */
router.get("/create", (req, res, next) => {
res.render("../views/users/create-user.hbs");
});

router.post("/create", async (req, res, next) => {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(req.body.password, salt);
User.create({ username: req.body.username, password: hash }).then(() => {
res.redirect("/");
});
});

router.get("/login", isLoggedOut ,(req, res, next) => {
res.render('../views/users/log-in.hbs');
});

router.post('/login', async (req, res, next) => {
User.findOne({username: req.body.username}).then(async (user) => {
const isLoggedIn = await bcrypt.compare(req.body.password, user.password)
if(isLoggedIn){
console.log('Your account exists');

req.session.currentUser = user.toObject();
delete req.session.currentUser.password;

res.redirect('/auth/main')
}else{
console.log('Your account doesnt exist');
}
})
})

router.get("/logout", isLoggedIn, (req, res) => {
req.session.destroy((err) => {
if (err) {
res.status(500).render("auth/logout", { errorMessage: err.message });
return;
}

res.redirect("/user/login");
});
});

module.exports = router;
2 changes: 2 additions & 0 deletions views/index.hbs
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
<h1>{{title}}</h1>
<p>Welcome to {{title}}</p>
<a href="/user/create">Create a User</a>
<a href="/user/login">Log In</a>
1 change: 1 addition & 0 deletions views/layout.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{title}}</title>
<link rel="stylesheet" href="/stylesheets/style.css" />

</head>

<body>
Expand Down
2 changes: 2 additions & 0 deletions views/protected/main.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<img src="/images/OIP.jpg" alt="Cat-Image">
<a href="/">Go Back</a>
2 changes: 2 additions & 0 deletions views/protected/private.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h1>You cant enter to this page if you arent logged in</h1>
<img src="/images/697b023b-64a5-49a0-8059-27b963453fb1.gif" alt="">
9 changes: 9 additions & 0 deletions views/users/create-user.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<form action="/user/create" method="POST">
<label for="username">Username
<input name="username" type="text" id="username" />
</label><br>
<label for="password">Password
<input name="password" type="password" id="password" />
</label><br>
<button class="p-2 bg-blue-900 text-black" type="submit">Create New User</button>
</form>
9 changes: 9 additions & 0 deletions views/users/log-in.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<form action="/user/login" method="POST">
<label for="username">Username
<input name="username" type="text" id="username" />
</label><br>
<label for="password">Password
<input name="password" type="password" id="password" />
</label><br>
<button class="p-2 bg-blue-900 text-black" type="submit">Log In</button>
</form>