node.jsでslackログインして、ユーザーの情報を取得して表示するところまでやる。
基本的にはこのドキュメントに沿っておこなう。備忘録。
Slack appをつくる
上記ドキュメントの Create your Slack app if you haven't already
の Create a Slack app now
からSlackアプリを作る。
ClientIDなどができてることを確認。
また、Redirect URIが必要なので、FeatureのPermissionのところからRedirect URLを設定する。
一旦、ローカルでやるので、http://localhost:3000/slack/auth/redirect とか入れておく。
slack loginボタンを設置する
/views/index.ejs
のなかに、
<a href="https://slack.com/oauth/authorize?scope=identity.basic&client_id=your_client_id&state=testapp">
<img src="https://api.slack.com/img/sign_in_with_slack.png" />
</a>
を設置する。
※ 確認のために、stateを追記している。
※ profile画像も取得したい場合は、scope=identity.basic, identity.avatar
とするなどscopeを追加する。(必要に合わせてpersmissionも追加する必要があるかも)
返ってきたcodeを使って、access tokenや情報を取得するようにする
/routes/slack.js
にslackログインのやり取りを書いていく。
npmのrequestを利用する。https://github.com/request/request
var request = require('request');
router.get('/auth/redirect', function(req, res, next) {
let code = req.query.code;
let state = req.query.state;
if (typeof code !== 'undefined' && state == "testapp") {
request.get('https://slack.com/api/oauth.access?client_id=' + your_client_id + '&client_secret=' + your_client_secret + '&code=' + code, function(err, response, body) {
let result = JSON.parse(body);
// これで結果が取得できる
console.log('result: ', result);
console.log('userName:', result.user.name);
});
}
});
あとは、取得したデータをDB格納したり、sessionを良い感じにしたりするとOK。
レポジトリはこちら。https://github.com/mazeltov7/SlackLoginTest
ログインセッション周りは、
- Express.js + Session + Sequelizeで簡易ログイン(SessionStore利用)
に書いてます。