register-admin.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const {
  2. userCollection
  3. } = require('../../common/constants')
  4. const {
  5. ERROR
  6. } = require('../../common/error')
  7. const {
  8. preRegisterWithPassword,
  9. postRegister
  10. } = require('../../lib/utils/register')
  11. /**
  12. * 注册管理员
  13. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#register-admin
  14. * @param {Object} params
  15. * @param {String} params.username 用户名
  16. * @param {String} params.password 密码
  17. * @param {String} params.nickname 昵称
  18. * @returns
  19. */
  20. module.exports = async function (params = {}) {
  21. const schema = {
  22. username: 'username',
  23. password: 'password',
  24. nickname: {
  25. type: 'nickname',
  26. required: false
  27. }
  28. }
  29. this.middleware.validate(params, schema)
  30. const {
  31. username,
  32. password,
  33. nickname
  34. } = params
  35. const getAdminRes = await userCollection.where({
  36. role: 'admin'
  37. }).limit(1).get()
  38. if (getAdminRes.data.length > 0) {
  39. const [admin] = getAdminRes.data
  40. const appId = this.getUniversalClientInfo().appId
  41. if (!admin.dcloud_appid || (admin.dcloud_appid && admin.dcloud_appid.includes(appId))) {
  42. return {
  43. errCode: ERROR.ADMIN_EXISTS,
  44. errMsg: this.t('uni-id-admin-exists')
  45. }
  46. } else {
  47. return {
  48. errCode: ERROR.ADMIN_EXISTS,
  49. errMsg: this.t('uni-id-admin-exist-in-other-apps')
  50. }
  51. }
  52. }
  53. const {
  54. user,
  55. extraData
  56. } = await preRegisterWithPassword.call(this, {
  57. user: {
  58. username
  59. },
  60. password
  61. })
  62. return postRegister.call(this, {
  63. user,
  64. extraData: {
  65. ...extraData,
  66. nickname,
  67. role: ['admin']
  68. }
  69. })
  70. }