register-admin.js 1.2 KB
Newer Older
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
const {
  userCollection
} = require('../../common/constants')
const {
  ERROR
} = require('../../common/error')
const {
  preRegisterWithPassword,
  postRegister
} = require('../../lib/utils/register')

/**
 * 注册管理员
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#register-admin
 * @param {Object} params
 * @param {String} params.username   用户名
 * @param {String} params.password   密码
 * @param {String} params.nickname   昵称
 * @returns
 */
module.exports = async function (params = {}) {
  const schema = {
    username: 'username',
    password: 'password',
    nickname: {
      type: 'nickname',
      required: false
    }
  }
  this.middleware.validate(params, schema)
  const {
    username,
    password,
    nickname
  } = params
  const getAdminRes = await userCollection.where({
    role: 'admin'
  }).limit(1).get()
  if (getAdminRes.data.length > 0) {
    return {
      errCode: ERROR.ADMIN_EXISTS
    }
  }
  const {
    user,
    extraData
  } = await preRegisterWithPassword.call(this, {
    user: {
      username
    },
    password
  })
  return postRegister.call(this, {
    user,
    extraData: {
      ...extraData,
      nickname,
      role: ['admin']
    }
  })
}