44

I've been looking for a while, and can't see to find a definitive documentation source. When I search for these, the first Google results are to StackOverflow.

Are there any more middleware functions similar to this?

nbro
  • 15,395
  • 32
  • 113
  • 196
az_
  • 1,493
  • 1
  • 16
  • 24

2 Answers2

66

While not explicitly documented anywhere easily found, you can see where the the isAuthenticated and isUnauthenticated flags are set in the Passport code at https://github.com/jaredhanson/passport/blob/a892b9dc54dce34b7170ad5d73d8ccfba87f4fcf/lib/passport/http/request.js#L74.

ensureAuthenticated is not official, but can be implemented via the following:

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated())
    return next();
  else
    // Return error content: res.jsonp(...) or redirect: res.redirect('/login')
}

app.get('/account', ensureAuthenticated, function(req, res) {
  // Do something with user via req.user
});
Rob DiMarco
  • 13,226
  • 1
  • 43
  • 55
  • 1
    The above example has a couple of issues. Line 3 should be `if (req.isAuthenticated())` and line 9 should be `..., ensureAuthenticated, ...` Checkout the following for a better example. https://github.com/jaredhanson/passport-local/blob/master/examples/express3-mongoose/app.js – chris Sep 08 '13 at 22:57
  • 1
    @chris Thanks for the note - I've corrected the issues above. – Rob DiMarco Sep 10 '13 at 17:52
  • 9
    some documentation would be nice, as much fun as examining the source is – Connor Leech May 26 '14 at 11:52
  • 1
    @ConnorLeech I'm not the author of Passport, but maybe you could try sending a pull request to [https://github.com/jaredhanson/passport](https://github.com/jaredhanson/passport)? – Rob DiMarco May 26 '14 at 22:14
  • 1
    Updated example link -> https://github.com/jaredhanson/passport-local/wiki/Examples – Jeff Lewis Aug 15 '16 at 17:26
0

the reason it return false is mostly because its declared below the route definition. i am doing it in other file so i use it like this

//auth check
function auth(req,res,next){
    if(req.isAuthenticated()){
        next();
    } 
    else{
        res.redirect("/fail");}
}

//routes
require("./routes/myroute")(app,auth);