20180927102719-init-serverurl.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import mongoose from 'mongoose';
  2. import { getMongoUri, mongoOptions } from '@growi/core';
  3. import Config from '~/server/models/config';
  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. mongoose.connect(getMongoUri(), mongoOptions);
  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(getMongoUri(), mongoOptions);
  69. // remote 'app:siteUrl'
  70. await Config.findOneAndDelete({
  71. ns: 'crowi',
  72. key: 'app:siteUrl',
  73. });
  74. logger.info('Migration has been successfully rollbacked');
  75. },
  76. };