Skip to content

Commit

Permalink
Usuario y token listo
Browse files Browse the repository at this point in the history
  • Loading branch information
estudiobarragan committed Oct 18, 2019
1 parent 401c5bf commit fd1cb70
Show file tree
Hide file tree
Showing 9 changed files with 409 additions and 9 deletions.
26 changes: 18 additions & 8 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,29 @@ var port = process.env.PORT || 3000; */
// requires
var express = require('express');
const mongoose = require("mongoose");
var bodyParser = require('body-parser');

// Inicializar variables
var app = express();

// Body Parser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// mongo cloud
const port = process.env.PORT || 3000;
const MC_url = "mongodb+srv://pablo:[email protected]/backend";
const MC_url = "mongodb+srv://pablo:[email protected]/hospitalDB";

// Importar rutas
var appRoutes = require('./routes/app');
var usuarioRoutes = require('./routes/usuario');
var loginRoutes = require('./routes/login');

app.use('/usuario', usuarioRoutes);
app.use('/login', loginRoutes);
app.use('/', appRoutes);

// Rutas
app.get('/', (req, res, next) => {
res.status(403).send({
ok: true,
mensaje: 'Peticion realizada correctamente'
})
})

mongoose.Promise = global.Promise;
mongoose.connect(MC_url, {
Expand Down
1 change: 1 addition & 0 deletions config/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports.SEED = '@este-es@mi-seed-secreto';
28 changes: 28 additions & 0 deletions middlewares/autenticacion.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict'
'use esversion: 6 '

var jwt = require('jsonwebtoken');

var SEED = require('../config/config').SEED;


/*
Verificar token
*/
exports.verificaToken = function(req, res, next) {
var token = req.query.token;

jwt.verify(token, SEED, (err, decoded) => {
if (err) {
return res.status(401).send({
ok: false,
mensaje: 'Token incorrecto',
errors: err
});
}
req.usuario = decoded.usuario;
next();
});
}
21 changes: 21 additions & 0 deletions models/usuario.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
var moongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');

var Schema = moongoose.Schema;

var rolesValidos = {
values: ['ADMIN_ROLE', 'USER_ROLE'],
message: '{VALUE} no es un rol permitido'
}

var usuarioSchema = new Schema({
'nombre': { type: String, required: [true, 'El nombre es obligatorio'] },
'correo': { type: String, unique: true, required: [true, 'El correo es obligatorio'] },
'clave': { type: String, required: [true, 'La clave de acceso es obligatorio'] },
'img': { type: String, required: [false] },
'role': { type: String, required: true, default: 'USER_ROLE', enum: rolesValidos }
});

usuarioSchema.plugin(uniqueValidator, { message: "El campo {PATH}, debe ser unico" });

module.exports = moongoose.model('Usuario', usuarioSchema);
115 changes: 115 additions & 0 deletions package-lock.json

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

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
"author": "Jose Maria Barragan",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.7.5"
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.7.5",
"mongoose-unique-validator": "^2.0.3"
}
}
15 changes: 15 additions & 0 deletions routes/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict'

var express = require('express');
var app = express();


// Rutas
app.get('/', (req, res, next) => {
res.status(403).send({
ok: true,
mensaje: 'Peticion realizada correctamente'
})
});

module.exports = app;
54 changes: 54 additions & 0 deletions routes/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use strict'

var express = require('express');
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');

var SEED = require('../config/config').SEED;
var app = express();
var Usuario = require('../models/usuario');

app.post('/', (req, res) => {
var body = req.body;

Usuario.findOne({ correo: body.correo }, (err, usuarioDB) => {
if (err) {
return res.status(500).send({
ok: false,
mensaje: 'Error al buscar el usuario',
errors: err
});
}
if (!usuarioDB) {
return res.status(400).send({
ok: false,
mensaje: 'Login incorrecto.',
errors: { message: "# No existe un usuario con ese correo electronico" }
});
}

if (!bcrypt.compareSync(body.clave, usuarioDB.clave)) {
return res.status(400).send({
ok: false,
mensaje: 'Login incorrecto.',
errors: { message: "# La clave es incorrecta" }
});
}
// La clave no se integra al token del usuario
usuarioDB.clave = ':-;';

// Crear un token
var token = jwt.sign({ usuario: usuarioDB }, SEED, { expiresIn: 14400 }); //4 horas

return res.status(200).send({
ok: true,
usuario: usuarioDB,
token,
id: usuarioDB.id
});
})

});


module.exports = app;
Loading

0 comments on commit fd1cb70

Please sign in to comment.