Go through a method on all routes of all http methods except two

4

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

Would you like a solution that does not involve calling a function in all the required places, can you do something like router.all() or router.use() in one place?

    
asked by anonymous 02.06.2018 / 19:19

1 answer

1

Middlewares . Just declare one before your routes, and set the logic to allow or deny 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
    
05.06.2018 / 19:26