mtfosbot/route/api/index.js

48 lines
1.3 KiB
JavaScript
Raw Normal View History

2018-08-11 15:28:00 +00:00
const Router = require('koa-router')
2018-08-14 06:17:48 +00:00
const koaBody = require('koa-body')
const {
chkObject,
resObject,
APIError,
genError
2018-08-14 06:17:48 +00:00
} = require('@libs/route-utils')
2018-08-14 09:30:27 +00:00
const DB = require('@libs/database')
2018-08-11 15:28:00 +00:00
const r = new Router()
const {
comparePassword
} = require('@libs/tools')
2018-08-11 15:28:00 +00:00
2018-08-14 06:17:48 +00:00
r.use(async (c, n) => {
c.obj = {}
2018-08-14 09:30:27 +00:00
c.db = await DB.connect()
2018-08-17 15:03:10 +00:00
c.chkBody = chkObject.bind(c.request)
2018-08-14 06:17:48 +00:00
try {
await n()
} catch (err) {
console.log(err)
c.obj = resObject(err instanceof APIError ? err.resKey : 'InternalError', err.apiMsg || null, err.msgCode || null)
2018-08-14 06:17:48 +00:00
}
2018-08-14 09:30:27 +00:00
c.db.release()
2018-08-14 06:17:48 +00:00
})
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')
2018-08-14 06:17:48 +00:00
})
r.use('/twitch', require('./twitch').routes())
2018-08-11 15:28:00 +00:00
module.exports = r