accounts-github包导致我的meteor用户有一封空电子邮件

Ben*_*Ben 2 nullreferenceexception meteor

我在我的meteor应用程序中添加了accounts-github,但是当我尝试访问Meteor.user.services.github.email时,我得到的是null.即使我知道电子邮件是在我的github帐户中设置的.我究竟做错了什么?该字段在那里,似乎帐户-github应该只为我取电子邮件...

Aks*_*hat 8

来自github api文档:

注意:返回的电子邮件是用户公开可见的电子邮件地址(如果用户未在其个人资料中指定公用电子邮件地址,则为null).

要获取私人电子邮件地址,您需要将user:email范围添加到您的应用.

如果你正在使用accounts-ui

客户端

Accounts.ui.config({
    requestPermissions: {
        github: ['user:email']
    }
});
Run Code Online (Sandbox Code Playgroud)

更新

我已经尝试过上面的代码,它给出了一些问题.看来github不再发送电子邮件数据和其他OAuth数据.添加以及上述(用于权限)修复了它:

它的作用是在对github的请求中单独获取电子邮件数据,并在用户登录时将其添加到用户.

添加github api包

meteor add mrt:github-api
Run Code Online (Sandbox Code Playgroud)

服务器端代码

Accounts.onLogin(function(info) {
    var user = info.user;
    if(user) {

    var github = new GitHub({
          version: "3.0.0", // required
          timeout: 5000     // optional
      });

      github.authenticate({
        type: "oauth",
        token: user.services.github.accessToken
      });

      try {
        var result = github.user.getEmails({user: user.services.github.username});

        var email = _(result).findWhere({primary: true});

        Meteor.users.update({
          _id: user._id
        },
        {
          $set: {
            'profile.email': email.email,
            'services.github.email': email.email
          }
        })
      }
      catch(e) {
        console.log(e.message);
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

然后,您可以在{{currentUser.profile.email}}(html),Meteor.user().profile.email以及services.github对象中正常访问电子邮件地址.

这样做也有一个好处,如果他们在github上更改了电子邮件字段并再次登录,它将保持最新状态.