Просмотр исходного кода

replace appService.getSiteUrl with growiInfoService.getSiteUrl

Yuki Takei 1 год назад
Родитель
Сommit
47c7c3aae2

+ 2 - 2
apps/app/src/pages/admin/security.page.tsx

@@ -92,9 +92,9 @@ const AdminSecuritySettingsPage: NextPage<Props> = (props) => {
 const injectServerConfigurations = async(context: GetServerSidePropsContext, props: Props): Promise<void> => {
   const req: CrowiRequest = context.req as CrowiRequest;
   const { crowi } = req;
-  const { appService, mailService } = crowi;
+  const { growiInfoService, mailService } = crowi;
 
-  props.siteUrl = appService.getSiteUrl();
+  props.siteUrl = growiInfoService.getSiteUrl();
   props.isMailerSetup = mailService.isMailerSetup;
 };
 

+ 2 - 2
apps/app/src/pages/admin/slack-integration.page.tsx

@@ -49,9 +49,9 @@ const AdminSlackIntegrationPage: NextPage<Props> = (props) => {
 const injectServerConfigurations = async(context: GetServerSidePropsContext, props: Props): Promise<void> => {
   const req: CrowiRequest = context.req as CrowiRequest;
   const { crowi } = req;
-  const { appService } = crowi;
+  const { growiInfoService } = crowi;
 
-  props.siteUrl = appService.getSiteUrl();
+  props.siteUrl = growiInfoService.getSiteUrl();
 };
 
 

+ 2 - 1
apps/app/src/server/crowi/express-init.js

@@ -10,6 +10,7 @@ import registerSafeRedirectFactory from '../middlewares/safe-redirect';
 
 const logger = loggerFactory('growi:crowi:express-init');
 
+/** @param {import('./index').default} crowi Crowi instance */
 module.exports = function(crowi, app) {
   const express = require('express');
   const compression = require('compression');
@@ -72,7 +73,7 @@ module.exports = function(crowi, app) {
     app.set('tzoffset', crowi.appService.getTzoffset());
 
     res.locals.req = req;
-    res.locals.baseUrl = crowi.appService.getSiteUrl();
+    res.locals.baseUrl = crowi.growiInfoService.getSiteUrl();
     res.locals.env = env;
     res.locals.now = now;
 

+ 9 - 0
apps/app/src/server/crowi/index.js

@@ -69,6 +69,9 @@ class Crowi {
   /** @type {FileUploader} */
   fileUploadService;
 
+  /** @type {import('../service/growi-info').GrowiInfoService} */
+  growiInfoService;
+
   /** @type {import('../service/page').IPageService} */
   pageService;
 
@@ -176,6 +179,7 @@ Crowi.prototype.init = async function() {
   ]);
 
   await Promise.all([
+    this.setupGrowiInfoService(),
     this.setupPassport(),
     this.setupSearcher(),
     this.setupMailer(),
@@ -658,6 +662,11 @@ Crowi.prototype.setUpFileUploaderSwitchService = async function() {
   }
 };
 
+Crowi.prototype.setupGrowiInfoService = async function() {
+  const { growiInfoService } = await import('../service/growi-info');
+  this.growiInfoService = growiInfoService;
+};
+
 /**
  * setup AttachmentService
  */

+ 2 - 1
apps/app/src/server/routes/apiv3/forgot-password.js

@@ -7,6 +7,7 @@ import { generateAddActivityMiddleware } from '~/server/middlewares/add-activity
 import injectResetOrderByTokenMiddleware from '~/server/middlewares/inject-reset-order-by-token-middleware';
 import PasswordResetOrder from '~/server/models/password-reset-order';
 import { configManager } from '~/server/service/config-manager';
+import { growiInfoService } from '~/server/service/growi-info';
 import loggerFactory from '~/utils/logger';
 
 import { apiV3FormValidator } from '../../middlewares/apiv3-form-validator';
@@ -119,7 +120,7 @@ module.exports = (crowi) => {
   router.post('/', checkPassportStrategyMiddleware, validator.email, apiV3FormValidator, addActivity, async(req, res) => {
     const { email } = req.body;
     const locale = configManager.getConfig('app:globalLang');
-    const appUrl = appService.getSiteUrl();
+    const appUrl = growiInfoService.getSiteUrl();
 
     try {
       const user = await User.findOne({ email });

+ 5 - 4
apps/app/src/server/routes/apiv3/slack-integration.js

@@ -10,6 +10,7 @@ import createError from 'http-errors';
 
 import { SlackCommandHandlerError } from '~/server/models/vo/slack-command-handler-error';
 import { configManager } from '~/server/service/config-manager';
+import { growiInfoService } from '~/server/service/growi-info';
 import loggerFactory from '~/utils/logger';
 
 
@@ -104,7 +105,7 @@ module.exports = (crowi) => {
       id: req.body.channel_id,
       name: req.body.channel_name,
     };
-    const siteUrl = crowi.appService.getSiteUrl();
+    const siteUrl = growiInfoService.getSiteUrl();
 
     let commandPermission;
     if (extractPermissions != null) { // with proxy
@@ -145,7 +146,7 @@ module.exports = (crowi) => {
     res.send();
 
     const { interactionPayloadAccessor } = req;
-    const siteUrl = crowi.appService.getSiteUrl();
+    const siteUrl = growiInfoService.getSiteUrl();
 
     const { actionId, callbackId } = interactionPayloadAccessor.getActionIdAndCallbackIdFromPayLoad();
     const callbacIdkOrActionId = callbackId || actionId;
@@ -214,7 +215,7 @@ module.exports = (crowi) => {
   function getRespondUtil(responseUrl) {
     const proxyUri = slackIntegrationService.proxyUriForCurrentType ?? null; // can be null
 
-    const appSiteUrl = crowi.appService.getSiteUrl();
+    const appSiteUrl = growiInfoService.getSiteUrl();
     if (appSiteUrl == null || appSiteUrl === '') {
       logger.error('App site url must exist.');
       throw SlackCommandHandlerError('App site url must exist.');
@@ -268,7 +269,7 @@ module.exports = (crowi) => {
 
     // Send response immediately to avoid opelation_timeout error
     // See https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
-    const appSiteUrl = crowi.appService.getSiteUrl();
+    const appSiteUrl = growiInfoService.getSiteUrl();
     try {
       await respondUtil.respond({
         text: 'Processing your request ...',

+ 3 - 2
apps/app/src/server/routes/apiv3/user-activation.ts

@@ -8,6 +8,7 @@ import { SupportedAction } from '~/interfaces/activity';
 import { RegistrationMode } from '~/interfaces/registration-mode';
 import UserRegistrationOrder from '~/server/models/user-registration-order';
 import { configManager } from '~/server/service/config-manager';
+import { growiInfoService } from '~/server/service/growi-info';
 import { getTranslation } from '~/server/service/i18next';
 import loggerFactory from '~/utils/logger';
 
@@ -146,7 +147,7 @@ export const completeRegistrationAction = (crowi) => {
             const appTitle = appService.getAppTitle();
             const locale = configManager.getConfig('app:globalLang');
             const template = path.join(crowi.localeDir, `${locale}/admin/userWaitingActivation.ejs`);
-            const url = appService.getSiteUrl();
+            const url = growiInfoService.getSiteUrl();
 
             sendEmailToAllAdmins(userData, admins, appTitle, mailService, template, url);
           }
@@ -219,7 +220,7 @@ async function makeRegistrationEmailToken(email, crowi) {
   }
 
   const locale = configManager.getConfig('app:globalLang');
-  const appUrl = appService.getSiteUrl();
+  const appUrl = growiInfoService.getSiteUrl();
 
   const userRegistrationOrder = await UserRegistrationOrder.createUserRegistrationOrder(email);
   const grwTzoffsetSec = crowi.appService.getTzoffset() * 60;

+ 4 - 2
apps/app/src/server/routes/apiv3/users.js

@@ -16,6 +16,7 @@ import ExternalAccount from '~/server/models/external-account';
 import { serializePageSecurely } from '~/server/models/serializers';
 import UserGroupRelation from '~/server/models/user-group-relation';
 import { configManager } from '~/server/service/config-manager';
+import { growiInfoService } from '~/server/service/growi-info';
 import { deleteCompletelyUserHomeBySystem } from '~/server/service/page/delete-completely-user-home-by-system';
 import loggerFactory from '~/utils/logger';
 
@@ -74,6 +75,7 @@ const validator = {};
  *            example: 2010-01-01T00:00:00.000Z
  */
 
+/** @param {import('~/server/crowi').default} crowi Crowi instance */
 module.exports = (crowi) => {
   const loginRequired = require('../../middlewares/login-required')(crowi, true);
   const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
@@ -159,7 +161,7 @@ module.exports = (crowi) => {
           vars: {
             email: user.email,
             password: user.password,
-            url: crowi.appService.getSiteUrl(),
+            url: growiInfoService.getSiteUrl(),
             appTitle,
           },
         });
@@ -190,7 +192,7 @@ module.exports = (crowi) => {
       vars: {
         email: user.email,
         password: user.password,
-        url: crowi.appService.getSiteUrl(),
+        url: growiInfoService.getSiteUrl(),
         appTitle,
       },
     });

+ 4 - 1
apps/app/src/server/routes/login.js

@@ -2,9 +2,12 @@ import { SupportedAction, SupportedTargetModel } from '~/interfaces/activity';
 import { configManager } from '~/server/service/config-manager';
 import loggerFactory from '~/utils/logger';
 
+import { growiInfoService } from '../service/growi-info';
+
 // disable all of linting
 // because this file is a deprecated legacy of Crowi
 
+/** @param {import('~/server/crowi').default} crowi Crowi instance */
 module.exports = function(crowi, app) {
   const logger = loggerFactory('growi:routes:login');
   const path = require('path');
@@ -30,7 +33,7 @@ module.exports = function(crowi, app) {
         vars: {
           adminUser: admin,
           createdUser: userData,
-          url: appService.getSiteUrl(),
+          url: growiInfoService.getSiteUrl(),
           appTitle,
         },
       });

+ 2 - 1
apps/app/src/server/service/export.js

@@ -3,6 +3,7 @@ import { getGrowiVersion } from '~/utils/growi-version';
 import loggerFactory from '~/utils/logger';
 
 import { configManager } from './config-manager';
+import { growiInfoService } from './growi-info';
 
 const logger = loggerFactory('growi:services:ExportService'); // eslint-disable-line no-unused-vars
 
@@ -99,7 +100,7 @@ class ExportService {
 
     const metaData = {
       version: getGrowiVersion(),
-      url: this.appService.getSiteUrl(),
+      url: growiInfoService.getSiteUrl(),
       passwordSeed,
       exportedAt: new Date(),
       envVars: configManager.getManagedEnvVars(),

+ 2 - 1
apps/app/src/server/service/global-notification/global-notification-slack.js

@@ -6,6 +6,7 @@ import loggerFactory from '~/utils/logger';
 import {
   prepareSlackMessageForGlobalNotification,
 } from '../../util/slack';
+import { growiInfoService } from '../growi-info';
 
 const logger = loggerFactory('growi:service:GlobalNotificationSlackService'); // eslint-disable-line no-unused-vars
 const urljoin = require('url-join');
@@ -65,7 +66,7 @@ class GlobalNotificationSlackService {
    * @return  {string} slack message body
    */
   generateMessageBody(event, id, path, triggeredBy, { comment, oldPath }) {
-    const siteUrl = this.crowi.appService.getSiteUrl();
+    const siteUrl = growiInfoService.getSiteUrl();
     const parmaLink = `<${urljoin(siteUrl, id)}|${path}>`;
     const pathLink = `<${urljoin(siteUrl, encodeSpaces(path))}|${path}>`;
     const username = `<${urljoin(siteUrl, 'user', triggeredBy.username)}|${triggeredBy.username}>`;

+ 13 - 16
apps/app/src/server/service/passport.ts

@@ -20,6 +20,7 @@ import S2sMessage from '../models/vo/s2s-message';
 
 import { configManager } from './config-manager';
 import type { ConfigKey } from './config-manager/config-definition';
+import { growiInfoService } from './growi-info';
 import type { S2sMessageHandlable } from './s2s-messaging/handlable';
 
 const logger = loggerFactory('growi:service:PassportService');
@@ -449,7 +450,6 @@ class PassportService implements S2sMessageHandlable {
 
     this.resetGoogleStrategy();
 
-    const { configManager } = this.crowi;
     const isGoogleEnabled = configManager.getConfig('security:passport-google:isEnabled');
 
     // when disabled
@@ -463,8 +463,8 @@ class PassportService implements S2sMessageHandlable {
         {
           clientID: configManager.getConfig('security:passport-google:clientId'),
           clientSecret: configManager.getConfig('security:passport-google:clientSecret'),
-          callbackURL: (this.crowi.appService.getSiteUrl() != null)
-            ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/google/callback') // auto-generated with v3.2.4 and above
+          callbackURL: configManager.getConfig('app:siteUrl') != null
+            ? urljoin(growiInfoService.getSiteUrl(), '/passport/google/callback') // auto-generated with v3.2.4 and above
             : configManager.getConfig('security:passport-google:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
           skipUserProfile: false,
         },
@@ -497,7 +497,6 @@ class PassportService implements S2sMessageHandlable {
 
     this.resetGitHubStrategy();
 
-    const { configManager } = this.crowi;
     const isGitHubEnabled = configManager.getConfig('security:passport-github:isEnabled');
 
     // when disabled
@@ -511,8 +510,8 @@ class PassportService implements S2sMessageHandlable {
         {
           clientID: configManager.getConfig('security:passport-github:clientId'),
           clientSecret: configManager.getConfig('security:passport-github:clientSecret'),
-          callbackURL: (this.crowi.appService.getSiteUrl() != null)
-            ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/github/callback') // auto-generated with v3.2.4 and above
+          callbackURL: configManager.getConfig('app:siteUrl') != null
+            ? urljoin(growiInfoService.getSiteUrl(), '/passport/github/callback') // auto-generated with v3.2.4 and above
             : configManager.getConfig('security:passport-github:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
           skipUserProfile: false,
         },
@@ -545,7 +544,6 @@ class PassportService implements S2sMessageHandlable {
 
     this.resetOidcStrategy();
 
-    const { configManager } = this.crowi;
     const isOidcEnabled = configManager.getConfig('security:passport-oidc:isEnabled');
 
     // when disabled
@@ -567,8 +565,8 @@ class PassportService implements S2sMessageHandlable {
     const issuerHost = configManager.getConfig('security:passport-oidc:issuerHost');
     const clientId = configManager.getConfig('security:passport-oidc:clientId');
     const clientSecret = configManager.getConfig('security:passport-oidc:clientSecret');
-    const redirectUri = (configManager.getConfig('app:siteUrl') != null)
-      ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/oidc/callback')
+    const redirectUri = configManager.getConfig('app:siteUrl') != null
+      ? urljoin(growiInfoService.getSiteUrl(), '/passport/oidc/callback')
       : configManager.getConfig('security:passport-oidc:callbackUrl'); // DEPRECATED: backward compatible with v3.2.3 and below
 
     // Prevent request timeout error on app init
@@ -716,10 +714,10 @@ class PassportService implements S2sMessageHandlable {
    * @returns instance of OIDCIssuer
    */
   async getOIDCIssuerInstance(issuerHost: string): Promise<void | OIDCIssuer> {
-    const OIDC_TIMEOUT_MULTIPLIER = await configManager.getConfig('security:passport-oidc:timeoutMultiplier');
-    const OIDC_DISCOVERY_RETRIES = await configManager.getConfig('security:passport-oidc:discoveryRetries');
-    const OIDC_ISSUER_TIMEOUT_OPTION = await configManager.getConfig('security:passport-oidc:oidcIssuerTimeoutOption');
-    const oidcIssuerHostReady = await this.isOidcHostReachable(issuerHost);
+    const OIDC_TIMEOUT_MULTIPLIER = configManager.getConfig('security:passport-oidc:timeoutMultiplier');
+    const OIDC_DISCOVERY_RETRIES = configManager.getConfig('security:passport-oidc:discoveryRetries');
+    const OIDC_ISSUER_TIMEOUT_OPTION = configManager.getConfig('security:passport-oidc:oidcIssuerTimeoutOption');
+    const oidcIssuerHostReady = this.isOidcHostReachable(issuerHost);
     if (!oidcIssuerHostReady) {
       logger.error('OidcStrategy: setup failed');
       return;
@@ -751,7 +749,6 @@ class PassportService implements S2sMessageHandlable {
 
     this.resetSamlStrategy();
 
-    const { configManager } = this.crowi;
     const isSamlEnabled = configManager.getConfig('security:passport-saml:isEnabled');
 
     // when disabled
@@ -764,8 +761,8 @@ class PassportService implements S2sMessageHandlable {
       new SamlStrategy(
         {
           entryPoint: configManager.getConfig('security:passport-saml:entryPoint'),
-          callbackUrl: (this.crowi.appService.getSiteUrl() != null)
-            ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/saml/callback') // auto-generated with v3.2.4 and above
+          callbackUrl: configManager.getConfig('app:siteUrl') != null
+            ? urljoin(growiInfoService.getSiteUrl(), '/passport/saml/callback') // auto-generated with v3.2.4 and above
             : configManager.getConfig('security:passport-saml:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
           issuer: configManager.getConfig('security:passport-saml:issuer'),
           cert: configManager.getConfig('security:passport-saml:cert'),

+ 7 - 1
apps/app/src/server/service/slack-command-handler/create-page-service.js

@@ -1,9 +1,12 @@
 import { markdownSectionBlock } from '@growi/slack/dist/utils/block-kit-builder';
 import { reshapeContentsBody } from '@growi/slack/dist/utils/reshape-contents-body';
 
+import Crowi from '~/server/crowi';
 import { generalXssFilter } from '~/services/general-xss-filter';
 import loggerFactory from '~/utils/logger';
 
+import { growiInfoService } from '../growi-info';
+
 // eslint-disable-next-line no-unused-vars
 const logger = loggerFactory('growi:service:CreatePageService');
 
@@ -12,6 +15,9 @@ const mongoose = require('mongoose');
 
 class CreatePageService {
 
+  /** @type {import('~/server/crowi').default} Crowi instance */
+  crowi;
+
   constructor(crowi) {
     this.crowi = crowi;
   }
@@ -29,7 +35,7 @@ class CreatePageService {
     const page = await this.crowi.pageService.create(normalizedPath, reshapedContentsBody, userOrDummyUser, {});
 
     // Send a message when page creation is complete
-    const growiUri = this.crowi.appService.getSiteUrl();
+    const growiUri = growiInfoService.getSiteUrl();
     await respondUtil.respond({
       text: 'Page has been created',
       blocks: [

+ 4 - 1
apps/app/src/server/service/slack-command-handler/help.js

@@ -5,13 +5,16 @@
 
 import { markdownSectionBlock } from '@growi/slack/dist/utils/block-kit-builder';
 
+import { growiInfoService } from '../growi-info';
+
+/** @param {import('~/server/crowi').default} crowi Crowi instance */
 module.exports = (crowi) => {
   const BaseSlackCommandHandler = require('./slack-command-handler');
   const handler = new BaseSlackCommandHandler();
 
   handler.handleCommand = async(growiCommand, client, body, respondUtil) => {
     const appTitle = crowi.appService.getAppTitle();
-    const appSiteUrl = crowi.appService.getSiteUrl();
+    const appSiteUrl = growiInfoService.getSiteUrl();
     // adjust spacing
     let message = `*Help* (*${appTitle}* at ${appSiteUrl})\n\n`;
     message += 'Usage:     `/growi [command] [args]`\n\n';

+ 4 - 2
apps/app/src/server/service/slack-command-handler/search.js

@@ -5,6 +5,8 @@ import { generateLastUpdateMrkdwn } from '@growi/slack/dist/utils/generate-last-
 
 import loggerFactory from '~/utils/logger';
 
+import { growiInfoService } from '../growi-info';
+
 
 const logger = loggerFactory('growi:service:SlackCommandHandler:search');
 
@@ -56,7 +58,7 @@ module.exports = (crowi) => {
   }
 
   function buildRespondBodyForSearchResult(searchResult, growiCommandArgs) {
-    const appUrl = crowi.appService.getSiteUrl();
+    const appUrl = growiInfoService.getSiteUrl();
     const appTitle = crowi.appService.getAppTitle();
 
     const {
@@ -237,7 +239,7 @@ module.exports = (crowi) => {
   handler.shareSinglePageResult = async function(client, payload, interactionPayloadAccessor, respondUtil) {
     const { user } = payload;
 
-    const appUrl = crowi.appService.getSiteUrl();
+    const appUrl = growiInfoService.getSiteUrl();
     const appTitle = crowi.appService.getAppTitle();
 
     const value = interactionPayloadAccessor.firstAction()?.value; // shareSinglePage action must have button action

+ 4 - 3
apps/app/src/server/service/slack-event-handler/link-shared.ts

@@ -11,8 +11,9 @@ import loggerFactory from '~/utils/logger';
 import type {
   DataForUnfurl, PublicData, UnfurlEventLink, UnfurlRequestEvent,
 } from '../../interfaces/slack-integration/link-shared-unfurl';
+import { growiInfoService } from '../growi-info';
 
-import { SlackEventHandler } from './base-event-handler';
+import type { SlackEventHandler } from './base-event-handler';
 
 const logger = loggerFactory('growi:service:SlackEventHandler:link-shared');
 
@@ -38,7 +39,7 @@ export class LinkSharedEventHandler implements SlackEventHandler<UnfurlRequestEv
 
   async handleEvent(client: WebClient, growiBotEvent: GrowiBotEvent<UnfurlRequestEvent>, data?: {origin: string}): Promise<void> {
     const { event } = growiBotEvent;
-    const origin = data?.origin || this.crowi.appService.getSiteUrl();
+    const origin = data?.origin || growiInfoService.getSiteUrl();
     const { channel, message_ts: ts, links } = event;
 
     let unfurlData: DataForUnfurl[];
@@ -90,7 +91,7 @@ export class LinkSharedEventHandler implements SlackEventHandler<UnfurlRequestEv
     const { pageBody: text, updatedAt } = body;
 
     const appTitle = this.crowi.appService.getAppTitle();
-    const siteUrl = this.crowi.appService.getSiteUrl();
+    const siteUrl = growiInfoService.getSiteUrl();
 
     const attachment: MessageAttachment = {
       title: body.path,

+ 2 - 1
apps/app/src/server/service/user-notification/index.ts

@@ -7,6 +7,7 @@ import {
   prepareSlackMessageForPage,
   prepareSlackMessageForComment,
 } from '../../util/slack';
+import { growiInfoService } from '../growi-info';
 
 /**
  * service class of UserNotification
@@ -51,7 +52,7 @@ export class UserNotificationService {
     const slackChannels: (string|null)[] = toArrayFromCsv(slackChannelsStr);
 
     const appTitle = appService.getAppTitle();
-    const siteUrl = appService.getSiteUrl();
+    const siteUrl = growiInfoService.getSiteUrl();
 
     const promises = slackChannels.map(async(chan) => {
       let messageObj;