2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MeteorでGitHubログイン時にEmail情報を取得する方法(bruz:github-api)

Last updated at Posted at 2015-08-18

MeteorでGitHubアカウントと連携する方法(github-accounts) の手順で連携した GitHub アカウント情報には Email 情報が含まれていませんでした。
いろいろ調査した結果、GitHub アカウントから Email 情報を取得する方法がわかりましたので、その方法を以下で解説します。

なお、Meteor と GitHub との連携方法については、前の記事をご参照ください。

今回の記事のサンプルコード

GitHubアカウントから Email 情報を取得する方法

1. bruz:github-api パッケージを追加する

bash$
meteor add bruz:github-api

2. client/lib ディレクトリと server/lib ディレクトリを作成

bash$
mkdir -p client/lib server/lib

3. GitHub ログイン時に Email を取得するコードを追加

client/lib/accounts.js
Accounts.ui.config({
    requestPermissions: {
        github: ['user:email']
    }
});
server/lib/accounts.server.js
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);
    }
  }
});

4. Email を表示するためのコードをテンプレートに追加

テンプレートファイルの好きな場所に以下のコードを追加します。

app.html
{{#if currentUser}}
  <h2>Email: {{currentUser.profile.email}}</h2>
{{/if}}

5. Meteor アプリにアクセスし、GitHub アカウントでログインする

bash$
meteor

で Meteor アプリケーションを起動したら、ブラウザで http://localhost:3000/ にアクセスします。
その後 GitHub アカウントでログインをすると、Email 情報が取得できます。
すでにログインをしている場合は、一度ログアウトし、再度ログインを試してみてください。

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?