const Router = require('koa-router') const r = new Router() const DB = require('@libs/database') const api = require('@libs/api-action') const qs = require('querystring') const config = require('@config/index') const axios = require('axios') const _ = require('lodash') r.get('/login', async (c, n) => { let redirectUrl = `${config.url.replace(/\/$/, '')}/twitch/oauth` let qsObj = { client_id: config.twitch.clientid, redirect_uri: redirectUrl, response_type: 'code', scope: 'user:read:email' } let qsStr = qs.stringify(qsObj) let toUrl = `https://id.twitch.tv/oauth2/authorize?${qsStr}` let backUrl = c.query['tourl'] || '' if (typeof backUrl === 'string' && backUrl.trim().length > 0) { c.session.backUrl = backUrl } c.redirect(toUrl) }) r.get('/oauth', async (c, n) => { let url = `https://id.twitch.tv/oauth2/token` let redirectUrl = `${config.url.replace(/\/$/, '')}/twitch/oauth` let code = c.query.code || '' if (!code) { c.body = 'oauth login fail' return } let qsObj = { client_id: config.twitch.clientid, client_secret: config.twitch.clientsecret, code, grant_type: 'authorization_code', redirect_uri: redirectUrl } let data = { 'access_token': '', 'refresh_token': '', 'expires_in': 0, 'scope': '', 'token_type': 'bearer' } try { let tokenResult = await axios({ method: 'post', url, params: qsObj }) if (!('data' in tokenResult)) { c.body = 'read token fail' return } data = _.assign({}, data, tokenResult.data) } catch (err) { console.log('request token fail ', err) c.body = 'get token fail' return } c.session.token = data try { let user = await api.twitchNew.getUserData(data.access_token) c.session.user = user } catch (err) { console.log('get user data fail ::: ', err) c.body = 'get user data fail' return } let db = await DB.connect() try { let count = await db.query({ text: `select id from "public"."twitch_channel" where id = $1`, values: [c.session.user.id] }) if (count.rowCount === 0) { await db.query({ text: `insert into "public"."twitch_channel" ("id", "name") values ($1, $2)`, values: [c.session.user.id, c.session.user.login] }) } } catch (err) { console.log(err) } db.release() c.session.loginType = 'twitch' if (typeof c.session.backUrl === 'string' && c.session.backUrl.length > 0) { let url = c.session.backUrl delete c.session.backUrl c.redirect(url) } else { c.redirect(`${config.url.replace(/\/$/, '')}/web`) } }) module.exports = r