Skip to content

Instantly share code, notes, and snippets.

@fob2257
Created November 9, 2018 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fob2257/e56106ca36bd83e5c9e8a5459cb823e4 to your computer and use it in GitHub Desktop.
Save fob2257/e56106ca36bd83e5c9e8a5459cb823e4 to your computer and use it in GitHub Desktop.
Auth con JWT en Express
// npm i -S dotenv uuid express cors bcryptjs jsonwebtoken body-parser
require('dotenv').config();
const fs = require('fs');
const http = require('http');
const cors = require('cors');
const uuidv4 = require('uuid/v4');
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const salt = 10;
const host = process.env.HOST || '127.0.0.1';
const port = process.env.PORT || 3000;
const secret = process.env.JWT_SECRET || 'NeverTellYourSecrets';
const app = express();
const server = http.createServer(app);
/**
* Utils
*/
let listaUsuarios = (() => {
try {
return JSON.parse(fs.readFileSync('./usuarios.json', 'utf8'));
} catch (error) {
return [];
}
})();
const updateUsuarios = obj => fs.writeFileSync('./usuarios.json', JSON.stringify(obj), 'utf8');
const hashPassword = async (pwd) => {
try {
return await bcrypt.hash(pwd, salt);
} catch (error) {
throw error;
}
};
const comparePassword = async (pwd, hash) => {
try {
return await bcrypt.compare(pwd, hash);
} catch (error) {
throw error;
}
};
const generateJWT = (payload, expiresIn) => jwt.sign(payload, secret, { expiresIn });
const verifyJWT = token => jwt.verify(token, secret);
/** ************ */
/**
* Middlewares
*/
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
const checkJWT = (req, res, next) => {
try {
const { authorization } = req.headers;
const decoded = verifyJWT(authorization.split(' ')[1]);
const [usuario] = listaUsuarios.filter(u => u.id === decoded.id);
if (!usuario || !usuario.activo) {
throw Error();
}
req.usuario = usuario;
next();
} catch (error) {
return res.status(401).send({ message: 'Unauthorized' });
}
};
/** ************ */
/**
* Routes
*/
app.post('/signup', async (req, res) => {
try {
const {
nombre,
apellido,
email = undefined,
} = req.body;
let { password = undefined } = req.body;
if (!email || !password) {
return res.status(400).json({
message: 'debe de ingresar un email y password para registrarse',
});
}
const emailUsed = listaUsuarios.filter(u => u.email === email);
if (emailUsed.length > 0) {
return res.status(400).json({
message: 'email ya está siendo utilizado',
});
}
password = await hashPassword(password);
listaUsuarios = [
...listaUsuarios,
{
id: uuidv4(),
nombre,
apellido,
email,
password,
activo: true,
createdAt: new Date(),
}
];
updateUsuarios(listaUsuarios);
res.status(201).json('Registro exitoso!');
} catch (error) {
console.log(error);
res.status(500).json(error);
}
});
app.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
const [usuario] = listaUsuarios.filter(u => u.email === email);
if (!usuario) {
return res.status(404).json({
message: 'email no fue encontrado',
});
}
if (usuario.activo == false) {
return res.status(400).json({
message: 'usuario se encuentra desactivado',
});
}
const match = await comparePassword(password, usuario.password);
if (!match) {
return res.status(400).json({
message: 'password incorrecto',
});
}
const tokenTTL = `${1000 * 60 * 60 * 1}ms`; // 1 hora
const token = generateJWT({
id: usuario.id,
nombre: usuario.nombre,
apellido: usuario.apellido,
email,
}, tokenTTL);
res.json({ token });
} catch (error) {
console.log(error);
res.status(500).json(error);
}
});
app.get('/info', checkJWT, (req, res) => res.json(req.usuario));
/** ************ */
server.listen(port, host, () => {
console.log(`jwt-pass app listening on ${host}:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment