passportのストラテジ(line-auth)を動かしてみます。
Overview
passportでのpassport-localストラテジでの認証を先日動かしてみたので、lineの認証を試してみたいと思います。
Input
Proccess
passport-line-authのインストール
npm i passport-line --save
lineに登録
公式見るとどうやら、、、
line Developersにログイン https://developers.line.biz/ja/
プロバイダを作ってそのなかにチャネル作るらしい。なるほど。(ちなみに日本語対応はされています。右下に言語設定ある)
プロバイダの作成と、チャネルの作成
チャネルにコールバック設定
この一連でチャネルIDとチャネルシークレットが割り当てられます。 Auth後のリダイレクト先を設定しておきます。
入力画面設置
先日のローカルの画面にLINE用の認証ボタンを追加してみます。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> </head> <body> <h1>認証テスト</h1> <form action="login" method="POST"> <input type="text" name="username"> <input type="password" name="password"> <button type="submit">ログイン</button> </form> <form action="auth/facebook" method="POST"> <button type="submit">facebook</button> </form> <form action="auth/twitter" method="POST"> <button type="submit">twitter</button> </form> <form action="auth/google" method="POST"> <button type="submit">google</button> </form> <form action="auth/line" method="POST"> <button type="submit">line</button> </form> </body> </html>
認証リクエストのルーティング,認証処理
line-authストラテジを使用するので、postでline認証向けのURLで受け取ったらそのまま委譲する形になります。 で、LINE認証後のコールバックはline側に設定した際のパスに合わせて作成しておきます。 ※今回はLINEのコールバック(戻り先URL)の設定は「"http://localhost:3090/auth/line/callback"」としました。
// ログイン 【LINE】認証 app.post('/auth/line', passport.authenticate('line')); // ログイン 【LINE】処理 成功なら/へだめならloginへ app.get('/auth/line/callback', passport.authenticate('line', { failureRedirect: '/login' }), function (req, res) { // ログイン成功 res.redirect('/'); } );
UserスキーマにlineId追加するためにmongooseのスキーマに追加
var mongoose = require('mongoose'); // スキーマ設定 var User = mongoose.Schema({ username: String, password: String, facebookId: String, // これは前前々回追加 twitterId: String, // これは前々回追加 googleId: String, // これは前回追加 lineId: String, // ★これは今回追加 date: {type: Date, default: new Date()}, }); module.exports = mongoose.model('User', User, 'users');
line-authストラテジの追加(ここでチャネルIDとチャネルシークレットが必要)
var LINE_CHANNEL_ID = 'xxxxxxxxxx'; var LINE_CHANNEL_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; passport.use(new LineStrategy({ channelID: LINE_CHANNEL_ID, channelSecret: LINE_CHANNEL_SECRET, callbackURL: 'http://localhost:3090/auth/line/callback', }, function(accessToken, refreshToken, profile, done) { User.findOneAndUpdate({ lineId: profile.id }, { $set: { lineId: profile.id } }, { upsert: true }, (err, user) => { if (err) throw (err); return done(err, user); }); } })); // passport.use
認証リクエストのルーティング
app.post('/auth/line', passport.authenticate('line')); // ログイン 【GO】処理 成功なら/へだめならloginへ app.get('/auth/line/callback', passport.authenticate('line', { failureRedirect: '/login' }), function (req, res) { // ログイン成功 res.redirect('/'); } );
Output