add-user.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. const {
  2. findUser
  3. } = require('../../lib/utils/account')
  4. const {
  5. ERROR
  6. } = require('../../common/error')
  7. const {
  8. userCollection
  9. } = require('../../common/constants')
  10. const PasswordUtils = require('../../lib/utils/password')
  11. /**
  12. * 新增用户
  13. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#add-user
  14. * @param {Object} params
  15. * @param {String} params.username 用户名
  16. * @param {String} params.password 密码
  17. * @param {String} params.nickname 昵称
  18. * @param {Array} params.authorizedApp 允许登录的AppID列表
  19. * @param {Array} params.role 用户角色列表
  20. * @param {String} params.mobile 手机号
  21. * @param {String} params.email 邮箱
  22. * @param {Array} params.tags 用户标签
  23. * @param {Number} params.status 用户状态
  24. * @returns
  25. */
  26. module.exports = async function (params = {}) {
  27. const schema = {
  28. username: 'username',
  29. password: 'password',
  30. authorizedApp: {
  31. required: false,
  32. type: 'array<string>'
  33. }, // 指定允许登录的app,传空数组或不传时表示可以不可以在任何端登录
  34. nickname: {
  35. required: false,
  36. type: 'nickname'
  37. },
  38. role: {
  39. require: false,
  40. type: 'array<string>'
  41. },
  42. mobile: {
  43. required: false,
  44. type: 'mobile'
  45. },
  46. email: {
  47. required: false,
  48. type: 'email'
  49. },
  50. tags: {
  51. required: false,
  52. type: 'array<string>'
  53. },
  54. status: {
  55. required: false,
  56. type: 'number'
  57. }
  58. }
  59. this.middleware.validate(params, schema)
  60. const {
  61. username,
  62. password,
  63. authorizedApp,
  64. nickname,
  65. role,
  66. mobile,
  67. email,
  68. tags,
  69. status
  70. } = params
  71. const userMatched = await findUser({
  72. userQuery: {
  73. username,
  74. mobile,
  75. email
  76. },
  77. authorizedApp
  78. })
  79. if (userMatched.length) {
  80. throw {
  81. errCode: ERROR.ACCOUNT_EXISTS
  82. }
  83. }
  84. const passwordUtils = new PasswordUtils({
  85. passwordSecret: this.config.passwordSecret
  86. })
  87. const {
  88. passwordHash,
  89. version
  90. } = passwordUtils.generatePasswordHash({
  91. password
  92. })
  93. const data = {
  94. username,
  95. password: passwordHash,
  96. password_secret_version: version,
  97. dcloud_appid: authorizedApp || [],
  98. nickname,
  99. role: role || [],
  100. mobile,
  101. email,
  102. tags: tags || [],
  103. status
  104. }
  105. if (email) {
  106. data.email_confirmed = 1
  107. }
  108. if (mobile) {
  109. data.mobile_confirmed = 1
  110. }
  111. await userCollection.add(data)
  112. return {
  113. errCode: 0,
  114. errMsg: ''
  115. }
  116. }