-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
create basic auth in nodejs, jwt with mongoDB
- Loading branch information
Guisse Mamadou Cire
committed
Apr 8, 2022
0 parents
commit 6da469f
Showing
16 changed files
with
2,530 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
#SECRET=BDFSPM-secret-key | ||
# MongoDB | ||
MONGO_URL=mongodb://localhost:27017/test_auth | ||
|
||
# BACKEND | ||
HOST_API=127.0.0.1 | ||
PORT=8080 | ||
|
||
# User default admin self service | ||
USERNAME_ADMIN=admin | ||
PASSWORD_ADMIN=Admin2020@ | ||
EMAIL_ADMIN=[email protected] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
# See http://help.github.com/ignore-files/ for more about ignoring files. | ||
|
||
# compiled output | ||
/dist | ||
/tmp | ||
/out-ts | ||
/log | ||
/.lh | ||
/.history | ||
/.vscode | ||
|
||
# Only exists if Bazel was run or directory tmp | ||
/bazel-out | ||
/working | ||
/bdfuc | ||
# dependencies | ||
/node_modules | ||
|
||
# profiling files | ||
chrome-profiler-events*.json | ||
speed-measure-plugin*.json | ||
|
||
# IDEs and editors | ||
/.idea | ||
.project | ||
.classpath | ||
.c9/ | ||
*.launch | ||
.settings/ | ||
*.sublime-workspace | ||
|
||
# IDE - VSCode | ||
.vscode/* | ||
!.vscode/settings.json | ||
!.vscode/tasks.json | ||
!.vscode/launch.json | ||
!.vscode/extensions.json | ||
.history/* | ||
|
||
# misc | ||
/.sass-cache | ||
/connect.lock | ||
/coverage | ||
/libpeerconnection.log | ||
npm-debug.log | ||
yarn-error.log | ||
testem.log | ||
/typings | ||
|
||
# System Files | ||
.DS_Store | ||
Thumbs.db |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
module.exports = { | ||
secret: require('crypto').randomBytes(64).toString('hex'), | ||
jwtExpiration: 86400, // 24 hour | ||
jwtRefreshExpiration: '7d', // 7 days | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
|
||
module.exports ={ | ||
endpoint: '/api/REST/services', | ||
version: '/v1', | ||
// endpoint auth | ||
AUTH_BASE: '/oauth/token', | ||
AUTH_SIGNUP : '/signup', | ||
AUTH_SIGNIN: '/login', | ||
|
||
//endpoint user | ||
USER_BASE: '/user', | ||
USER_FIND_ALL: '/list', | ||
USER_CREATE: '/add', | ||
USER_FIND: '/get/:id', | ||
USER_UPDATE : '/edit/:id', | ||
USER_DELETE : '/delete/:id', | ||
FIND_ALL : '/all', | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
const db = require("../models/index"); | ||
var bcrypt = require("bcryptjs"); | ||
var log4js = require("log4js"); | ||
var logger = log4js.getLogger(); | ||
logger.level = "debug"; | ||
const Role = db.role; | ||
const User = db.user; | ||
|
||
const { | ||
USERNAME_ADMIN, | ||
PASSWORD_ADMIN, | ||
EMAIL_ADMIN | ||
} = process.env; | ||
|
||
module.exports = { | ||
initialyRoles, | ||
initialyUser | ||
}; | ||
|
||
function initialyRoles() { | ||
Role.estimatedDocumentCount((err, count) => { | ||
if (!err && count === 0) { | ||
new Role({ | ||
name: "user", | ||
}).save((err) => { | ||
if (err) { | ||
logger.error(err); | ||
} | ||
logger.info("Added 'user' to roles collection"); | ||
}); | ||
|
||
new Role({ | ||
name: "manager", | ||
}).save((err) => { | ||
if (err) { | ||
logger.error(err); | ||
} | ||
logger.info("Added 'manager' to roles collection"); | ||
}); | ||
|
||
new Role({ | ||
name: "ene", | ||
}).save((err) => { | ||
if (err) { | ||
logger.error(err); | ||
} | ||
logger.info("Added 'ene' to roles collections"); | ||
}); | ||
|
||
new Role({ | ||
name: "admin", | ||
}).save((err) => { | ||
if (err) { | ||
logger.error(err); | ||
} | ||
logger.info("Added 'admin' to roles collection"); | ||
}); | ||
} | ||
}); | ||
} | ||
|
||
async function initialyUser() { | ||
User.estimatedDocumentCount((err, count) => { | ||
if (count === 0 && !err) { | ||
const user = new User({ | ||
username: USERNAME_ADMIN, | ||
password: bcrypt.hashSync(PASSWORD_ADMIN, 8), | ||
email: EMAIL_ADMIN, | ||
}); | ||
user.save((err, user) => { | ||
if (err) { | ||
logger.error(err); | ||
} | ||
Role.find( | ||
{ | ||
name: { $in: ['admin'] }, | ||
}, | ||
(err, roles) => { | ||
if (err) { | ||
logger.error(err); | ||
} | ||
user.roles = roles.map((role) => role._id); | ||
user.save((err) => { | ||
if (err) { | ||
logger.error(err); | ||
} | ||
|
||
logger.info("Added 'admin' to user collection"); | ||
|
||
}); | ||
} | ||
); | ||
}); | ||
} | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
const config = require("../config/auth.config"); | ||
const db = require("../models"); | ||
const User = db.user; | ||
const Role = db.role; | ||
|
||
var jwt = require("jsonwebtoken"); | ||
var bcrypt = require("bcryptjs"); | ||
|
||
const fs = require("fs"); | ||
const path = require("path"); | ||
|
||
signup = (req, res) => { | ||
if (!req.body) { | ||
return res.status(400).json({ message: 'ERREUR : le body n\'est pas bien défini, veuillez vérifiez le body' }); | ||
} | ||
const user = new User({ | ||
username: req.body.username, | ||
email: req.body.email, | ||
password: bcrypt.hashSync(req.body.password, 8) | ||
}); | ||
|
||
user.save((err, user) => { | ||
if (err) { | ||
return res.status(500).json({ message: err }); | ||
} | ||
if (req.body.roles) { | ||
Role.find( | ||
{ | ||
name: { $in: req.body.roles } | ||
}, | ||
(err, roles) => { | ||
if (err) { | ||
return res.status(500).json({ message: err }); | ||
} | ||
|
||
user.roles = roles.map(role => role._id); | ||
user.save(err => { | ||
if (err) { | ||
return res.status(500).json({ message: err }); | ||
} | ||
return res.status(200).json({ message: `SUCCES : le compte ${user.username} a été créé avec succès ! ` }); | ||
}); | ||
} | ||
); | ||
} else { | ||
Role.findOne({ name: "user" }, (err, role) => { | ||
if (err) { | ||
return res.status(500).json({ message: err }); | ||
} | ||
|
||
user.roles = [role._id]; | ||
user.save(err => { | ||
if (err) { | ||
return res.status(500).json({ message: err }); | ||
} | ||
return res.status(201).json({ message: `SUCCES : le compte ${user.username} a été créé avec succès ! ` }); | ||
}); | ||
}); | ||
} | ||
}); | ||
}; | ||
|
||
|
||
basicAuth = async (req,res,next)=>{ | ||
var authHeader = req.headers.authorization; | ||
if (!authHeader) { | ||
var err = new Error('You are not authenticated!'); | ||
res.setHeader('WWW-Authenticate', 'Basic'); | ||
err.status = 401; | ||
return res.status(401).json(err); | ||
} | ||
var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':'); | ||
var username = auth[0]; | ||
var password = auth[1]; | ||
User.findOne({ | ||
username: username | ||
}).populate("roles", "-__v") | ||
.exec(function (err, user) { | ||
if (!user) { | ||
return res.status(404).json({ message: `ERREUR : le nom d\'utilisateur ou le mot de passe est incorrect` }); | ||
} else { | ||
if (!bcrypt.compareSync(password, user.password)) { | ||
return res.status(404).json({ | ||
message: `ERREUR : le nom d\'utilisateur ou le mot de passe est incorrect !` | ||
}); | ||
}else{ | ||
var token = jwt.sign({ id: user.id }, config.secret, { | ||
// algorithm: 'RS256', | ||
expiresIn: config.jwtExpiration, | ||
}); | ||
var authorities = []; | ||
for (let i = 0; i < user.roles.length; i++) { | ||
authorities.push("ROLE_" + user.roles[i].name.toUpperCase()); | ||
} | ||
res.status(200).json({ | ||
id: user._id, | ||
username: user.username, | ||
email: user.email, | ||
roles: authorities, | ||
accessToken: token | ||
}); | ||
} | ||
} | ||
}); | ||
|
||
}; | ||
|
||
module.exports = { | ||
signup, | ||
basicAuth | ||
} |
Oops, something went wrong.