add twitch oauth login

This commit is contained in:
Jay
2018-08-12 23:31:09 +08:00
parent 89b24e0bf6
commit 334fce3b9b
11 changed files with 140 additions and 77 deletions
+1 -1
View File
@@ -103,6 +103,6 @@ r.use('/web', require('./web').routes())
r.use('/api', require('./api').routes())
r.use('/line', require('./line').routes())
r.use('/google', require('./google').routes())
// r.use('/twitch', require('./twitch').routes())
r.use('/twitch', require('./twitch').routes())
module.exports = r
+89 -65
View File
@@ -1,81 +1,105 @@
const Router = require('koa-router')
const r = new Router()
const {
getRaw
} = require('@libs/middleware')
const DB = require('@libs/database')
const api = require('@libs/api-action')
// const config = require('../../config')
const qs = require('querystring')
const config = require('@config/index')
const axios = require('axios')
const _ = require('lodash')
r.get('/webhook', async (c, n) => {
let mode = c.query['hub.mode']
let token = c.query['hub.secret']
let challenge = c.query['hub.challenge']
console.log(mode, token, challenge)
console.log(c.headers)
if (mode) {
if (mode === 'subscribe') {
c.status = 200
c.body = challenge
} else {
c.status = 403
c.body = ''
}
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.post('/webhook', getRaw, async (c, n) => {
// middleware
c.db = await DB.connect()
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 {
await n()
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)
}
c.db.release()
c.body = 'success'
c.status = 200
}, async (c, n) => {
console.log(JSON.stringify(c.request.body, null, 2))
if (!('data' in c.request.body) || !Array.isArray(c.request.body.data)) return
if (c.request.body.data.length === 0) return // length > 0 live, length === 0 down
let data = c.request.body.data[0]
let uid = c.query['uid'] || ''
let type = c.query['type'] || ''
if (!uid || !type) return
let text = `select rt."line" as group, rt."twitch" as twitch, rt."tmpl" as tmpl, twitch."name" as user from "public"."line_twitch_rt" rt
left join "public"."twitch_channel" twitch
on twitch."id" = rt."twitch"
left join "public"."line_group" line
on line."id" = rt."line"
where
line."notify" = true
and twitch."id" = $1
and rt."type" = $2`
let values = [uid, type]
let twch = await c.db.query({
text,
values
})
if (twch.rowCount === 0) return
let chLink = `https://twitch.tv/`
for (let i in twch.rows) {
let tmp = twch.rows[i]
let msg = tmp.tmpl || ''
let link = chLink + tmp.user
if (typeof msg !== 'string' || msg.trim().length === 0) {
msg = `${data.title}\n${link}`
} else {
msg = msg.replace(/{link}/, link).replace(/{txt}/, data.title).replace(/\\n/, '\n')
}
await api.line.pushMessage(tmp.group, msg).then(() => { }).catch(() => { })
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`)
}
})