20180927102719-init-serverurl.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. require('module-alias/register');
  2. const logger = require('@alias/logger')('growi:migrate:init-serverurl');
  3. const mongoose = require('mongoose');
  4. const config = require('@root/config/migrate');
  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 = 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. await Config.findOneAndUpdateByNsAndKey('crowi', 'app:siteUrl', siteUrl);
  57. logger.info('Migration has successfully applied');
  58. }
  59. },
  60. async down(db) {
  61. logger.info('Undo migration');
  62. mongoose.connect(config.mongoUri, config.mongodb.options);
  63. const Config = require('@server/models/config')();
  64. // remote 'app:siteUrl'
  65. await Config.findOneAndDelete({
  66. ns: 'crowi',
  67. key: 'app:siteUrl',
  68. });
  69. logger.info('Migration has successfully undoed');
  70. },
  71. };