1. add login api

2. add get channel list api
This commit is contained in:
Jay
2018-08-15 21:19:06 +08:00
parent ff36b00097
commit 4e610d87e3
8 changed files with 242 additions and 4 deletions
+24 -2
View File
@@ -1,10 +1,16 @@
const Router = require('koa-router')
const koaBody = require('koa-body')
const {
chkObject
chkObject,
resObject,
APIError,
genError
} = require('@libs/route-utils')
const DB = require('@libs/database')
const r = new Router()
const {
comparePassword
} = require('@libs/tools')
r.use(async (c, n) => {
c.obj = {}
@@ -14,12 +20,28 @@ r.use(async (c, n) => {
await n()
} catch (err) {
console.log(err)
c.obj = resObject(err instanceof APIError ? err.resKey : 'InternalError', err.apiMsg || null, err.msgCode || null)
}
c.db.release()
})
r.post('/login', koaBody(), async (c, n) => {
if (!c.chkBody('account', 'string') || !c.chkBody('password', 'string')) throw new Error('DataFormat')
if (!c.chkBody('account', 'string') || !c.chkBody('password', 'string')) throw genError('DataFormat')
let text = `select * from "public"."account" where "account" = $1 limit 1`
let values = [c.request.body.account]
let userAcc = await c.db.query({text, values})
if (userAcc.rowCount === 0) throw genError('NotFound', 'user not found')
if (!comparePassword(c.request.body.password, userAcc.rows[0].password)) throw genError('DataFormat', 'account or password error')
let user = userAcc.rows[0]
delete user.password
c.session.user = user
c.session.loginType = 'system'
c.obj = resObject('Success')
})
r.use('/twitch', require('./twitch').routes())
module.exports = r
+41
View File
@@ -0,0 +1,41 @@
const Router = require('koa-router')
const {
genError,
checkSession,
resObject
} = require('@libs/route-utils')
const r = new Router()
const typeTwitch = async (c, n) => {
let text = `select * from "public"."twitch_channel" where "id" = $1`
let values = [c.session.user.id]
let result = await c.db.query({text, values})
c.state.channelList = result.rows
return n()
}
const typeSystem = async (c, n) => {
let text = `select * form "public"."twitch_channel"`
let values = [c.session.user.id]
let result = await c.db.query({text, values})
c.state.channelList = result.rows
return n()
}
r.get('/channels', checkSession, async (c, n) => {
if (c.session.loginType === 'twitch') {
return typeTwitch(c, n)
} else if (c.session.loginType === 'system') {
return typeSystem(c, n)
}
throw genError('Forbidden')
}, async (c, n) => {
if (!('channelList' in c.state) || !Array.isArray(c.state.channelList)) throw genError('InternalError')
c.obj = resObject('Success', {
list: c.state.channelList
})
})
module.exports = r