mtfosbot/route/api/index.js
2018-08-23 20:15:42 +08:00

73 lines
1.8 KiB
JavaScript

const Router = require('koa-router')
const koaBody = require('koa-body')
const {
chkObject,
resObject,
APIError,
genError,
checkSession
} = 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(c.request)
let obj = null
try {
await n()
} catch (err) {
console.log(err)
obj = resObject(err instanceof APIError ? err.resKey : 'InternalError', err.apiMsg || null, err.msgCode || null)
}
if (Object.keys(c.obj).length > 0 && 'status' in c.obj && 'obj' in c.obj) {
c.status = c.obj.status
c.body = c.obj.obj
}
if (obj !== null) {
c.status = obj.status
c.body = obj.obj
}
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')
let matchPass = await comparePassword(c.request.body.password, userAcc.rows[0].password)
if (!matchPass) 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.post('/logout', async (c, n) => {
c.session = null
c.obj = resObject('Success')
})
r.get('/session', checkSession, async (c, n) => {
c.obj = resObject('Success', {
user: c.state.loginUser
})
})
r.use('/twitch', require('./twitch').routes())
module.exports = r