Search code examples
node.jsexpressexpress-session

creating authentication function node.js


I have this beautiful way of checking if someone is authenticated using express-session. Here is how:

if (req.session.loggedin) {

... do code ...

} else {
    req.session.destory;
    res.redirect('/login')
}

however, I want to create some sort of middleware maybe, or a call to the function everything another function is called. Like this.

function auth (req, res) {
   if (req.session.loggedin) {

        return;

   } else {
    req.session.destory;
    res.redirect('/login')
   }

}

app.get('/home', (req, res) => {
  auth()
... do code ...

}) 

or :

app.get('/home', (req, res, auth) => {
... do code ...
})

is this possible, if so, how do I do it?


Solution

  • Make auth middleware with validating session, remember call next function when any is good.

    function auth(req, res, next) {
       if (req.session.loggedin) {
           return next(); // call next function to go to next handler
       } else {
          req.session.destory;
          res.redirect('/login')
       }
    }
    

    Then, apply the middleware for each router that requires authentication:

    app.get('/home', auth, (req, res) => { // apply auth before "do code"
       // ... do code ...
    })