20180927102719-init-serverurl.js 2.3 KB

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