external-account.js 5.3 KB

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