mtfosbot/route/api/index.js
Jay 4e610d87e3 1. add login api
2. add get channel list api
2018-08-15 21:19:06 +08:00

48 lines
1.3 KiB
JavaScript

const Router = require('koa-router')
const koaBody = require('koa-body')
const {
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 = {}
c.db = await DB.connect()
c.chkBody = chkObject.bind({body: c.request.body})
try {
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 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