Skip to content

Commit

Permalink
Fin sección 10 - Auth
Browse files Browse the repository at this point in the history
  • Loading branch information
AndradeWI committed Oct 5, 2020
1 parent 7bad947 commit c051d87
Show file tree
Hide file tree
Showing 13 changed files with 519 additions and 10 deletions.
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
PORT=3000
DB_CNN=mongodb+srv://izidro_user:pwA23v6MRzBOi6Mc@cluster0.w1sc3.mongodb.net/hospitaldb
DB_CNN=mongodb+srv://izidro_user:pwA23v6MRzBOi6Mc@cluster0.w1sc3.mongodb.net/hospitaldb
JWT_SECRET=dfjfdfkdsfnjdnf3432543634vmfvmkdsmvdfewiorwe0534nejfn#$%$##bhjhbj
54 changes: 54 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const { response } = require('express');
const bcrypt = require('bcryptjs');

const Usuario = require('../models/usuario');
const { gerarJWT } = require('../helpers/jwt');


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

const { email, password } = req.body;

try {

// Verificar email
const usuarioBD = await Usuario.findOne({ email });

if ( !usuarioBD ) {
return res.status(404).json({
ok: false,
msg: 'Email inválido'
});
}

// Verificar senha
const validPassword = bcrypt.compareSync( password, usuarioBD.password );

if ( !validPassword ) {
return res.status(400).json({
ok: 'false',
msg: 'Senha inválida'
});
}

// Gerar o TOKEN - JWT
const token = await gerarJWT( usuarioBD.id );

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

} catch (error) {
console.log(error);
res.status(500).json({
ok: false,
msg: 'Fale com o Administrador'
})
}

}

module.exports = {
login
}
146 changes: 146 additions & 0 deletions controllers/usuarios.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
const { response } = require('express');
const bcrypt = require('bcryptjs');

const Usuario = require('../models/usuario');
const { gerarJWT } = require('../helpers/jwt');


const getUsuarios = async(req, res) => {

const usuarios = await Usuario.find();

res.json({
ok: true,
usuarios
});

}

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

const { email, password, name } = req.body;

try {

const existeEmail = await Usuario.findOne({ email });

if ( existeEmail ) {
return res.status(400).json({
ok: false,
msg: 'O email já está registrado'
});
}

const usuario = new Usuario( req.body );

// Encriptar senha
const salt =bcrypt.genSaltSync();
usuario.password = bcrypt.hashSync( password, salt );

// Gravar usuário
await usuario.save();

// Gerar o TOKEN - JWT
const token = await gerarJWT( usuario.id );

res.json({
ok: true,
usuario,
token
});
} catch (error) {
console.log(error);
res.status(500).json({
ok: false,
msg: 'Erro inesperado... revisar logs'
});
}

}

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

// TODO: Validar token e comprovar se é o usuário correto

const uid = req.params.id;

try {

const usuarioDB = await Usuario.findById( uid );

if ( !usuarioDB ) {
return res.status(404).json({
ok: false,
msg: 'Não existe um usuário com esse id'
});
}

// Atualizações
const { password, google, email, ...campos } = req.body;

if ( usuarioDB.email !== email ) {

const existeEmail = await Usuario.findOne({ email });
if ( existeEmail ) {
return res.status(400).json({
ok: false,
msg: 'Já existe um usuário cadastrado com este email'
});
}
}

campos.email = email;
const usuarioAtualizado = await Usuario.findOneAndUpdate( uid, campos, { new: true } );

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

} catch (error) {
console.log(error);
res.status(500).json({
ok: false,
msg: 'Error inesperado'
});
}

}

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

const uid = req.params.id;

try {

const usuarioDB = await Usuario.findById( uid );

if ( !usuarioDB ) {
return res.status(404).json({
ok: false,
msg: 'Não existe um usuário com esse id'
});
}

await Usuario.findByIdAndDelete( uid );

res.json({
ok: true,
msg: 'Usuário excluído!'
})
} catch (error) {
console.log(error);
res.status(500).json({
ok: false,
msg: 'Fale com o administrador'
});
}

}

module.exports = {
getUsuarios,
crearUsuarios,
updateUser,
excluirUsuario,
}
3 changes: 2 additions & 1 deletion database/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ const dbConection = async() => {
await mongoose.connect( process.env.DB_CNN, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
useCreateIndex: true,
useFindAndModify: false
});

console.log('DB Online');
Expand Down
32 changes: 32 additions & 0 deletions helpers/jwt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

const jwt = require('jsonwebtoken');


const gerarJWT = ( uid ) => {

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

const payload = {
uid,
};

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

if ( err ) {
console.log(err);
reject('Não pode gerar o JWT');
}else {
resolve( token );
}

});

});

}

module.exports = {
gerarJWT,
}
13 changes: 5 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,15 @@ const app = express();
// Configurar CORS
app.use( cors() );

// Leitura e parse do body
app.use( express.json() );

// Base de dados
dbConection();


// Rotas
app.get( '/', (req, res) => {
res.json({
ok: true,
msg: 'Olá Mundo'
})
})

app.use( '/api/usuarios', require('./routes/usuarios.routes') );
app.use( '/api/login', require('./routes/auth.routes') );


app.listen( process.env.PORT, () => {
Expand Down
19 changes: 19 additions & 0 deletions middlewares/validar-campos.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { response } = require('express');
const { validationResult } = require('express-validator');

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

const errors = validationResult( req );

if ( !errors.isEmpty() ) {
return res.status(400).json({
ok: false,
errors: errors.mapped()
});
}
next();
}

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


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

// Ler o token
const token = req.header('x-token');
console.log(token);

if ( !token ) {
return res.status(401).json({
ok: false,
msg: 'Não possui token na requisição'
});
}

try {

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

next();

} catch (error) {
return res.status(401).json({
ok: false,
msg: 'Token inválido'
});
}

}


module.exports = {
validarJWT
}
39 changes: 39 additions & 0 deletions models/usuario.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const { Schema, model } = require('mongoose');


const UsuarioSchema = Schema({

name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
img: {
type: String,
},
role: {
type: String,
required: true,
default: 'USER_ROLE'
},
google: {
type: Boolean,
default: false
},
});

UsuarioSchema.method('toJSON', function() {
const { __v, _id, password, ...object } = this.toObject();
object.uid = _id;
return object;
})

module.exports = model( 'Usuario', UsuarioSchema );
Loading

0 comments on commit c051d87

Please sign in to comment.