20180927102719-init-serverurl.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const logger = require('@alias/logger')('growi:migrate:init-serverurl');
  2. const mongoose = require('mongoose');
  3. const config = require('@root/config/migrate');
  4. const { getModelSafely } = require('@commons/util/mongoose-utils');
  5. /**
  6. * check all values of the array are equal
  7. * @see https://stackoverflow.com/a/35568895
  8. */
  9. function isAllValuesSame(array) {
  10. return !!array.reduce((a, b) => {
  11. return (a === b) ? a : NaN;
  12. });
  13. }
  14. module.exports = {
  15. async up(db) {
  16. logger.info('Apply migration');
  17. mongoose.connect(config.mongoUri, config.mongodb.options);
  18. const Config = getModelSafely('Config') || require('@server/models/config')();
  19. // find 'app:siteUrl'
  20. const siteUrlConfig = await Config.findOne({
  21. ns: 'crowi',
  22. key: 'app:siteUrl',
  23. });
  24. // exit if exists
  25. if (siteUrlConfig != null) {
  26. logger.info('\'app:siteUrl\' is already exists. This migration terminates without any changes.');
  27. return;
  28. }
  29. // find all callbackUrls
  30. const configs = await Config.find({
  31. ns: 'crowi',
  32. $or: [
  33. { key: 'security:passport-github:callbackUrl' },
  34. { key: 'security:passport-google:callbackUrl' },
  35. { key: 'security:passport-twitter:callbackUrl' },
  36. { key: 'security:passport-saml:callbackUrl' },
  37. ],
  38. });
  39. // determine serverUrl
  40. let siteUrl;
  41. if (configs.length > 0) {
  42. logger.info(`${configs.length} configs which has callbackUrl found: `);
  43. logger.info(configs);
  44. // extract domain
  45. const siteUrls = configs.map((config) => {
  46. // see https://regex101.com/r/Q0Isjo/2
  47. const match = config.value.match(/^"(https?:\/\/[^/]+).*"$/);
  48. return (match != null) ? match[1] : null;
  49. }).filter((value) => { return value != null });
  50. // determine serverUrl if all values are same
  51. if (siteUrls.length > 0 && isAllValuesSame(siteUrls)) {
  52. siteUrl = siteUrls[0];
  53. }
  54. }
  55. if (siteUrl != null) {
  56. const ns = 'crowi';
  57. const key = 'app:siteUrl';
  58. await Config.findOneAndUpdate(
  59. { ns, key },
  60. { ns, key, value: JSON.stringify(siteUrl) },
  61. { upsert: true },
  62. );
  63. logger.info('Migration has successfully applied');
  64. }
  65. },
  66. async down(db) {
  67. logger.info('Rollback migration');
  68. mongoose.connect(config.mongoUri, config.mongodb.options);
  69. const Config = getModelSafely('Config') || require('@server/models/config')();
  70. // remote 'app:siteUrl'
  71. await Config.findOneAndDelete({
  72. ns: 'crowi',
  73. key: 'app:siteUrl',
  74. });
  75. logger.info('Migration has been successfully rollbacked');
  76. },
  77. };