Pass a method on all routes of all http methods except two

Asked

Viewed 134 times

4

Basically I want to make all the routes that come from any http method (get, post, put, ...) pass, first, by a method that will make the verification if the user is authenticated, however, this method should not be called when the user will authenticate (method POST route /auth) and when it will register (method POST route /user). Remembering that I have other methods in the route /user and other routes with the method POST

I would like a solution that does not involve calling a function in all necessary places, has how to do something like router.all() or router.use() in one place?

1 answer

1


Middleware. Just declare one before your routes, and set the logic on it to allow or refuse the request:

var app = express()

app.use(function (req, res, next) {
    // endpoints ignorados
    if ((req.url === '/auth' || req.url === '/user') && req.method === 'POST') {
        // `next()` significa "ok, pode continuar na rota `req.url`"
        next();
    }
    // checa login
    else if (/*checa se usuário está logado*/) {
        next();
    }
    // não logado, envia erro ou whatever vc quiser.
    else {
        res.status(401).send('Você precisa logar');
    }
});

// ... suas rotas GET, POST, etc
  • 1

    In this case the status is 401 (not authenticated), 403 is when the user is authenticated but has no permission

  • Truth, my confusion. Fixed in response.

Browser other questions tagged

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