All files / koa/app/controller/user user.ctrl.js

76.87% Statements 113/147
69.89% Branches 65/93
81.82% Functions 9/11
76.87% Lines 113/147

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369    5x 5x   5x 5x     5x 5x 5x                                     5x 10x 10x 10x 10x     10x 1x 9x 1x 8x 1x 7x 1x 6x 1x 5x 1x   10x 6x   4x 4x 1x   4x 1x   4x 4x 4x 2x 2x   2x                                       5x 4x 4x 4x 4x                 4x 4x 4x                                   5x 1x 1x 1x 1x                                   5x 1x 1x 1x 1x 1x                                             5x 5x 5x 5x   5x 1x   5x     5x 5x   5x 1x   4x 4x 4x 4x   4x     4x 4x   4x 3x   4x     4x 4x 4x                                         5x 4x 4x   4x 1x 3x 1x   4x 2x   2x 2x 2x           2x 2x 2x                                   5x 3x 3x 1x   2x 2x 1x 1x   1x           5x                                                                                   5x 1x 1x 1x                                 5x 2x 2x                                   5x        
'use strict'
 
const captcha = require('trek-captcha')
const config = require('../../../config/env')
 
const { User } = require('../../model')
const { LogsProxy } = require('../../proxy')
 
// /* eslint-disable */
const EMAIL_REGEXP = /^([A-Za-z0-9_\-\.])+\@(o-in.me|qq.com)$/
const USERNAME_REGEXP = /^[(\u4e00-\u9fa5)0-9a-zA-Z\_\s@]+$/
const PWD_REGEXP = /^(\w){6,20}$/
// /* eslint-enable */
 
/**
 * @api {post} user/add 添加用户
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName add
 * @apiSampleRequest user/add
 * @apiPermission none
 *
 * @apiParam (Request body) {String} email 邮箱
 * @apiParam (Request body) {String} username 用户名
 * @apiParam (Request body) {String} password 密码
 *
 * @apiUse Response
 */
// export async function add(ctx) { //ES6 model import case
exports.add = async(ctx, next) => {
  const body = ctx.request.body
  const email = body.email ? body.email.replace(/(^\s+)|(\s+$)/g, '') : ''
  const username = body.username ? body.username.replace(/(^\s+)|(\s+$)/g, '') : ''
  const password = body.password ? body.password.replace(/(^\s+)|(\s+$)/g, '') : ''
 
  let msg
  if (email === '') {
    msg = '邮箱地址不能为空'
  } else if (username === '') {
    msg = '用户名不能为空'
  } else if (password === '') {
    msg = '密码不能为空'
  } else if (email.length <= 4 || email.length > 30 || !EMAIL_REGEXP.test(email)) {
    msg = '邮箱地址不合法,只能输入5-30个字母、数字、下划线'
  } else if (username.length <= 4 || username.length > 30 || !USERNAME_REGEXP.test(username)) {
    msg = '用户名不合法,只能输入5-30个包含中文中文英文(包含大小写)空格以及中文名字带'
  } else if (password.length <= 5 || password.length > 20 || !PWD_REGEXP.test(password)) {
    msg = '密码不合法,只能输入6-20个字母、数字、下划线'
  }
  if (msg) {
    return ctx.resMid.resBody(ctx, 422, msg)
  }
  try {
    if (body.role) {
      Reflect.deleteProperty(body, 'role');
    }
    if (body.status) {
      Reflect.deleteProperty(body, 'status');
    }
    let user = new User(body)
    user.role = 'user'
    user = await user.save()
    await LogsProxy.createLogs((ctx.req.user && ctx.req.user._id) || user._id, user._id, 'User', '添加用户')
    ctx.resMid.resBody(ctx, '', '', { _id: user._id })
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {get} user/getList 获取列表用户
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName getList
 * @apiSampleRequest user/getList
 * @apiPermission admin
 *
 * @apiUse ListParam
 * @apiParam (Query) {String}  where 查询条件(邮箱或用户名)
 *
 * @apiUse Header
 * @apiUse Response
 * @apiUse ListResponse
 */
exports.getList = async(ctx, next) => {
  try {
    let query = {};
    let options = ctx.query;
    Iif (options.where) {
      query['$and'] = [];
      query['$and'].push({
        $or: [
          { email: { $regex: new RegExp(options.where, 'ig') } },
          { username: { $regex: new RegExp(options.where, 'ig') } },
        ],
      });
    }
    options.select = '-salt -hashedPassword'
    const data = await User.paginate(query, options)
    ctx.resMid.resBody(ctx, '', '', data)
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {get} user/getOne/:id 获取某个用户
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName getOne
 * @apiSampleRequest user/getOne/:id
 * @apiPermission user
 *
 * @apiUse Header
 * @apiUse Response
 */
exports.getOne = async(ctx, next) => {
  const userId = ctx.params.id
  try {
    const user = await User.findById(userId).select('-salt -hashedPassword')
    ctx.resMid.resBody(ctx, '', '', user.userInfo)
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {get} user/getMe/ 获取自己用户
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName getMe
 * @apiSampleRequest user/getMe
 * @apiPermission none
 *
 * @apiUse Header
 * @apiUse Response
 */
exports.getMe = async(ctx, next) => {
  const userId = ctx.req.user._id
  try {
    const user = await User.findOne({ _id: userId }, '-salt -hashedPassword')
    ctx.resMid.resBody(ctx, '', '', user)
    LogsProxy.createLogs(ctx.req.user._id, user._id, 'User', `用户登录,其IP地址:${ctx.request.ip}`)
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {put} user/modOne/:id 修改某个用户
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName modOne
 * @apiSampleRequest user/modOne/:id
 * @apiPermission admin
 *
 * @apiParam (Request body) [role='user'] {String}  role 角色,不填写默认不修改
 * @apiParam (Request body) {String}  partner 经销商合作伙伴,选择下拉列表,提交_id
 * @apiParam (Request body) {String}  status 状态,不填写默认不修改
 * @apiParam (Request body) {String}  password 密码,不填写默认不修改
 *
 * @apiUse Header
 * @apiUse Response
 */
exports.modOne = async(ctx, next) => {
  const editUserId = ctx.params.id // 被编辑人
  const body = ctx.request.body
  const role = body.role || 'user'
  let msg
  if (!config.userRoles.includes(role)) {
    msg = '角色不合法'
  }
  Iif (role === config.userRoles[1] && !body.partner) { // 为经销商时;必须选择经销商类型;
    msg = '请选择经销商类型'
  }
  Eif (role !== config.userRoles[1]) { // 不是经销商时,删除这个字段,以防为空,清空数据
    Reflect.deleteProperty(body, 'partner')
  }
  if (msg) {
    return ctx.resMid.resBody(ctx, 422, msg)
  }
  try {
    let user = await User.findById(editUserId)
    Eif (role) {
      user.role = role
    }
    Iif (body.partner) {
      user.partner = body.partner
    }
    Eif (user.role !== config.userRoles[1]) { // 清空之前有的partner角色数据
      user.partner = null
    }
    if (body.status) {
      user.status = body.status
    }
    Iif (body.password) {
      user.password = body.password
    }
    user = await user.save()
    await LogsProxy.createLogs(ctx.req.user._id, user._id, 'User', '修改用户')
    ctx.resMid.resBody(ctx, '', '', { _id: user._id })
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {put} user/modMe 修改自己用户
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName modMe
 * @apiSampleRequest user/modMe
 * @apiPermission user
 *
 * @apiParam (Request body) {String} email 邮箱
 * @apiParam (Request body) {String} username 用户名
 *
 * @apiUse Header
 * @apiUse Response
 */
exports.modMe = async(ctx, next) => {
  const body = ctx.request.body
  const username = body.username ? body.username.replace(/(^\s+)|(\s+$)/g, '') : ''
  let msg
  if (username === '') {
    msg = '用户名不能为空'
  } else if (username.length <= 2 || username.length > 15 || !USERNAME_REGEXP.test(username)) {
    msg = '用户名不合法'
  }
  if (msg) {
    return ctx.resMid.resBody(ctx, 422, msg)
  }
  let user = ctx.req.user
  user.username = username
  try {
    // TODO chagne use update can usage the common validator
    // var unset = { $unset: { username: 1 } };
    // var opts = { runValidators: true };
    // User.update({}, unset, opts, function(err) {})
 
    user = await user.save()
    await LogsProxy.createLogs(ctx.req.user._id, user._id, 'User', '修改用户自己')
    ctx.resMid.resBody(ctx, '', '', user.userInfo)
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {delete} user/delOne/:id 删除用户
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName delOne
 * @apiSampleRequest user/delOne/:id
 * @apiPermission admin
 *
 * @apiUse Header
 * @apiUse Response
 */
exports.delOne = async(ctx, next) => {
  const userId = ctx.req.user._id
  if (String(userId) === String(ctx.params.id)) {
    return ctx.resMid.resBody(ctx, 403, '不能删除自己已经登录的账号')
  } else {
    try {
      const user = await User.findByIdAndRemove(ctx.params.id)
      await LogsProxy.createLogs(ctx.req.user._id, user._id, 'User', '删除用户')
      ctx.resMid.resBody(ctx, '', '')
    } catch (err) {
      ctx.throw(err)
    }
  }
}
 
 
exports.password = async(ctx, next) => {
  const body = ctx.request.body
  const oldPassword = body.oldPassword ? body.oldPassword.replace(/(^\s+)|(\s+$)/g, '') : ''
  const newPassword = body.newPassword ? body.newPassword.replace(/(^\s+)|(\s+$)/g, '') : ''
  let msg
  if (oldPassword.length <= 5 || oldPassword.length > 20 || !PWD_REGEXP.test(oldPassword)) {
    msg = '旧密码不合法,只能输入6-20个字母、数字、下划线'
  }
  if (newPassword.length <= 5 || newPassword.length > 20 || !PWD_REGEXP.test(newPassword)) {
    msg = '新密码不合法,只能输入6-20个字母、数字、下划线'
  }
  if (msg) {
    return ctx.resMid.resBody(ctx, 422, msg)
  }
  let user = ctx.req.user
  try {
    user = await User.findById(user._id)
    if (user.authenticate(oldPassword)) {
      user.password = newPassword;
      await user.save()
    } else {
      ctx.throw('新旧密码一致')
    }
    await LogsProxy.createLogs(ctx.req.user._id, user._id, 'User', '修改用户密码')
    ctx.resMid.resBody(ctx, '', '', user.userInfo)
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {get} user/getUserProvider 获取自己绑定的社交账号
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName getUserProvider
 * @apiSampleRequest user/getUserProvider
 * @apiPermission user
 *
 * @apiUse Header
 * @apiUse Response
 */
exports.getUserProvider = async(ctx, next) => {
  try {
    const user = await User.findById(ctx.req.user._id)
    ctx.resMid.resBody(ctx, '', '', user.providerInfo)
  } catch (err) {
    ctx.throw(err)
  }
}
 
/**
 * @api {get} user/getSnsLogins 获取第三方登录列表
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName getSnsLogins
 * @apiSampleRequest user/getSnsLogins
 * @apiPermission none
 *
 * @apiUse Response
 */
exports.getSnsLogins = async(ctx, next) => {
  Eif (config.snsLogins) {
    ctx.resMid.resBody(ctx, '', '', config.snsLogins)
  } else {
    ctx.throw(404)
  }
}
 
/**
 * @api {get} user/getCaptcha 获取验证码
 * @apiDescription 作者:samy
 *
 * @apiGroup user
 * @apiName getCaptcha
 * @apiSampleRequest user/getCaptcha
 * @apiPermission none
 *
 * @apiUse Header
 * @apiUse Response
 */
exports.getCaptcha = async(ctx, next) => {
  const { token, buffer } = await captcha({ size: 6 })
  ctx.session.captcha = token
  ctx.resMid.resBody(ctx, '', '', buffer)
}