Skip to content
Open
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
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
POSTGRES_URI=postgres://postgres:admin@localhost:5432/testdb
SESSION_SECRET=bezkoder-secret-key
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ For more detail, please visit:
Working with Front-end:
> [Vue.js JWT Authentication with Vuex and Vue Router](https://bezkoder.com/jwt-vue-vuex-authentication/)

> [Angular 8 JWT Authentication with HttpInterceptor and Router](https://bezkoder.com/angular-jwt-authentication/)
> [Angular 8 JWT Authentication example](https://bezkoder.com/angular-jwt-authentication/)

> [Angular 10 JWT Authentication with HttpInterceptor and Router](https://bezkoder.com/angular-10-jwt-auth/)
> [Angular 10 JWT Authentication example](https://bezkoder.com/angular-10-jwt-auth/)

> [Angular 11 JWT Authentication example](https://bezkoder.com/angular-11-jwt-auth/)

> [React JWT Authentication & Authorization (without Redux) example](https://bezkoder.com/react-jwt-auth/)

Expand Down
3 changes: 0 additions & 3 deletions app/config/auth.config.js

This file was deleted.

4 changes: 0 additions & 4 deletions app/config/db.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
module.exports = {
HOST: "localhost",
USER: "postgres",
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i just added string in connection that's why i removed

PASSWORD: "123",
DB: "testdb",
dialect: "postgres",
pool: {
max: 5,
Expand Down
129 changes: 67 additions & 62 deletions app/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,87 +1,92 @@
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const db = require("../models");
const config = require("../config/auth.config");
const User = db.user;
const Role = db.role;

const Op = db.Sequelize.Op;

var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");

exports.signup = (req, res) => {
exports.signup = async (req, res) => {
// Save User to Database
User.create({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8)
})
.then(user => {
try {
const user = await User.create({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 10)
});
if (user) {
if (req.body.roles) {
Role.findAll({
const role = await Role.findAll({
where: {
name: {
[Op.or]: req.body.roles
}
}
}).then(roles => {
user.setRoles(roles).then(() => {
res.send({ message: "User registered successfully!" });
});
});
if (role) {
await user.setRoles(roles)
res.send({ message: "User registered successfully!" });
}

} else {
// user role = 1
user.setRoles([1]).then(() => {
res.send({ message: "User registered successfully!" });
});
}
})
.catch(err => {
res.status(500).send({ message: err.message });
});
};
const setRoles = await user.setRoles([1]);
res.send({ message: "User registered successfully!" });

exports.signin = (req, res) => {
User.findOne({
where: {
username: req.body.username
}
})
.then(user => {
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
}

var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
} catch (err) {
res.status(500).send({ message: err.message });
}

if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});

};

exports.signin = async (req, res) => {

try {
const user = await User.findOne({
where: {
username: req.body.username
}
});
if (!user) {
return res.status(404).send({ message: "User Not found." });
}

var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400 // 24 hours
});
const passwordIsValid = await bcrypt.compareSync(
req.body.password,
user.password
);

var authorities = [];
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
authorities.push("ROLE_" + roles[i].name.toUpperCase());
}
res.status(200).send({
id: user.id,
username: user.username,
email: user.email,
roles: authorities,
accessToken: token
});
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});
})
.catch(err => {
res.status(500).send({ message: err.message });
}

const token = await jwt.sign({ id: user.id }, process.env.SESSION_SECRET, {
expiresIn: 86400 // 24 hours
});
};

const authorities = [];
const roles = await user.getRoles()
if (roles) {
for (let i = 0; i < roles.length; i++) {
authorities.push("ROLE_" + roles[i].name.toUpperCase());
}
res.status(200).send({
id: user.id,
username: user.username,
email: user.email,
roles: authorities,
accessToken: token
});
}
} catch (err) {
res.status(500).send({ message: err.message });
}

}
60 changes: 33 additions & 27 deletions app/middleware/authJwt.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");
const db = require("../models");
const User = db.user;

verifyToken = (req, res, next) => {
verifyToken = async (req, res, next) => {

let token = req.headers["x-access-token"];

if (!token) {
Expand All @@ -12,7 +12,7 @@ verifyToken = (req, res, next) => {
});
}

jwt.verify(token, config.secret, (err, decoded) => {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added secret from env file

jwt.verify(token, process.env.SESSION_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({
message: "Unauthorized!"
Expand All @@ -23,44 +23,51 @@ verifyToken = (req, res, next) => {
});
};

isAdmin = (req, res, next) => {
User.findByPk(req.userId).then(user => {
user.getRoles().then(roles => {
isAdmin = async (req, res, next) => {
const user = await User.findByPk(req.userId);
if (user) {
const roles = await user.getRoles();
if (roles) {
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "admin") {
next();
return;
}
}

res.status(403).send({
message: "Require Admin Role!"
});
return;
});
});
};
}
}
}

isModerator = async (req, res, next) => {

isModerator = (req, res, next) => {
User.findByPk(req.userId).then(user => {
user.getRoles().then(roles => {
const user = await User.findByPk(req.userId);
if (user) {
const roles = await user.getRoles();
if (roles) {
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
return;
}
}

res.status(403).send({
message: "Require Moderator Role!"
});
});
});
};
}

}
}

isModeratorOrAdmin = (req, res, next) => {
User.findByPk(req.userId).then(user => {
user.getRoles().then(roles => {
isModeratorOrAdmin = async (req, res, next) => {

const user = await User.findByPk(req.userId);
if (user) {
const roles = await user.getRoles();
if (roles) {
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
Expand All @@ -71,14 +78,13 @@ isModeratorOrAdmin = (req, res, next) => {
next();
return;
}
res.status(403).send({
message: "Require Moderator or Admin Role!"
});
}

res.status(403).send({
message: "Require Moderator or Admin Role!"
});
});
});
};
}
}
}

const authJwt = {
verifyToken: verifyToken,
Expand Down
49 changes: 23 additions & 26 deletions app/middleware/verifySignUp.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,35 @@ const db = require("../models");
const ROLES = db.ROLES;
const User = db.user;

checkDuplicateUsernameOrEmail = (req, res, next) => {
checkDuplicateUsernameOrEmail = async (req, res, next) => {
// Username
User.findOne({
const user = await User.findOne({
where: {
username: req.body.username
}
}).then(user => {
if (user) {
res.status(400).send({
message: "Failed! Username is already in use!"
});
return;
}

// Email
User.findOne({
where: {
email: req.body.email
}
}).then(user => {
if (user) {
res.status(400).send({
message: "Failed! Email is already in use!"
});
return;
}

next();
});
if (user) {
res.status(400).send({
message: "Failed! Username is already in use!"
});
return;
}

// Email
const isfind = await User.findOne({
where: {
email: req.body.email
}
});
};
if (isfind) {
res.status(400).send({
message: "Failed! Email is already in use!"
});
return;
}
next();
}


checkRolesExisted = (req, res, next) => {
if (req.body.roles) {
Expand All @@ -45,7 +43,6 @@ checkRolesExisted = (req, res, next) => {
}
}
}

next();
};

Expand Down
10 changes: 3 additions & 7 deletions app/models/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
const config = require("../config/db.config.js");

const Sequelize = require("sequelize");

const sequelize = new Sequelize(
config.DB,
config.USER,
config.PASSWORD,
process.env.POSTGRES_URI,
{
host: config.HOST,
dialect: config.dialect,
operatorsAliases: false,

operatorsAliases: 0,
pool: {
max: config.pool.max,
min: config.pool.min,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"bcrypt": "^5.0.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"pg": "^7.17.1",
Expand Down
Loading