【问题标题】:Combining koa-passport with koa-router (getting user data)结合koa-passport和koa-router(获取用户数据)
【发布时间】:2015-03-29 08:05:41
【问题描述】:

我已经创建了一个登录名,它能够登录一个用户并存储该用户(如果他们是数据库中的新用户)。

然后用户被重定向到/,然后检查他们是否经过身份验证,见下文(app.js):

.get('/', function* () {
    if (this.isAuthenticated()) {
        yield this.render('homeSecure', {}); // <-- need user data here
    } else {
        yield this.render('homePublic', {});
    }

正如我在代码中评论的那样,我想发送登录的用户对象。我不知道如何获取登录人的 id,因为 koa 的文档通常不是和 express 一样完整。

我正在使用koa-generic-session-mongo 来处理我的会话。这是我的 GoogleStrategy (auth.js):

var user = null;
// ...
var GoogleStrategy = require('passport-google').Strategy;
passport.use(new GoogleStrategy({
        returnURL: 'http://localhost:' + (process.env.PORT || 3000) + '/auth/google/callback',
        realm: 'http://localhost:' + (process.env.PORT || 3000)
    },
    function (identifier, profile, done) {
        var emails = new Array();
        for (var i = 0; i < profile.emails.length; i++) {
            emails.push(profile.emails[i].value);
        }
        co(function* () {
            yield users.findOne({
                emails: emails
            });
        });
        if (user === null) { // first time signin, create account
            co(function* () {
                user = {
                    id: 1,
                    name: profile.displayName,
                    emails: emails
                };
                yield users.insert(user);
            });
        }
        console.log(user);
        done(null, user);
    }));

【问题讨论】:

  • user 变量在if (user === null) 检查之前在哪里得到它的值,我不明白
  • @3k user 是全局的,我会更新示例。

标签: mongodb passport.js koa


【解决方案1】:
publicRouter
    .get('/', function* () {
        if (this.isAuthenticated()) {
            yield this.render('homeSecure', {
                user: this.req.user
            });
        } else {
            yield this.render('homePublic', {});
        }
    })...

【讨论】:

  • 感谢这对我帮助很大。由于某种原因,用户对象最终出现在节点上下文 this.req.user 中,而不仅仅是在 this.userthis.request.user 中(这两个都是我认为会使用的 Koa 上下文对象)。有谁知道为什么会这样?
【解决方案2】:

免责声明:我没有使用过koa-passport,我只是看了一下代码。

根据the source code of the koa-passport library,您要查找的属性是passport.user,用法如下:

app.use( function*(){
    var user = this.passport.user
})

因此,您的代码示例将变为

.get('/', function* () {
    if (this.isAuthenticated()) {
        yield this.render('homeSecure', this.passport.user );
    } else {
        yield this.render('homePublic', {});
    }

如果这不起作用,this file 让我怀疑 koa-passport 遵循标准护照接口并为请求提供this.user

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 2014-12-25
    • 2017-01-16
    • 1970-01-01
    • 2020-01-20
    • 2017-05-23
    • 2015-10-08
    • 2016-10-03
    相关资源
    最近更新 更多