Skip to main content
added 200 characters in body
Source Link
trincot
  • 356.7k
  • 38
  • 281
  • 338

You could promisify your function, like this:

req.isLoggedin = () => new Promise((resolve, reject) => {
    //passport-local
    if(req.isAuthenticated()) return resolve(true);

    //http-bearer
   passport.authenticate('bearer-login', (err, user) => {
       if (err) return reject(err);
       resolve(!!user);
   })(req, res);
});

And then you can do:

req.isLoggedin().then( isLoggedin => {
    if (isLoggedin) {
        console.log('user is logged in');
    }
}).catch( err => {
    console.log('there was an error:', err); 
});

Do not try to keep the synchronous pattern (if (req.isLoggeedin())), as it will lead to poorly designed code. Instead, embrace fully the asynchronous coding patterns: anything is possible with it.

You could promisify your function, like this:

req.isLoggedin = () => new Promise((resolve, reject) => {
    //passport-local
    if(req.isAuthenticated()) return resolve(true);

    //http-bearer
   passport.authenticate('bearer-login', (err, user) => {
       if (err) return reject(err);
       resolve(!!user);
   })(req, res);
});

And then you can do:

req.isLoggedin().then( isLoggedin => {
    if (isLoggedin) {
        console.log('user is logged in');
    }
}).catch( err => {
    console.log('there was an error:', err); 
});

You could promisify your function, like this:

req.isLoggedin = () => new Promise((resolve, reject) => {
    //passport-local
    if(req.isAuthenticated()) return resolve(true);

    //http-bearer
   passport.authenticate('bearer-login', (err, user) => {
       if (err) return reject(err);
       resolve(!!user);
   })(req, res);
});

And then you can do:

req.isLoggedin().then( isLoggedin => {
    if (isLoggedin) {
        console.log('user is logged in');
    }
}).catch( err => {
    console.log('there was an error:', err); 
});

Do not try to keep the synchronous pattern (if (req.isLoggeedin())), as it will lead to poorly designed code. Instead, embrace fully the asynchronous coding patterns: anything is possible with it.

Source Link
trincot
  • 356.7k
  • 38
  • 281
  • 338

You could promisify your function, like this:

req.isLoggedin = () => new Promise((resolve, reject) => {
    //passport-local
    if(req.isAuthenticated()) return resolve(true);

    //http-bearer
   passport.authenticate('bearer-login', (err, user) => {
       if (err) return reject(err);
       resolve(!!user);
   })(req, res);
});

And then you can do:

req.isLoggedin().then( isLoggedin => {
    if (isLoggedin) {
        console.log('user is logged in');
    }
}).catch( err => {
    console.log('there was an error:', err); 
});