Skip to content

Commit

Permalink
Agregada generacion de jwt
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucas Serrey committed Dec 11, 2019
1 parent 3fd5b3d commit 6757f66
Show file tree
Hide file tree
Showing 9 changed files with 247 additions and 12 deletions.
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 @@ -13,6 +13,7 @@
"bcrypt": "^3.0.7",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.7.14",
"mongoose-unique-validator": "^2.0.3",
"underscore": "^1.9.1"
Expand Down
11 changes: 11 additions & 0 deletions server/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ process.env.PORT = process.env.PORT || 3000
// =========================
process.env.NODE_ENV = process.env.NODE_ENV || 'dev';

// =========================
// VENCIMIENTO DEL TOKEN
// =========================
process.env.TOKEN_EXPIRE = 60 * 60 * 24 * 30;

// =========================
// SEED
// =========================
process.env.SEED = process.env.SEED || 'el-secret-local';


// =========================
// Base de Datos
// =========================
Expand Down
54 changes: 54 additions & 0 deletions server/middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const jwt = require('jsonwebtoken');

// =========================
// Verifica Token
// =========================
let verificaToken = (req, res, next) => {

let token = req.get('token');

jwt.verify(token, process.env.SEED, (err, decoded) => {

if (err) {
return res.status(401).json({
ok: false,
err: {
message: 'Token no válido'
}
});
}

req.usuario = decoded.usuario;
next();

});
};

// =========================
// Verifica AdminRole
// =========================
let verificaAdminRole = (req, res, next) => {

usuario = req.usuario;

if(usuario.role != 'ADMIN_ROLE'){

res.json({
ok: false,
err: {
message: 'Debe ser administrador'
}
});
}
else{

next();
}

};


module.exports = {
verificaToken,
verificaAdminRole
}
9 changes: 9 additions & 0 deletions server/models/usuario.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ let usuarioSchema = new Schema({
}
});

// Excluir atributos
usuarioSchema.methods.toJSON = function () {

let userObject = this.toObject();
delete userObject.password;
delete userObject.__v;
return userObject;
}

usuarioSchema.plugin( uniqueValidator, {
message: '{PATH} debe ser unico'
});
Expand Down
7 changes: 7 additions & 0 deletions server/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const express = require('express');
const app = express();

app.use(require('./usuario'));
app.use(require('./login'));

module.exports = app;
56 changes: 56 additions & 0 deletions server/routes/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

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

const app = express();

app.post('/login', (req,res) => {

let body = req.body;

Usuario.findOne({email: body.email}, (err, usuarioDB) => {

if (err) {
return res.status(500).json({
ok: false,
err
});
}

if(!usuarioDB){
return res.status(400).json({
ok: false,
err: {
message: '(Usuario) o contraseña incorrectos'
}
});
}

if( !bcrypt.compareSync( body.password, usuarioDB.password) ){
return res.status(400).json({
ok: false,
err: {
message: 'Usuario o (contraseña) incorrectos'
}
});
}

let token = jwt.sign({
usuario: usuarioDB
}, process.env.SEED, { expiresIn: process.env.TOKEN_EXPIRE }) // 30 dias

res.json({
ok: true,
usuario: usuarioDB,
token
});
});



});


module.exports = app;
15 changes: 10 additions & 5 deletions server/routes/usuario.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ const _ = require('underscore');

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

const { verificaToken, verificaAdminRole } = require('../middlewares/auth');

const app = express();


app.get('/usuario', function (req, res) {
app.get('/usuario', verificaToken, (req, res) => {

let desde = Number(req.query.desde) || 0;
let limite = Number(req.query.limite) || 5;
Expand Down Expand Up @@ -37,7 +39,7 @@ app.get('/usuario', function (req, res) {

});

app.post('/usuario', function (req, res) {
app.post('/usuario', [verificaToken, verificaAdminRole], (req, res) => {

let body = req.body;

Expand Down Expand Up @@ -68,16 +70,19 @@ app.post('/usuario', function (req, res) {

})

app.put('/usuario/:id', function (req, res) {
app.put('/usuario/:id', [verificaToken, verificaAdminRole], (req, res) => {

let id = req.params.id;
let id = req.params.id;
let body = _.pick(req.body, ['nombre', 'email', 'img', 'role', 'estado'] );

// delete body.password;
// delete body.google;
//console.log(body);

Usuario.findByIdAndUpdate(id, body,{ new: true, runValidators: true }, (err, usuarioDB) => {

console.log(usuarioDB);

if (err) {
return res.status(400).json({
ok: false,
Expand All @@ -92,7 +97,7 @@ app.put('/usuario/:id', function (req, res) {
});
})

app.delete('/usuario/:id', function (req, res) {
app.delete('/usuario/:id', [verificaToken, verificaAdminRole], (req, res) => {

let id = req.params.id;

Expand Down
15 changes: 8 additions & 7 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,22 @@ app.use(bodyParser.urlencoded({ extended: false}));
// parse application/json
app.use(bodyParser.json());

// Incluyo archivo con las rutas del usuario
app.use( require('./routes/usuario'));
// Incluyo las rutas
app.use(require('./routes/index'));

//Conexion a DB
// lucas: V7QZDXveXxwkst1l
// mongodb+srv://lucas:[email protected]/cafe

//console.log( process.env.URLDB );

mongoose.connect(process.env.URLDB, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true},
(err, res) => {
mongoose.connect(process.env.URLDB,
{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false},
(err, res) => {

if(err) throw new err;
console.log('Base de datos ONLINE!');
if(err) throw new err;
console.log('Base de datos ONLINE!');
});


app.listen(process.env.PORT, () => { console.log(`Escuchando el puerto ${process.env.PORT}`); })
app.listen(process.env.PORT, () => { console.log(`Escuchando el puerto ${ process.env.PORT }`); })

0 comments on commit 6757f66

Please sign in to comment.