const Router = require('koa-router');
const pubtool = require('../util/pubtool');
const User = require('../module/User');
const router = new Router();

/**
 * 用户登录
 */
router.post('/sign', async ctx => {
  let {name, password} = ctx.request.body;
  (!password || password.length < 5) && ctx.error('密码错误')

  let user = new User();
  user.name = name;
  let result = await user.query();

  if (result.length === 0) {
    ctx.error('该账号不存在!');
  } else if (result[0].psw !== pubtool.hashEncryption(password, 2)) {
    ctx.error('密码错误');
  } else {
    await (ctx.session.user = result[0]);
    ctx.body = { cmsg: '登录成功' };
  }
});

router.post('/sinout', async ctx => {
  await (delete ctx.session.user);
  ctx.body = { cmsg: '成功退出' };
})

module.exports = exports = {path: '/user', router};