Skip to content

added comments to the code, to understand better for newbies #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
31 changes: 24 additions & 7 deletions app/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Registration and Login controller

const config = require("../config/auth.config");
const db = require("../models");
const User = db.user;
@@ -6,31 +8,37 @@ const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");

// Registration logic
exports.signup = (req, res) => {
// create a user instance
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8)
});

user.save((err, user) => {
// if there is an error while creating a user instance
if (err) {
res.status(500).send({ message: err });
return;
}

// if the user request contains a specified role
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles }
},
(err, roles) => {
// if the role is not found
if (err) {
res.status(500).send({ message: err });
return;
}

// else save the role and map it to the respective role id
user.roles = roles.map(role => role._id);
// save the user
user.save(err => {
if (err) {
res.status(500).send({ message: err });
@@ -42,6 +50,7 @@ exports.signup = (req, res) => {
}
);
} else {
// this role is the default role of the application
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
@@ -62,7 +71,9 @@ exports.signup = (req, res) => {
});
};

// Login logic
exports.signin = (req, res) => {
// check if username exists in the server
User.findOne({
username: req.body.username
})
@@ -72,11 +83,13 @@ exports.signin = (req, res) => {
res.status(500).send({ message: err });
return;
}


// if user does not exist in the server
if (!user) {
return res.status(404).send({ message: "User Not found." });
}


// compare the provided password to the password in the server
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
@@ -88,16 +101,20 @@ exports.signin = (req, res) => {
message: "Invalid Password!"
});
}


// create token
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400 // 24 hours
});


// create authorities array: a new name for all the roles in the roles array after adding the prefix..
var authorities = [];


// for each role in the roles array, add the prefix ROLE_, and convert the role name to uppercase
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
// return the user details
res.status(200).send({
id: user._id,
username: user.username,
10 changes: 10 additions & 0 deletions app/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
// Controller for testing Authorization..

// It contains four functions:

// allAccess for public access
// userBoard for loggedin users (any role)
// adminBoard for moderator users
// moderatorBoard for admin users


exports.allAccess = (req, res) => {
res.status(200).send("Public Content.");
};
3 changes: 3 additions & 0 deletions app/middlewares/authJwt.js
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ const db = require("../models");
const User = db.user;
const Role = db.role;

// token is obtained from the http header and verified
verifyToken = (req, res, next) => {
let token = req.headers["x-access-token"];

@@ -20,6 +21,7 @@ verifyToken = (req, res, next) => {
});
};

// check if user role is an admin..
isAdmin = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
@@ -51,6 +53,7 @@ isAdmin = (req, res, next) => {
});
};

// check if user role is a manager..
isModerator = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
8 changes: 5 additions & 3 deletions app/middlewares/verifySignUp.js
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@ const ROLES = db.ROLES;
const User = db.user;

checkDuplicateUsernameOrEmail = (req, res, next) => {
// Username
// check if Username exist in the server.
User.findOne({
username: req.body.username
}).exec((err, user) => {
@@ -17,7 +17,7 @@ checkDuplicateUsernameOrEmail = (req, res, next) => {
return;
}

// Email
// Check if Email exist in the server.
User.findOne({
email: req.body.email
}).exec((err, user) => {
@@ -35,10 +35,12 @@ checkDuplicateUsernameOrEmail = (req, res, next) => {
});
});
};

// check if the role the user choose exists in the server.
checkRolesExisted = (req, res, next) => {
if (req.body.roles) {
// loop through the roles array
for (let i = 0; i < req.body.roles.length; i++) {
// if role specified is not in the roles array
if (!ROLES.includes(req.body.roles[i])) {
res.status(400).send({
message: `Failed! Role ${req.body.roles[i]} does not exist!`
6 changes: 4 additions & 2 deletions app/routes/auth.routes.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Authorization routes

const { verifySignUp } = require("../middlewares");
const controller = require("../controllers/auth.controller");

@@ -9,7 +11,7 @@ module.exports = function(app) {
);
next();
});

// Signup route
app.post(
"/api/auth/signup",
[
@@ -18,6 +20,6 @@ module.exports = function(app) {
],
controller.signup
);

// Login route
app.post("/api/auth/signin", controller.signin);
};
5 changes: 4 additions & 1 deletion app/routes/user.routes.js
Original file line number Diff line number Diff line change
@@ -9,17 +9,20 @@ module.exports = function(app) {
);
next();
});

// Get contents for public
app.get("/api/test/all", controller.allAccess);

// Get contents for all users
app.get("/api/test/user", [authJwt.verifyToken], controller.userBoard);

// Get contents for moderators
app.get(
"/api/test/mod",
[authJwt.verifyToken, authJwt.isModerator],
controller.moderatorBoard
);

// Get contents for admin
app.get(
"/api/test/admin",
[authJwt.verifyToken, authJwt.isAdmin],