Js Node / Routes / Controllers

Asked

Viewed 893 times

1

I’m starting to study the nodejs and a question has arisen:

Good I wanted to make an api to power the front - end web and mobile with this api

in case I have these routes (only for study):

const express = require('express');
const routes = express.Router();

const ProductController = require('./controllers/ProductController');
//primeira rota
routes.get("/products", ProductController.index);
routes.get("/products/:id", ProductController.show);
routes.post("/products", ProductController.store);
routes.put("/products/:id", ProductController.update);
routes.delete("/products/:id", ProductController.delete);

module.exports = routes;

Well I was left with doubt how I could make certain route only accessed by my mobile or web front-end

an example: To register a product, as I could limit this only to my front-end( ie an administrator Dashboard access this route), and if a common user can find this route could not add a product .. ( I believe this is related to security? )

If anyone can give me tips on what to study to limit given route only to my front - end.

1 answer

3


For security of access to your API, one of the most common alternatives is to use token. The token would be a code generated by your application in the login process. This code should be returned in the header of all requests (Bearer Token). Before executing a route, it would be checked using a "middleware", which is a chunk of code executed before meeting the request. If it exists, or if it exists but its contents are not valid, then the route is not executed.

Through the token, you can validate if that user is allowed to access the route

Here’s an example of route and token validation with JWT

Route archive:

const express = require("express");
const validate = require("express-validation");
const handle = require("express-async-handler");
const routes = express.Router();
const authMiddleware = require("./app/middlewares/auth");
const UsuarioController = require("./app/controllers/UsuarioController");
const FerramentasController = require("./app/controllers/FerramentasController");

routes.post("/login", validate(validatorLogin), handle(UsuarioController.login));
routes.post(
  "/usuario",
  handle(UsuarioController.cadastrar)
);
routes.get("/ferramentas", handle(FerramentasController.listar));
routes.get("/ferramentas/:id", handle(FerramentasController.detalhe));
//As rotas a partir daqui exigem autenticação
routes.use(authMiddleware);
routes.post(
  "/ferramentas",
  handle(FerramentasController.cadastrar)
);
routes.delete("/ferramentas/:id", handle(FerramentasController.remover));

module.exports = routes;

Here is an example of how the "authMiddleware" would be responsible for validating the token before executing the route:

const jwt = require("jsonwebtoken");
const authConfig = require("../../config/auth");
const { promisify } = require("util");
module.exports = async (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    res.status("401").json({ error: "Token não informado" });
  }
  const [, token] = authHeader.split(" "); // Quebra o header num array e pega o segundo elemento (token sem o Bearer)
  try {
    //Transforma uma funcao que usa callbacks numa promisse
    const decoded = await promisify(jwt.verify)(token, authConfig.secret);
    req.userID = decoded.id; // Adiciona em todas as requisicoes que utilizaram este middleware o ID do usuário
    return next(); // Middleware tem sempre req, res e next
  } catch (error) {
    res.status("401").json({ error: "Token inválido" });
  }
};

Within the route, you will be able to validate req.userid recovered by middleware, and validate whether the user is allowed to use that route.

Regarding blocking Web or Mobile access, you might think about creating a custom header (header). So in addition to the token being valid, the header should also have a certain information for the route to run.

Here’s a tutorial on how to implement a JWT token

https://www.luiztools.com.br/post/autenticacao-json-web-token-jwt-em-nodejs/

  • Many thanks I will read very carefully and try to apply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.