fbpx

Começando uma API REST com Node.JS Parte 3

Faala galera, demorei mas voltei com a parte 3 do artigo de como fazer uma API com nodeJs!

Mas antes caso não tenham visto a part 1 e part2, da um conferida.

Nossa API já está acessando o banco de dados mongo e agora vamos implementar autenticação JWT para adicionarmos um passo de segurança.

Esse tipo de autenticação é muito comum e é usada para que apenas pessoas autorizadas acessem nossos métodos da API.

O que é o JWT? (JSON Web Tokens)

JWT é uma string codificada que será usada como chave para concluir uma requisição à nossa API.

Toda requisição feita para nossa API o token será validado, permitindo ou não que a transação seja concluída com sucesso.

Esse token é formado por alguns dados criptografados e uma chave privada, que será usada para validar.

Não é indicado que se salve dados sensíveis nesse token, por mais que ele seja criptografado, é possível reverter essa criptografia e assim ler os dados ali contidos.

Leia mais sobre JWT aqui.

Implementando autenticação JWT

Como nossos usuários não tem senha no banco, vamos começar por isso e adicionar uma senha para eles.

Para facilitar, essa é a senha 123456 criptografada 16fd10090c85fadf1e2413980214b135fafa0169ded1939004ecc4e17dc31b77

Vamos dar um update em nossos usuários e adicionar o campo senha.

Não se esqueçam de atualizar a model de usuário com esse novo campo!

Também alterei o método de criar usuário, para criar com a senha criptografada:

const crypto = require('crypto');
const secret = 'minhastringdeseguranca101010';
 
exports.post = async (req, res, next) => {
   const hash = crypto.createHmac('sha256', secret)
       .update(req.body.senha)
       .digest('hex');
   const usuario = await UsuarioModel.create({
       ...req.body,
       senha: hash
   });
   res.status(200).send(usuario);
};
npm install jsonwebtoken

Criaremos uma pasta em src, chamada Middleware, e dentro dela um arquivo Auth.js

const jwt = require('jsonwebtoken');
const secret = 'minhastringdeseguranca101010';
 
exports.auth = (req, res, next) => {
 const token = req.headers['authorization'];
 if (!token) return res.status(401).send({ auth: false, message: 'Essa rota requer autenticação.' });
  jwt.verify(token, secret, function(err, decoded) {
   if (err) return res.status(500).send({ auth: false, message: 'Token não autorizado.' });
  
   req.currentUser = decoded.userId;
   next();
 });
}

Nesse método vamos pegar o valor de authorization do header e validar ele com a biblioteca do JWT.

Criamos também um controller para fazer o login, AuthController.js

Notem que estou utilizando uma lib chamada crypto, ela vem junto com o node, não precisa de instalação.

const UsuarioModel = require('../Models/Usuario');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const secret = 'minhastringdeseguranca101010';
 
exports.login = async (req, res, next) => {
   const { senha, nome } = req.body;
   const hash = crypto.createHmac('sha256', secret)
       .update(senha)
       .digest('hex');
  
   const usuario = await UsuarioModel.findOne({ nome, senha: hash });
   if (usuario) {
       const token = jwt.sign({ userId: usuario._id }, secret);
       res.send({auth: true, token})
   } else {
       res.status(401).send({ auth: false, error: 'Nome ou senha inválidos.' })
   }
};

Adicionamos uma rota para o login: AuthRoute.js

const AuthController = require('../Controllers/AuthController');
 
module.exports = (app) => {
   app.post('/login', AuthController.login);
}

E puxamos ela no Routes/index.js

const UsuarioRoute = require('./UsuarioRoute');
const AuthRoute = require('./AuthRoute');
 
module.exports = (app) => {
   UsuarioRoute(app);
   AuthRoute(app);
}

Precisamos alterar nosso arquivo de rotas do usuário para adicionar o middleware que criamos logo acima:

const UsuarioController = require('../Controllers/UsuarioController');
const auth = require('../Middleware/Auth').auth;
 
module.exports = (app) => {
   app.post('/usuario', auth, UsuarioController.post);
   app.put('/usuario/:id', auth, UsuarioController.put);
   app.delete('/usuario/:id', auth, UsuarioController.delete);
   app.get('/usuarios', auth, UsuarioController.get);
   app.get('/usuario/:id', auth, UsuarioController.getById);
}

Pronto! Bem simples, não? Vamos testar!

Se tentarmos acessar nossa rota de get /usuarios vamos receber a seguinte mensagem:

Muito bom! Agora vamos fazer o login: O usuário que temos é “Mariana” e a senha “123456”.

Veja que me retornou o token, é isso que vamos usar para fazer as próximas requisições agora.

Voltando pra requisição em usuários, vamos adicionar um parâmetro no header: Authorization, com o valor do token que recebemos quando fizemos o login.

Veja que agora ele retorna os dados, completando a minha requisição.

E assim implementamos com sucesso um esquema de autenticação em nossa API! 

*Para uma melhor segurança, o ideal é usar um arquivo .env para salvar o valor da nossa variável secret

Até um próximo artigo 🙂

Hire developers: Learn how to find devs for your project

If you’ve ever had to hire developers, you know the challenge that this task can become. After all, software development is one of the sexy areas these days.

While there are more vacancies than developers available on the market, startups and large corporations are deploying to offer the best benefits for professionals. Thus the most experienced and skilled developers are even more difficult to find.

In contrast to this difficulty, hiring a professional who does not suit your needs can cause a loss of up to (unbelievable) 20 salaries for your company.

Thinking about it, I made this article for you to learn how to find the best developer for your company.

Tips for finding developers

Look for an indication

The first source of professionals is always the indication of people close to them, after all, a recommendation indicates that there is a relationship of trust between these two people. Therefore, if the person who recommended you is trustworthy, the indicated professional also has a great chance of being.

This is the safest way to hire developers, the problem is that it depends on your networking circle, if it is small, consequently the amount of referral will be small too.

Make a comparison with other jobs openings

One of the main points to hire developers is to present an attractive job offer, for that, search for other job openings similar to the one you are offering on the internet.

That way you can get an idea if you are within the reality of the market and if you can offer something more to have an even more attractive job offer.

A great site to look for jobs offers similar to yours is GlassDoor.

Linkedin

The main function of Linkedin is the professional relationship, and it is no wonder that it is the largest base of professionals in all areas on the internet.

There is no lack of developers there, so it is essential that you do thorough research to find the best professionals according to your needs.

Search using filters such as location and the name of the technology you need that you will have a lot of professionals to talk to.

Linkedin itself has a recruitment tool, it pays to analyze if it makes sense in your context.

We already use it here, it has its positive and negative points, soon we will make a post dedicated to that.

Be in communities

Today there is no shortage of communities for developers to exchange ideas about technology. Meetups, Lives, Telegram and Slack are great places and tools for you to find people engaged in a certain technology.

From more closed communities like a specific one of some framework or even more open about development in general.

It is important to keep an eye on all of them, there you can observe professionals debating, taking and resolving doubts from other programmers. So you can discover talents not yet recognized.

Tips for evaluating a developer

Rate his Github

One of the biggest challenges when hiring a developer is to assess your technical level.

And this is where Github comes in, it is the main source of open source for a developer, that is, people can post their personal projects or studies for other developers to contribute or view.

In this way, you can understand the experience of this professional and even assess the quality of the codes developed.

Conduct interviews

The primary phase in a selection process is the interview, this is where you can validate both the company’s cultural fit and the technical level of the developer.

Try to be very thorough in the questions because this way you can catch inconsistency in people’s speeches.

Here we seek to understand what “side projects” the person has worked on, how much experience with the technology we need and understand a little about their personal life.

Perform technical tests

The vast majority of companies apply technical tests to assess the technical level of professionals, with whom the developer is subjected to a challenge that is related to the technology that the company needs.

To be honest, here at the company we are reevaluating the question of the technical test, we realized that with it the selection process is very long and that it breaks the expectation of the developer.

So we are weighing the benefits and harms of having a technical test in the process. I’ll be back soon with news. ?


In this article, I give some tips on how we are doing to attract and hire developers more easily (after all this is our core business).

So, the main lesson here is that you have to test, which is best for your region, for the technology stack you need and always think about innovating in relation to competitors.

Think of hiring as a sale, you have competitors and you need to differentiate yourself from the rest. A good starting point is a culture.

Any questions leave here in the comments!