Skip to content

Instantly share code, notes, and snippets.

@annetyy
Created July 11, 2019 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save annetyy/872d4614d17cb646c22c1f32a2eccd3e to your computer and use it in GitHub Desktop.
Save annetyy/872d4614d17cb646c22c1f32a2eccd3e to your computer and use it in GitHub Desktop.
const jwt = require('jsonwebtoken');
const authHashConfig = require('../config/auth.json');
module.exports = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).send({error: 'No token provided'});
const parts = authHeader.split(' '); // separar pelos espaços p pegar o barrer
// dividiu e tem 2 partes?
if (!parts.lenght === 2) {
return res.status(401).send({error: 'Token error'});
}
const [scheme, token] = parts;
// verificar se tem bearer escrito
// regex, pq pode ter mais q bearer
// começa com bearer?
// [!] negação, [/] começa regex, [^] inicio, var, [$] final, i case sensetive
if (!/^Bearer$/i.test(scheme)) {
return res.status(401).send({error: 'Token malformatted'});
}
// agora a verificação pesada, essas de cima são pra deixar o back suave
jwt.verify(token, authHashConfig, (err, decoded) => {
if (err) return res.status(401).send({error: 'Token invalid'});
req.userId = decoded.id;
// ta habilitado pra ir pro controller
return next();
});
};
{
"secret": "MUAHAHAHAHAHAHAHAHAHA"
}
const {User} = require('../models/');
const Sequelize = require('sequelize');
const op = Sequelize.Op; // operador OR
const crypto = require('crypto');
const passHashConfig = require('../config/hash_pass.json');
const jwt = require('jsonwebtoken');
const authHashConfig = require('../config/auth.json');
// token (userid+hashconfig+timestamp pra gerar um valor unico)
function generateToken(params = {}) {
return jwt.sign(params, authHashConfig.secret, {
expiresIn: 86400, // secs (1dia)
});
}
module.exports = {
// usando BODY
async showall(req, res) {
const aux = await User.findAll({
order: [['createdAt', 'DESC']],
});
return res.json(aux);
},
async register(req, res) {
const {name, email, password} = req.body;
// checar se já tem user name/email registrado
const registeredAux = await User.findOne({
where: {
[op.or]: [{name}, {email}],
},
});
if (registeredAux) {
return res.status(400).send({error: 'User/Email already exist'});
}
// nao tem, entao
// encrypta senha
const hash = crypto
.createHash('sha256')
.update(password + passHashConfig.hash_code) // concatenation
.digest('hex') // get hash in hex format
.toUpperCase(); // letras em maiusculo
// reg
const usr = await User.create({
name,
email,
password: hash,
});
// pra api não retornar a senha
usr.password = undefined;
res.json({
usr,
token: generateToken({id: usr.id}),
});
},
// usando PARAMS
async findone(req, res) {
const {name} = req.params;
const aux = await User.findOne({
where: {name},
});
return res.json(aux);
},
async delete(req, res) {
const {id} = req.params;
const aux = await User.destroy({
where: {
id,
},
});
return res.json(aux);
},
// usando PARAMS + BODY
async edit(req, res) {
const {name} = req.params;
const {newMail} = req.body;
const aux = await User.update(
{
email: newMail,
},
{
where: {
name,
},
}
);
return res.json(aux);
},
// JWT
async auth(req, res) {
const {name, password} = req.body;
// checar se já tem user email registrado
const usr = await User.findOne({
where: {
name,
},
});
if (!usr) {
return res.status(400).send({error: 'User not found'});
}
// checar senha encryptada
const hash = crypto
.createHash('sha256')
.update(password + passHashConfig.hash_code) // concatenation
.digest('hex') // get hash in hex format
.toUpperCase(); // letras em maiusculo
if (hash !== usr.password) {
return res.status(400).send({error: 'Invalid password'});
}
// pra api não retornar a senha pro cara
usr.password = undefined;
res.send({
usr,
token: generateToken({id: usr.id}),
});
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment