external-account.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const debug = require('debug')('crowi:models:external-account');
  2. const mongoose = require('mongoose');
  3. const uniqueValidator = require('mongoose-unique-validator');
  4. const ObjectId = mongoose.Schema.Types.ObjectId;
  5. /*
  6. * define schema
  7. */
  8. const schema = new mongoose.Schema({
  9. providerType: { type: String, required: true },
  10. accountId: { type: String, required: true },
  11. user: { type: ObjectId, ref: 'User', required: true },
  12. createdAt: { type: Date, default: Date.now, required: true },
  13. });
  14. // compound index
  15. schema.index({ providerType: 1, accountId: 1 });
  16. // apply plugins
  17. schema.plugin(uniqueValidator);
  18. /**
  19. * ExternalAccount Class
  20. *
  21. * @class ExternalAccount
  22. */
  23. class ExternalAccount {
  24. /**
  25. * get the populated user entity
  26. *
  27. * @returns Promise<User>
  28. * @memberof ExternalAccount
  29. */
  30. getPopulatedUser() {
  31. return this.populate('user').execPopulate()
  32. .then((account) => {
  33. return account.user;
  34. })
  35. }
  36. /**
  37. * find an account or register if not found
  38. *
  39. * @static
  40. * @param {string} providerType
  41. * @param {string} accountId
  42. * @param {object} createUserFunction the function that create a user document and return Promise<User>
  43. * @returns {Promise<ExternalAccount>}
  44. * @memberof ExternalAccount
  45. */
  46. static findOrRegister(providerType, accountId, createUserFunction) {
  47. return this.findOne({ providerType, accountId })
  48. .then((account) => {
  49. // found
  50. if (account != null) {
  51. debug(`ExternalAccount '${accountId}' is found `, account);
  52. return account;
  53. }
  54. // not found
  55. else {
  56. debug(`ExternalAccount '${accountId}' is not found, it is going to be registered.`);
  57. return createUserFunction().then((user) => {
  58. return this.create({ providerType: 'ldap', accountId, user: user._id });
  59. });
  60. }
  61. });
  62. }
  63. }
  64. module.exports = function(crowi) {
  65. schema.loadClass(ExternalAccount);
  66. return mongoose.model('ExternalAccount', schema);
  67. }