Skip to content

Instantly share code, notes, and snippets.

@da7a90
Last active September 25, 2019 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save da7a90/1156791ae5858639ea0c64c387e59885 to your computer and use it in GitHub Desktop.
Save da7a90/1156791ae5858639ea0c64c387e59885 to your computer and use it in GitHub Desktop.
simple authentication for beginners in NodeJS
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const app = express();
// Configuring the database
const dbConfig = require('./database.config.js');
const mongoose = require('mongoose');
const User = require('./model')
mongoose.Promise = global.Promise;
// Connecting to the database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
// parse urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
//this is sort of the main definition of our session with all the attributes it needs to keep the user logged in
app.use(session({
cookieName: 'session',
secret: 'random_string_goes_here',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
}));
//using a statics directory for all static css and js files it must not contain the html files if you want the authentication to work correctly
app.use(express.static(__dirname+"\\statics"));
//defining an endpoint for yahweh to get all the users
app.get("/users", (req, res) => {
if(req.session && req.session.email && req.session.role=="yahweh")
{
User.find()
.then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving users."
});
});}
});
//defining an endpoint for yahweh to delete all the users you can give a specific user's id but we're trying to do this really simply
app.delete("/delete", (req, res) => {
if(req.session && req.session.email && req.session.role=="yahweh")
{
User.remove({}).then(users => {res.send(users);}).catch(err => {
res.status(500).send({
message: err.message || "errooooor"
});
});}
});
//this is the route for the login page every time a user access ourappsdomain.com/login it will provide him with the login page
app.get("/login", (req, res) => {
res.sendFile(__dirname+"\\login.html");
}
);
//this is the route for the admin page it will check if there is a user connected with
//req.session&&req.session.email and also it will check if this user's role is yahweh or not if it's not he won't be able to access this route and will be redirected to the login page
app.get("/yahweh", (req, res) => {
if(req.session && req.session.email && req.session.role=="yahweh")
{
res.sendFile(__dirname+"\\admin.html");}
else{res.redirect('/login');}
});
//same thing for batman
app.get("/Batman", (req, res) => {
if(req.session && req.session.email && req.session.role=="batman")
{
res.sendFile(__dirname+"\\publish.html");}
else{res.redirect('/login');}
});
//and poor jeff he can only read
app.get("/Jeff", (req, res) => {
if(req.session && req.session.email && req.session.role=="Jeff")
{
res.sendFile(__dirname+"\\read.html");}
else{res.redirect('/login');}
});
//this is to redirect every user to his proper page if there is a session if not to the login page
app.get("/", (req, res) => {
if(req.session && req.session.email && req.session.role=="yahweh")
{
res.sendFile(__dirname+"\\admin.html");}
else{res.redirect('/login');}
if(req.session && req.session.email && req.session.role=="batman")
{
res.sendFile(__dirname+"\\publish.html");}
else{res.redirect('/login');}
if(req.session && req.session.email && req.session.role=="jeff")
{
res.sendFile(__dirname+"\\read.html");}
else{res.redirect('/login');}
});
//ok now here is the fun part after the user has submitted his login credentials we will check first if this user exists in our database
//if he does we will check for his role assgned to him at creation in our database and give the session his email and role and redirect him
//to his proper page
app.post("/login", (req, res) => {
var email = req.body.email;
var password = req.body.password;
User.findOne({email : email}).then(user => {
if(user&&user.role=="yahweh")
{
if(password==user.password){
req.session.email = email;
req.session.role = "yahweh";
res.redirect('/yahweh');}
}
if(user&&user.role=="batman"){
if(password==user.password){
req.session.email = email;
req.session.role = "batman";
res.redirect('/batman');
}
if(user&&user.role=="jeff"){
if(password==user.password){
req.session.email = email;
req.session.role = "jeff";
res.redirect('/jeff');
}
}
res.send("message");
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving users."
});
});
});
//if a user logs out we take his request to clear all the session data that we gave him previously and redirect him to the login page
//now if he tries to access the pages he will be redirected to the login page everytime because the request he is sending does not contain session data
app.get('/logout', function(req, res) {
req.session.destroy();
res.redirect('/login');
});
app.listen(9000, () => {
console.log("Server is listening on port 9000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment