Skip to content

Commit

Permalink
usuario y token listo
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsasoAguirre committed Jan 25, 2020
1 parent e67833b commit 59c1e70
Show file tree
Hide file tree
Showing 9 changed files with 432 additions and 10 deletions.
26 changes: 17 additions & 9 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
// Requires
var express = require('express');
var mongoose = require('mongoose')
var 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())


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

// Conexion a la base de datos
mongoose.connection.openUri('mongodb://localhost:27017/hospitalDB', (err, res) => {
if (err) throw err;
Expand All @@ -14,14 +27,9 @@ mongoose.connection.openUri('mongodb://localhost:27017/hospitalDB', (err, res) =
})

// Rutas
app.get('/', (req, res, next) => {

res.status(200).json({
ok: true,
mensaje: 'Peticion realizada correctamente'
})
});

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

//Escuchar peticiones
app.listen(3000, () => {
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@-un-seed-absurdo';
25 changes: 25 additions & 0 deletions middelwares/autentication.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
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).json({
ok: false,
mensaje: 'Token no valido',
errors: err
});
}
req.usuario = decoded.usuario;
next();
// res.status(200).json({
// ok: true,
// decode: decoded
// });
})
}
44 changes: 44 additions & 0 deletions models/usuario.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');

var Schema = mongoose.Schema;


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

var usuarioSchema = new Schema({

nombre: {
type: String,
required: [true, 'El nombre es obligatorio']
},

email: {
type: String,
unique: true,
required: [true, 'El email es obligatorio']
},

password: {
type: String,
required: [true, 'La contraseña es obligatoria']
},

img: {
type: String,
required: false
},

role: {
type: String,
required: true,
default: 'USER_ROLE',
enum: rolesValidos,
}
});

usuarioSchema.plugin(uniqueValidator, { message: '{PATH} debe ser único' })
module.exports = mongoose.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,8 +10,12 @@
"author": "Itsaso Aguirre",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.8.9"
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.8.9",
"mongoose-unique-validator": "^2.0.3"
},
"devDependencies": {
"nodemon": "^2.0.2"
Expand Down
13 changes: 13 additions & 0 deletions routes/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var express = require('express');

var app = express();

app.get('/', (req, res, next) => {

res.status(200).json({
ok: true,
mensaje: 'Peticion realizada correctamente'
})
});

module.exports = app;
61 changes: 61 additions & 0 deletions routes/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
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({ email: body.email }, (err, usuarioBD) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error al buscar usuario',
errors: err
});
}

// Evaluar si existe ese ususario

if (!usuarioBD) {
return res.status(400).json({
ok: false,
// TODO: quitar -email, es solo para comprbar que falla en desarrollo
mensaje: 'Credenciales incorrectas - email',
errors: err
});
}

//Validamos que la contraseña sea correcta
if (!bcrypt.compareSync(body.password, usuarioBD.password)) {
return res.status(400).json({
ok: false,
mensaje: 'Credenciales incorrectas - password',
errors: err
});
}

//Crear un token
usuarioBD.password = ':)';

var token = jwt.sign({ usuario: usuarioBD }, SEED, { expiresIn: 14400 }) //4 horas

res.status(200).json({
ok: true,
usuario: usuarioBD,
token: token,
id: usuarioBD.id
})

});

});

module.exports = app;
Loading

0 comments on commit 59c1e70

Please sign in to comment.