Is it possible to block access to a middleware route?

Asked

Viewed 362 times

0

Guys, I have a public folder with all the "public" files from my site html,css,js etc. And another folder called private with all the file private files connected with database and etc, which is a route only for me that I am admin can access it, and I want to know if I can block access to that route so in case an ordinary user tries to access this private route he can’t. So far I’ve managed to create middleware, but I don’t even know where to start, my app.js file is so far so far:

 const express = require("express")
 const handleBars = require("express-handlebars")
 const bodyParser = require("body-parser")
 const app = express()
 const admin = require("admin")
 const path = require("path")

 //Configuções
 app.use(bodyParser.urlencoded({extended: true})
 app.use(bodyParser.json())

 //Handlebars
 app.engine('handlebars',handlebars({defaultLayout: 'main' }))
 app.set('view-engine', 'handlebars')

 //Public
 app.use(express.static(path.join(__dirname + "public")))

 app.use((req,res,next) => {
  console.log("Middleware rodando")
  next()
 })

 //Rotas
 app.get("/", (req,res) => {
  res.sendFile(__dirname + "/public/index.html")
 })

 app.use('/admin', admin)

 const PORT = 3000
 app.listen(PORT, () => {
   console.log("Servidor rodando")
 })

2 answers

1

You can do something like

const middleware = (req, res, next) => {
 try {
    // validaçao
    return next();
  } catch (err) {
    return res.status(401).json({ error: 'Auth'});
  }
}



//Rotas
app.get("/", middleware, (req,res) => {
  res.sendFile(__dirname + "/public/index.html")
 })
  • 401 or 403, depending on the problem. Exceptions is not the best way to treat this type of error

0


You can create a function responsible for checking if the user is admin and use it as middleware, for example:

const adminOnly = (req, res, next) => {
    // Verifique qual usuário está enviando o request
    if (usuario === admin) {
        // Se ele for admin, você chama o próximo middleware
        next();
    } else {
        // Status 401 = Unauthorized (não autorizado)
        res.status(401).send();
    }
}

app.use('/admin', adminOnly, admin);

Thus, when sending a request to the routes that are handled by your admin, go through the middleware adminOnly. If the user is not an admin, you will receive a reply 401, otherwise it follows its normal stream (inside your file admin.js).

For more information on middleware in Express, see the official website with a few examples.


Detail: you can arrange this in folders:

  • /routes for the files responsible for routing your app.
  • /controllers for the files that will perform the necessary methods, such as database queries and have the res.send().
  • /middlewares to the archives responsible for authentication and authorization of the routes.

This leaves a project more organized than putting everything in its main file, but you learn over time.

  • Thanks! Conseui do something similar from Allah.

Browser other questions tagged

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