All files / koa/auth/local index.js

73.91% Statements 17/23
43.75% Branches 7/16
100% Functions 4/4
77.27% Lines 17/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45    5x 5x 5x 5x     5x   15x                       15x     15x       5x 15x 15x 15x 7x   8x       8x 8x       5x
'use strict'
 
const router = require('koa-router')()
const passport = require('koa-passport')
const { signToken } = require('../auth.service')
const config = require('../../config/env')
 
function checkCaptcha() {
  return async(ctx, next) => {
    let msg
    Iif (config.env !== 'test' && !ctx.req.headers.horse) {
      // if (config.env != 'development') {
      //   if (!ctx.request.body.captcha) {
      //     msg = '验证码不能为空.'
      //   } else if (ctx.session.captcha !== ctx.request.body.captcha.toLowerCase()) {
      //     msg = '验证码错误.'
      //   }
      // }
      if (ctx.request.body.email === '' || ctx.request.body.password === '') {
        msg = '用户名和密码不能为空.'
      }
    }
    Iif (msg) {
      return ctx.resMid.resBody(ctx, 422, msg)
    }
    await next()
  }
}
 
router.post('/', checkCaptcha(), async(ctx, next) => {
  await passport.authenticate('local', async(err, user, info) => {
    Iif (err) { ctx.throw(err) }
    if (info) {
      return ctx.resMid.resBody(ctx, 403, info)
    }
    Iif (!user) {
      ctx.status = 404
      ctx.body = { message: 'Something went wrong, please try again.' }
    }
    let token = signToken(user._id, user.role)
    ctx.body = { token }
  })(ctx, next)
})
 
module.exports = router