Skip to content

Commit

Permalink
JWT implementado
Browse files Browse the repository at this point in the history
  • Loading branch information
Klerith committed Feb 6, 2021
1 parent 76fae7a commit 50f402a
Show file tree
Hide file tree
Showing 13 changed files with 338 additions and 7 deletions.
1 change: 1 addition & 0 deletions .example.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
PORT=8080
MONGODB_CNN=
SECRETORPRIVATEKEY=
59 changes: 59 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const { response } = require('express');
const bcryptjs = require('bcryptjs')

const Usuario = require('../models/usuario');

const { generarJWT } = require('../helpers/generar-jwt');


const login = async(req, res = response) => {

const { correo, password } = req.body;

try {

// Verificar si el email existe
const usuario = await Usuario.findOne({ correo });
if ( !usuario ) {
return res.status(400).json({
msg: 'Usuario / Password no son correctos - correo'
});
}

// SI el usuario está activo
if ( !usuario.estado ) {
return res.status(400).json({
msg: 'Usuario / Password no son correctos - estado: false'
});
}

// Verificar la contraseña
const validPassword = bcryptjs.compareSync( password, usuario.password );
if ( !validPassword ) {
return res.status(400).json({
msg: 'Usuario / Password no son correctos - password'
});
}

// Generar el JWT
const token = await generarJWT( usuario.id );

res.json({
usuario,
token
})

} catch (error) {
console.log(error)
res.status(500).json({
msg: 'Hable con el administrador'
});
}

}



module.exports = {
login
}
6 changes: 1 addition & 5 deletions controllers/usuarios.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,9 @@ const usuariosPatch = (req, res = response) => {
const usuariosDelete = async(req, res = response) => {

const { id } = req.params;

// Fisicamente lo borramos
// const usuario = await Usuario.findByIdAndDelete( id );

const usuario = await Usuario.findByIdAndUpdate( id, { estado: false } );


res.json(usuario);
}

Expand Down
32 changes: 32 additions & 0 deletions helpers/generar-jwt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const jwt = require('jsonwebtoken');



const generarJWT = ( uid = '' ) => {

return new Promise( (resolve, reject) => {

const payload = { uid };

jwt.sign( payload, process.env.SECRETORPRIVATEKEY, {
expiresIn: '4h'
}, ( err, token ) => {

if ( err ) {
console.log(err);
reject( 'No se pudo generar el token' )
} else {
resolve( token );
}
})

})
}




module.exports = {
generarJWT
}

11 changes: 11 additions & 0 deletions middlewares/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@


const validaCampos = require('../middlewares/validar-campos');
const validarJWT = require('../middlewares/validar-jwt');
const validaRoles = require('../middlewares/validar-roles');

module.exports = {
...validaCampos,
...validarJWT,
...validaRoles,
}
56 changes: 56 additions & 0 deletions middlewares/validar-jwt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const { response, request } = require('express');
const jwt = require('jsonwebtoken');

const Usuario = require('../models/usuario');


const validarJWT = async( req = request, res = response, next ) => {

const token = req.header('x-token');

if ( !token ) {
return res.status(401).json({
msg: 'No hay token en la petición'
});
}

try {

const { uid } = jwt.verify( token, process.env.SECRETORPRIVATEKEY );

// leer el usuario que corresponde al uid
const usuario = await Usuario.findById( uid );

if( !usuario ) {
return res.status(401).json({
msg: 'Token no válido - usuario no existe DB'
})
}

// Verificar si el uid tiene estado true
if ( !usuario.estado ) {
return res.status(401).json({
msg: 'Token no válido - usuario con estado: false'
})
}


req.usuario = usuario;
next();

} catch (error) {

console.log(error);
res.status(401).json({
msg: 'Token no válido'
})
}

}




module.exports = {
validarJWT
}
49 changes: 49 additions & 0 deletions middlewares/validar-roles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const { response } = require('express')


const esAdminRole = ( req, res = response, next ) => {

if ( !req.usuario ) {
return res.status(500).json({
msg: 'Se quiere verificar el role sin validar el token primero'
});
}

const { rol, nombre } = req.usuario;

if ( rol !== 'ADMIN_ROLE' ) {
return res.status(401).json({
msg: `${ nombre } no es administrador - No puede hacer esto`
});
}

next();
}


const tieneRole = ( ...roles ) => {
return (req, res = response, next) => {

if ( !req.usuario ) {
return res.status(500).json({
msg: 'Se quiere verificar el role sin validar el token primero'
});
}

if ( !roles.includes( req.usuario.rol ) ) {
return res.status(401).json({
msg: `El servicio requiere uno de estos roles ${ roles }`
});
}


next();
}
}



module.exports = {
esAdminRole,
tieneRole
}
4 changes: 4 additions & 0 deletions models/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ class Server {
constructor() {
this.app = express();
this.port = process.env.PORT;

this.usuariosPath = '/api/usuarios';
this.authPath = '/api/auth';

// Conectar a base de datos
this.conectarDB();
Expand Down Expand Up @@ -39,6 +41,8 @@ class Server {
}

routes() {

this.app.use( this.authPath, require('../routes/auth'));
this.app.use( this.usuariosPath, require('../routes/usuarios'));
}

Expand Down
3 changes: 2 additions & 1 deletion models/usuario.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ const UsuarioSchema = Schema({


UsuarioSchema.methods.toJSON = function() {
const { __v, password, ...usuario } = this.toObject();
const { __v, password, _id, ...usuario } = this.toObject();
usuario.uid = _id;
return usuario;
}

Expand Down
91 changes: 91 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.9.2",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.15"
}
}
Loading

0 comments on commit 50f402a

Please sign in to comment.