external-account.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // disable no-return-await for model functions
  2. /* eslint-disable no-return-await */
  3. const debug = require('debug')('growi:models:external-account');
  4. const mongoose = require('mongoose');
  5. const mongoosePaginate = require('mongoose-paginate-v2');
  6. const uniqueValidator = require('mongoose-unique-validator');
  7. const ObjectId = mongoose.Schema.Types.ObjectId;
  8. /*
  9. * define schema
  10. */
  11. const schema = new mongoose.Schema({
  12. providerType: { type: String, required: true },
  13. accountId: { type: String, required: true },
  14. user: { type: ObjectId, ref: 'User', required: true },
  15. }, {
  16. timestamps: { createdAt: true, updatedAt: false },
  17. });
  18. // compound index
  19. schema.index({ providerType: 1, accountId: 1 }, { unique: true });
  20. // apply plugins
  21. schema.plugin(mongoosePaginate);
  22. schema.plugin(uniqueValidator);
  23. /**
  24. * The Exception class thrown when User.username is duplicated when creating user
  25. *
  26. * @class DuplicatedUsernameException
  27. */
  28. class DuplicatedUsernameException {
  29. constructor(message, user) {
  30. this.name = this.constructor.name;
  31. this.message = message;
  32. this.user = user;
  33. }
  34. }
  35. /**
  36. * ExternalAccount Class
  37. *
  38. * @class ExternalAccount
  39. */
  40. class ExternalAccount {
  41. /**
  42. * limit items num for pagination
  43. *
  44. * @readonly
  45. * @static
  46. * @memberof ExternalAccount
  47. */
  48. static get DEFAULT_LIMIT() {
  49. return 50;
  50. }
  51. static set crowi(crowi) {
  52. this._crowi = crowi;
  53. }
  54. static get crowi() {
  55. return this._crowi;
  56. }
  57. /**
  58. * get the populated user entity
  59. *
  60. * @returns Promise<User>
  61. * @memberof ExternalAccount
  62. */
  63. getPopulatedUser() {
  64. return this.populate('user')
  65. .then((account) => {
  66. return account.user;
  67. });
  68. }
  69. /**
  70. * find an account or register if not found
  71. *
  72. * @static
  73. * @param {string} providerType
  74. * @param {string} accountId
  75. * @param {object} usernameToBeRegistered the username of User entity that will be created when accountId is not found
  76. * @param {object} nameToBeRegistered the name of User entity that will be created when accountId is not found
  77. * @param {object} mailToBeRegistered the mail of User entity that will be created when accountId is not found
  78. * @param {boolean} isSameUsernameTreatedAsIdenticalUser
  79. * @param {boolean} isSameEmailTreatedAsIdenticalUser
  80. * @returns {Promise<ExternalAccount>}
  81. * @memberof ExternalAccount
  82. */
  83. static findOrRegister(providerType, accountId,
  84. usernameToBeRegistered, nameToBeRegistered, mailToBeRegistered,
  85. isSameUsernameTreatedAsIdenticalUser, isSameEmailTreatedAsIdenticalUser) {
  86. //
  87. return this.findOne({ providerType, accountId })
  88. .then((account) => {
  89. // ExternalAccount is found
  90. if (account != null) {
  91. debug(`ExternalAccount '${accountId}' is found `, account);
  92. return account;
  93. }
  94. const User = ExternalAccount.crowi.model('User');
  95. let promise = User.findOne({ username: usernameToBeRegistered });
  96. if (isSameUsernameTreatedAsIdenticalUser && isSameEmailTreatedAsIdenticalUser) {
  97. promise = promise
  98. .then((user) => {
  99. if (user == null) { return User.findOne({ email: mailToBeRegistered }) }
  100. return user;
  101. });
  102. }
  103. else if (isSameEmailTreatedAsIdenticalUser) {
  104. promise = User.findOne({ email: mailToBeRegistered });
  105. }
  106. return promise
  107. .then((user) => {
  108. // when the User that have the same `username` exists
  109. if (user != null) {
  110. throw new DuplicatedUsernameException(`User '${usernameToBeRegistered}' already exists`, user);
  111. }
  112. if (nameToBeRegistered == null) {
  113. // eslint-disable-next-line no-param-reassign
  114. nameToBeRegistered = '';
  115. }
  116. // create a new User with STATUS_ACTIVE
  117. debug(`ExternalAccount '${accountId}' is not found, it is going to be registered.`);
  118. return User.createUser(nameToBeRegistered, usernameToBeRegistered, mailToBeRegistered, undefined, undefined, User.STATUS_ACTIVE);
  119. })
  120. .then((newUser) => {
  121. return this.associate(providerType, accountId, newUser);
  122. });
  123. });
  124. }
  125. /**
  126. * Create ExternalAccount document and associate to existing User
  127. *
  128. * @param {string} providerType
  129. * @param {string} accountId
  130. * @param {object} user
  131. */
  132. static associate(providerType, accountId, user) {
  133. return this.create({ providerType, accountId, user: user._id });
  134. }
  135. /**
  136. * find all entities with pagination
  137. *
  138. * @see https://github.com/edwardhotchkiss/mongoose-paginate
  139. *
  140. * @static
  141. * @param {any} opts mongoose-paginate options object
  142. * @returns {Promise<any>} mongoose-paginate result object
  143. * @memberof ExternalAccount
  144. */
  145. static findAllWithPagination(opts) {
  146. const query = {};
  147. const options = Object.assign({ populate: 'user' }, opts);
  148. if (options.sort == null) {
  149. options.sort = { accountId: 1, createdAt: 1 };
  150. }
  151. if (options.limit == null) {
  152. options.limit = ExternalAccount.DEFAULT_LIMIT;
  153. }
  154. return this.paginate(query, options);
  155. }
  156. }
  157. module.exports = function(crowi) {
  158. ExternalAccount.crowi = crowi;
  159. schema.loadClass(ExternalAccount);
  160. return mongoose.model('ExternalAccount', schema);
  161. };