passport-github如何提取会话cookie以了解用户已经登录

时间:2017-05-15 02:47:03

标签: node.js passport.js

我正在为我的应用程序构建一个passport-github auth。但我认为目前我不知道如何从请求中提取cookie,即用户已经登录。所以每次当我转到主页时,我会被重定向到/ login。

我的代码大致如下:

passport.use(new GitHubStrategy({
    clientID: authConfig.GITHUB_CLIENT_ID,
    clientSecret: authConfig.GITHUB_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:8080/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    return db.user.findOne({where:{github_id:profile.id}})
    .then(data=>{
      if (data) {
        return done(null,data);
      } else {
        return db.user.build({ github_id: profile.id }).save()
        .then(()=>{
          return db.user.findOne({where:{github_id:profile.id}})
        })
        .then(data=>{
          return done(null,data);
        })
      }
    });
  }
));

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing
passport.serializeUser(function(user, done) {
  console.log("serialize>>>>>", user.github_id);
  done(null, user.github_id);
});

passport.deserializeUser(function(id, done) {
  console.log("deserialize>>>>", id);
  db.user.findOne({where:{github_id: id}})
  .then(user=>{
    done(null, user.toJSON());
  })
});

我已经建立了会议:

app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

我有一个isAuthenticated函数来检查req信息:

function isAuthenticated (req, res, next) {
  // If the user is logged in, continue with the request to the restricted route
  console.log("req.user is>>>>", req);
  if (req.isAuthenticated()) {
    return next();
  }
  // If the user isnt' logged in, redirect them to the login page
  return res.redirect("/index");
}

我正在使用这个passport-github lib。我无法从req似乎

获得一些有用的信息

更新为包含路线: 这是路线:

    const isAuthenticated = require('./middleware/isAuthenticated.js');
router
    .get('/index', query.renderIndex)
    .get('/', isAuthenticated, query.displayRepos)
    .post('/', query.queryRepoTopic)
    .post('/trending', query.addRepo)
    .post('/addTopic', query.addTopic)
    .get('trending', query.updateScore);

router.get('/login', auth.loginPage)
  .get('/auth/github',
    passport.authenticate('github', { scope: [ 'user:email' ] }),
    function(req, res){}
  )
  .get('/auth/github/callback', 
    passport.authenticate('github', { failureRedirect: '/login' }),
    auth.signInRedirect
  )
  .get('/logout', auth.logout);

这是执行逻辑的控制器函数:

const loginPage = (req, res) => {
  res.render('index');
}

// signin a user in 
const signInRedirect = (req, res) => {
  console.log("here in callback>>>");
  console.log("req.user is>>>>", req.user);
  //res.json("you have successfully logged in!");
  res.redirect('/');
}

const logout = (req, res) => {
  req.logout();
  res.redirect('/index');
}

1 个答案:

答案 0 :(得分:1)

我看到你有这个路线配置:

    const isAuthenticated = require('./middleware/isAuthenticated.js');
    router
        .get('/index', query.renderIndex)
        .get('/', isAuthenticated, query.displayRepos)
...

如果您想呼叫localhost:3000,并在您未登录时被重定向到auth/github,则可以像这样更改isAuthenticated function

function isAuthenticated (req, res, next) {
  // If the user is logged in, continue with the request to the restricted route
  console.log("req.user is>>>>", req);
  if (req.isAuthenticated()) {
    return next();
  }
  // If the user isnt' logged in, redirect them to the github login page.
  return res.redirect("/auth/github");
}

这意味着,当您尝试拨打'/'时,isAuthenticated会检查req.user是否已设置(if (req.isAuthenticated())),如果没有,则重定向到{ {1}}路线。

你试过这个吗?

有它可以提供帮助!