20180927102719-init-serverurl.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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('\'app:siteUrl\' is already exists. This migration terminates without any changes.');
  26. return;
  27. }
  28. // find all callbackUrls
  29. const configs = await Config.find({
  30. $or: [
  31. { key: 'security:passport-github:callbackUrl' },
  32. { key: 'security:passport-google:callbackUrl' },
  33. { key: 'security:passport-saml:callbackUrl' },
  34. ],
  35. });
  36. // determine serverUrl
  37. let siteUrl;
  38. if (configs.length > 0) {
  39. logger.info(`${configs.length} configs which has callbackUrl found: `);
  40. logger.info(configs);
  41. // extract domain
  42. const siteUrls = configs.map((config) => {
  43. // see https://regex101.com/r/Q0Isjo/2
  44. const match = config.value.match(/^"(https?:\/\/[^/]+).*"$/);
  45. return (match != null) ? match[1] : null;
  46. }).filter((value) => { return value != null });
  47. // determine serverUrl if all values are same
  48. if (siteUrls.length > 0 && isAllValuesSame(siteUrls)) {
  49. siteUrl = siteUrls[0];
  50. }
  51. }
  52. if (siteUrl != null) {
  53. const key = 'app:siteUrl';
  54. await Config.findOneAndUpdate(
  55. { key },
  56. { key, value: JSON.stringify(siteUrl) },
  57. { upsert: true },
  58. );
  59. logger.info('Migration has successfully applied');
  60. }
  61. },
  62. async down(db) {
  63. logger.info('Rollback migration');
  64. await mongoose.connect(getMongoUri(), mongoOptions);
  65. // remote 'app:siteUrl'
  66. await Config.findOneAndDelete({
  67. key: 'app:siteUrl',
  68. });
  69. logger.info('Migration has been successfully rollbacked');
  70. },
  71. };