2
0
Эх сурвалжийг харах

Merge pull request #2923 from weseek/feat/GW-3658-can-use-GCP-from-db-vars

Feat/gw 3658 can use gcp from db vars
Yuki Takei 5 жил өмнө
parent
commit
2a5687ed16

+ 11 - 3
resource/locales/en_US/admin/admin.json

@@ -38,10 +38,17 @@
     "host": "Host",
     "port": "Port",
     "user": "User",
+    "initialize_mail_settings": "initialize e-mail settings",
+    "initialize_mail_modal_header": "Initialize e-mail settings",
+    "confirm_to_initialize_mail_settings": "You can't restore to the current settings. Are you sure you want to initialize e-mail settings?",
+    "file_upload_settings":"File Upload Settings",
+    "file_upload_method":"File Upload Method",
+    "fixed_by_env_var": "This is fixed by the env var <code>FILE_UPLOAD={{fileUploadType}}</code>.",
+    "gcs_label": "GCP(GCS)",
+    "aws_label": "AWS(S3)",
+    "file_upload": "This is for uploading file settings. If you complete file upload settings, file upload function, profile picture function etc will be enabled.",
     "ses_settings":"SES settings",
     "test_connection": "Test connection to mail",
-    "aws_settings": "AWS settings",
-    "aws_access": "This is for AWS settings. If you complete AWS settings, file upload function, profile picture function etc will be enabled.",
     "change_setting": "Caution:if you change this setting not completed, you will not be able to access files you have uploaded so far.",
     "region": "Region",
     "bucket_name": "Bucket name",
@@ -52,7 +59,8 @@
     "load_plugins": "Load_plugins",
     "enable": "Enable",
     "disable": "Disable",
-    "use_env_var_if_empty": "If the value in the database is empty, the value of the environment variable <cod>{{variable}}</code> is used."
+    "use_env_var_if_empty": "If the value in the database is empty, the value of the environment variable <cod>{{variable}}</code> is used.",
+    "note_for_the_only_env_option": "The GCS Settings is limited by the value of environment variable.<br>To change this setting, please change to false or delete the value of the environment variable <code>{{env}}</code> ."
   },
   "markdown_setting": {
     "lineBreak_header": "Line break setting",

+ 1 - 3
resource/locales/en_US/translation.json

@@ -1,6 +1,5 @@
 {
   "Help": "Help",
-  "view": "View",
   "Edit": "Edit",
   "Delete": "Delete",
   "delete_all": "Delete all",
@@ -440,7 +439,6 @@
     "open_sandbox": "Open Sandbox"
   },
   "hackmd": {
-    "hack_md": "HackMD",
     "not_set_up": "HackMD is not set up.",
     "used_for_not_found": "Can not use HackMD to a page that does not exist.",
     "start_to_edit": "Start to edit with HackMD",
@@ -537,7 +535,7 @@
     "missing mandatory configs": "The following mandatory items are not set in either database nor environment variables.",
     "Local": {
       "name": "ID/Password",
-      "note for the only env option": "The LOCAL authentication is limited by the value of environment variable.<br>To change this setting, please change to false or delete the value of the environment variable <code>{{env}}/code> .",
+      "note for the only env option": "The LOCAL authentication is limited by the value of environment variable.<br>To change this setting, please change to false or delete the value of the environment variable <code>{{env}}</code> .",
       "enable_local": "Enable ID/Password"
     },
     "ldap": {

+ 11 - 3
resource/locales/ja_JP/admin/admin.json

@@ -38,10 +38,17 @@
     "host": "ホスト",
     "port": "ポート",
     "user": "ユーザー",
+    "initialize_mail_settings": "設定を初期化",
+    "initialize_mail_modal_header": "メール設定の初期化",
+    "confirm_to_initialize_mail_settings": "一度初期化した設定は戻せません。本当に初期化しますか?",
+    "file_upload_settings":"ファイルアップロード設定",
+    "file_upload_method":"ファイルアップロード方法",
+    "gcs_label": "GCP(GCS)",
+    "aws_label": "AWS(S3)",
+    "fixed_by_env_var": "環境変数 <code>FILE_UPLOAD={{fileUploadType}}</code> により固定されています。",
+    "file_upload": "ファイルをアップロードするための設定を行います。ファイルアップロードの設定を完了させると、ファイルアップロード機能、プロフィール写真機能などが有効になります。",
     "ses_settings":"SES設定",
     "test_connection": "接続テスト",
-    "aws_settings": "AWS設定",
-    "aws_access": "AWS にアクセスするための設定を行います。AWS の設定を完了させると、ファイルアップロード機能、プロフィール写真機能などが有効になります。",
     "change_setting": "この設定を途中で変更すると、これまでにアップロードしたファイル等へのアクセスができなくなりますのでご注意下さい。",
     "region": "リージョン",
     "bucket_name": "バケット名",
@@ -52,7 +59,8 @@
     "load_plugins": "プラグインを読み込む",
     "enable": "有効",
     "disable": "無効",
-    "use_env_var_if_empty": "データベース側の値が空の場合、環境変数 <code>{{variable}}</code> の値を利用します"
+    "use_env_var_if_empty": "データベース側の値が空の場合、環境変数 <code>{{variable}}</code> の値を利用します",
+    "note_for_the_only_env_option": "現在GCS設定は環境変数の値によって制限されています<br>この設定を変更する場合は環境変数 <code>{{env}}</code> の値をfalseに変更もしくは削除してください"
   },
   "markdown_setting": {
     "lineBreak_header": "Line Break設定",

+ 0 - 2
resource/locales/ja_JP/translation.json

@@ -1,6 +1,5 @@
 {
   "Help": "ヘルプ",
-  "view": "View",
   "Edit": "編集",
   "Delete": "削除",
   "delete_all": "全て削除",
@@ -442,7 +441,6 @@
     "open_sandbox": "Sandbox を開く"
   },
   "hackmd":{
-    "hack_md": "HackMD",
     "not_set_up": "HackMD はセットアップされていません",
     "used_for_not_found": "HackMD は新しいページの作成には利用できません",
     "start_to_edit": "HackMD を開始する",

+ 12 - 4
resource/locales/zh_CN/admin/admin.json

@@ -38,10 +38,17 @@
 		"host": "服务器",
 		"port": "端口号",
 		"user": "用户名",
+    "initialize_mail_settings": "重置邮件设置",
+    "initialize_mail_modal_header": "重置邮件设置",
+    "confirm_to_initialize_mail_settings": "当前设置将被清空且不可恢复。确认重置?",
+    "file_upload_settings":"文件上传设置",
+    "file_upload_method":"文件上传方法",
+    "gcs_label": "GCP(GCS)",
+    "aws_label": "AWS(S3)",
+		"fixed_by_env_var": "这是由env var<code>FILE_UPLOAD={{fileUploadType}}</code>修复的。",
+    "file_upload": "这是文件上传设定。完成了文件上传设定以后,文件上传功能、档案头像功能将会被开启。",
     "ses_settings":"SES设置",
     "test_connection": "测试邮件服务器连接",
-		"aws_settings": "AWS设置",
-		"aws_access": "这是用于AWS设置的。如果您完成了AWS设置,文件上传功能,个人资料图片功能等将被启用。",
 		"": "如果您没有SMTP设置,电子邮件将通过SES发送。您需要从电子邮件地址和生产设置进行验证。",
 		"change_setting": "注意:如果你更改此设置未完成,您将无法访问迄今为止上传的文件。",
 		"region": "Region",
@@ -53,8 +60,9 @@
 		"load_plugins": "加载插件",
 		"enable": "启用",
 		"disable": "停用",
-		"use_env_var_if_empty": "如果数据库中的值为空,则环境变量的值 <cod>{{variable}}</code> 启用。"
-	},
+		"use_env_var_if_empty": "如果数据库中的值为空,则环境变量的值 <cod>{{variable}}</code> 启用。",
+    "note_for_the_only_env_option": "The GCS settings is limited by the value of environment variable.<br>To change this setting, please change to false or delete the value of the environment variable <code>{{env}}</code> ."
+  },
 	"markdown_setting": {
 		"lineBreak_header": "换行设置",
 		"lineBreak_desc": "您可以更改换行设置。",

+ 2 - 4
resource/locales/zh_CN/translation.json

@@ -1,6 +1,5 @@
 {
-  "Help": "帮助",
-  "view": "View",
+	"Help": "帮助",
 	"Edit": "编辑",
 	"Delete": "删除",
 	"delete_all": "删除所有",
@@ -416,7 +415,6 @@
 		"open_sandbox": "开放式沙箱"
 	},
 	"hackmd": {
-    "hack_md": "HackMD",
     "not_set_up": "HackMD is not set up.",
     "used_for_not_found": "Can not use HackMD to a page that does not exist.",
 		"start_to_edit": "Start to edit with HackMD",
@@ -524,7 +522,7 @@
 		"missing mandatory configs": "The following mandatory items are not set in either database nor environment variables.",
 		"Local": {
 			"name": "ID/Password",
-			"note for the only env option": "The LOCAL authentication is limited by the value of environment variable.<br>To change this setting, please change to false or delete the value of the environment variable <code>{{env}}/code> .",
+			"note for the only env option": "The LOCAL authentication is limited by the value of environment variable.<br>To change this setting, please change to false or delete the value of the environment variable <code>{{env}}</code> .",
 			"enable_local": "Enable ID/Password"
 		},
 		"ldap": {

+ 1 - 1
src/client/js/components/Admin/App/AppSetting.jsx

@@ -81,7 +81,7 @@ class AppSetting extends React.Component {
           >
             {t('admin:app_setting.default_language')}
           </label>
-          <div className="col-md-6">
+          <div className="col-md-6 py-2">
             {
               localeMetadatas.map(meta => (
                 <div key={meta.id} className="custom-control custom-radio custom-control-inline">

+ 3 - 3
src/client/js/components/Admin/App/AppSettingsPageContents.jsx

@@ -5,8 +5,8 @@ import PropTypes from 'prop-types';
 import AppSetting from './AppSetting';
 import SiteUrlSetting from './SiteUrlSetting';
 import MailSetting from './MailSetting';
-import AwsSetting from './AwsSetting';
 import PluginSetting from './PluginSetting';
+import FileUploadSetting from './FileUploadSetting';
 
 class AppSettingsPageContents extends React.Component {
 
@@ -38,8 +38,8 @@ class AppSettingsPageContents extends React.Component {
 
         <div className="row mt-5">
           <div className="col-lg-12">
-            <h2 className="admin-setting-header">{t('admin:app_setting.aws_settings')}</h2>
-            <AwsSetting />
+            <h2 className="admin-setting-header">{t('admin:app_setting.file_upload_settings')}</h2>
+            <FileUploadSetting />
           </div>
         </div>
 

+ 76 - 114
src/client/js/components/Admin/App/AwsSetting.jsx

@@ -1,142 +1,104 @@
 import React from 'react';
 import PropTypes from 'prop-types';
 import { withTranslation } from 'react-i18next';
-import loggerFactory from '@alias/logger';
 
 import { withUnstatedContainers } from '../../UnstatedUtils';
-import { toastSuccess, toastError } from '../../../util/apiNotification';
 
 import AppContainer from '../../../services/AppContainer';
 import AdminAppContainer from '../../../services/AdminAppContainer';
-import AdminUpdateButtonRow from '../Common/AdminUpdateButtonRow';
 
-const logger = loggerFactory('growi:appSettings');
-
-class AwsSetting extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.submitHandler = this.submitHandler.bind(this);
-  }
-
-  async submitHandler() {
-    const { t, adminAppContainer } = this.props;
-
-    try {
-      await adminAppContainer.updateAwsSettingHandler();
-      toastSuccess(t('toaster.update_successed', { target: t('admin:app_setting.aws_settings') }));
-    }
-    catch (err) {
-      toastError(err);
-      logger.error(err);
-    }
-  }
-
-  render() {
-    const { t, adminAppContainer } = this.props;
-
-    return (
-      <React.Fragment>
-        <p className="card well">
-          {t('admin:app_setting.aws_access')}
-          <br />
-          <span className="text-danger">
-            <i className="ti-unlink"></i>
-            {t('admin:app_setting.change_setting')}
-          </span>
-        </p>
-
-        <div className="row form-group">
-          <label className="text-left text-md-right col-md-3 col-form-label">
-            {t('admin:app_setting.region')}
-          </label>
-          <div className="col-md-6">
-            <input
-              className="form-control"
-              placeholder={`${t('eg')} ap-northeast-1`}
-              defaultValue={adminAppContainer.state.region || ''}
-              onChange={(e) => {
-                adminAppContainer.changeRegion(e.target.value);
+function AwsSetting(props) {
+  const { t, adminAppContainer } = props;
+
+  return (
+    <React.Fragment>
+      <div className="row form-group">
+        <label className="text-left text-md-right col-md-3 col-form-label">
+          {t('admin:app_setting.region')}
+        </label>
+        <div className="col-md-6">
+          <input
+            className="form-control"
+            placeholder={`${t('eg')} ap-northeast-1`}
+            defaultValue={adminAppContainer.state.s3Region || ''}
+            onChange={(e) => {
+                adminAppContainer.changeS3Region(e.target.value);
               }}
-            />
-          </div>
+          />
         </div>
-
-        <div className="row form-group">
-          <label className="text-left text-md-right col-md-3 col-form-label">
-            {t('admin:app_setting.custom_endpoint')}
-          </label>
-          <div className="col-md-6">
-            <input
-              className="form-control"
-              type="text"
-              placeholder={`${t('eg')} http://localhost:9000`}
-              defaultValue={adminAppContainer.state.customEndpoint || ''}
-              onChange={(e) => {
-                adminAppContainer.changeCustomEndpoint(e.target.value);
+      </div>
+
+      <div className="row form-group">
+        <label className="text-left text-md-right col-md-3 col-form-label">
+          {t('admin:app_setting.custom_endpoint')}
+        </label>
+        <div className="col-md-6">
+          <input
+            className="form-control"
+            type="text"
+            placeholder={`${t('eg')} http://localhost:9000`}
+            defaultValue={adminAppContainer.state.s3CustomEndpoint || ''}
+            onChange={(e) => {
+                adminAppContainer.changeS3CustomEndpoint(e.target.value);
               }}
-            />
-            <p className="form-text text-muted">{t('admin:app_setting.custom_endpoint_change')}</p>
-          </div>
+          />
+          <p className="form-text text-muted">{t('admin:app_setting.custom_endpoint_change')}</p>
         </div>
-
-        <div className="row form-group">
-          <label className="text-left text-md-right col-md-3 col-form-label">
-            {t('admin:app_setting.bucket_name')}
-          </label>
-          <div className="col-md-6">
-            <input
-              className="form-control"
-              type="text"
-              placeholder={`${t('eg')} crowi`}
-              defaultValue={adminAppContainer.state.bucket || ''}
-              onChange={(e) => {
-                adminAppContainer.changeBucket(e.target.value);
+      </div>
+
+      <div className="row form-group">
+        <label className="text-left text-md-right col-md-3 col-form-label">
+          {t('admin:app_setting.bucket_name')}
+        </label>
+        <div className="col-md-6">
+          <input
+            className="form-control"
+            type="text"
+            placeholder={`${t('eg')} crowi`}
+            defaultValue={adminAppContainer.state.s3Bucket || ''}
+            onChange={(e) => {
+                adminAppContainer.changeS3Bucket(e.target.value);
               }}
-            />
-          </div>
+          />
         </div>
+      </div>
 
-        <div className="row form-group">
-          <label className="text-left text-md-right col-md-3 col-form-label">
+      <div className="row form-group">
+        <label className="text-left text-md-right col-md-3 col-form-label">
             Access key ID
-          </label>
-          <div className="col-md-6">
-            <input
-              className="form-control"
-              type="text"
-              defaultValue={adminAppContainer.state.accessKeyId || ''}
-              onChange={(e) => {
-                adminAppContainer.changeAccessKeyId(e.target.value);
+        </label>
+        <div className="col-md-6">
+          <input
+            className="form-control"
+            type="text"
+            defaultValue={adminAppContainer.state.s3AccessKeyId || ''}
+            onChange={(e) => {
+                adminAppContainer.changeS3AccessKeyId(e.target.value);
               }}
-            />
-          </div>
+          />
         </div>
+      </div>
 
-        <div className="row form-group">
-          <label className="text-left text-md-right col-md-3 col-form-label">
+      <div className="row form-group">
+        <label className="text-left text-md-right col-md-3 col-form-label">
             Secret access key
-          </label>
-          <div className="col-md-6">
-            <input
-              className="form-control"
-              type="text"
-              defaultValue={adminAppContainer.state.secretAccessKey || ''}
-              onChange={(e) => {
-                adminAppContainer.changeSecretAccessKey(e.target.value);
+        </label>
+        <div className="col-md-6">
+          <input
+            className="form-control"
+            type="text"
+            defaultValue={adminAppContainer.state.s3SecretAccessKey || ''}
+            onChange={(e) => {
+                adminAppContainer.changeS3SecretAccessKey(e.target.value);
               }}
-            />
-          </div>
+          />
         </div>
-
-        <AdminUpdateButtonRow onClick={this.submitHandler} disabled={adminAppContainer.state.retrieveError != null} />
-      </React.Fragment>
-    );
-  }
-
+      </div>
+    </React.Fragment>
+  );
 }
 
+
 /**
  * Wrapper component for using unstated
  */

+ 101 - 0
src/client/js/components/Admin/App/FileUploadSetting.jsx

@@ -0,0 +1,101 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+
+import { withUnstatedContainers } from '../../UnstatedUtils';
+import { toastSuccess, toastError } from '../../../util/apiNotification';
+
+import AppContainer from '../../../services/AppContainer';
+import AdminAppContainer from '../../../services/AdminAppContainer';
+import AdminUpdateButtonRow from '../Common/AdminUpdateButtonRow';
+
+import AwsSetting from './AwsSetting';
+import GcsSettings from './GcsSettings';
+
+function FileUploadSetting(props) {
+
+  const { t, adminAppContainer } = props;
+  const { fileUploadType } = adminAppContainer.state;
+  const fileUploadTypes = ['aws', 'gcs'];
+
+  async function submitHandler() {
+    const { t } = props;
+
+    try {
+      await adminAppContainer.updateFileUploadSettingHandler();
+      toastSuccess(t('toaster.update_successed', { target: t('admin:app_setting.file_upload_settings') }));
+    }
+    catch (err) {
+      toastError(err);
+    }
+  }
+
+  return (
+    <React.Fragment>
+      <p className="card well my-3">
+        {t('admin:app_setting.file_upload')}
+        <br />
+        <br />
+        <span className="text-danger">
+          <i className="ti-unlink"></i>
+          {t('admin:app_setting.change_setting')}
+        </span>
+      </p>
+
+      <div className="row form-group mb-5">
+        <label className="text-left text-md-right col-md-3 col-form-label">
+          {t('admin:app_setting.file_upload_method')}
+        </label>
+
+        <div className="col-md-6 py-2">
+          {fileUploadTypes.map((type) => {
+              return (
+                <div key={type} className="custom-control custom-radio custom-control-inline">
+                  <input
+                    type="radio"
+                    className="custom-control-input"
+                    name="file-upload-type"
+                    id={`file-upload-type-radio-${type}`}
+                    checked={adminAppContainer.state.fileUploadType === type}
+                    disabled={adminAppContainer.state.isFixedFileUploadByEnvVar}
+                    onChange={(e) => {
+                    adminAppContainer.changeFileUploadType(type);
+                  }}
+                  />
+                  <label className="custom-control-label" htmlFor={`file-upload-type-radio-${type}`}>{t(`admin:app_setting.${type}_label`)}</label>
+                </div>
+              );
+            })}
+        </div>
+        {adminAppContainer.state.isFixedFileUploadByEnvVar && (
+          <p className="alert alert-warning mt-2 text-left offset-3 col-6">
+            <i className="icon-exclamation icon-fw">
+            </i><b>FIXED</b><br />
+            {/* eslint-disable-next-line react/no-danger */}
+            <b dangerouslySetInnerHTML={{ __html: t('admin:app_setting.fixed_by_env_var', { fileUploadType: adminAppContainer.state.envFileUploadType }) }} />
+          </p>
+        )}
+      </div>
+
+      {fileUploadType === 'aws' && <AwsSetting />}
+      {fileUploadType === 'gcs' && <GcsSettings />}
+
+      <AdminUpdateButtonRow onClick={submitHandler} disabled={adminAppContainer.state.retrieveError != null} />
+
+    </React.Fragment>
+  );
+}
+
+
+/**
+ * Wrapper component for using unstated
+ */
+const FileUploadSettingWrapper = withUnstatedContainers(FileUploadSetting, [AppContainer, AdminAppContainer]);
+
+FileUploadSetting.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  adminAppContainer: PropTypes.instanceOf(AdminAppContainer).isRequired,
+};
+
+export default withTranslation()(FileUploadSettingWrapper);

+ 116 - 0
src/client/js/components/Admin/App/GcsSettings.jsx

@@ -0,0 +1,116 @@
+
+import React from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+
+import { withUnstatedContainers } from '../../UnstatedUtils';
+
+import AppContainer from '../../../services/AppContainer';
+import AdminAppContainer from '../../../services/AdminAppContainer';
+
+
+function GcsSetting(props) {
+  const { t, adminAppContainer } = props;
+  const { gcsUseOnlyEnvVars } = adminAppContainer.state;
+
+  return (
+    <>
+      {gcsUseOnlyEnvVars && (
+        <p
+          className="alert alert-info"
+          dangerouslySetInnerHTML={{ __html: t('admin:app_setting.note_for_the_only_env_option', { env: 'IS_GCS_ENV_PRIORITIZED' }) }}
+        />
+      )}
+      <table className={`table settings-table ${gcsUseOnlyEnvVars && 'use-only-env-vars'}`}>
+        <colgroup>
+          <col className="item-name" />
+          <col className="from-db" />
+          <col className="from-env-vars" />
+        </colgroup>
+        <thead>
+          <tr>
+            <th></th>
+            <th>Database</th>
+            <th>Environment variables</th>
+          </tr>
+        </thead>
+        <tbody>
+          <tr>
+            <th>Api Key Json Path</th>
+            <td>
+              <input
+                className="form-control"
+                type="text"
+                name="gcsApiKeyJsonPath"
+                readOnly={gcsUseOnlyEnvVars}
+                defaultValue={adminAppContainer.state.gcsApiKeyJsonPath}
+                onChange={e => adminAppContainer.changeGcsApiKeyJsonPath(e.target.value)}
+              />
+            </td>
+            <td>
+              <input className="form-control" type="text" value={adminAppContainer.state.envGcsApiKeyJsonPath || ''} readOnly tabIndex="-1" />
+              <p className="form-text text-muted">
+                {/* eslint-disable-next-line react/no-danger */}
+                <small dangerouslySetInnerHTML={{ __html: t('admin:app_setting.use_env_var_if_empty', { variable: 'GCS_API_KEY_JSON_PATH' }) }} />
+              </p>
+            </td>
+          </tr>
+          <tr>
+            <th>{t('admin:app_setting.bucket_name')}</th>
+            <td>
+              <input
+                className="form-control"
+                type="text"
+                name="gcsBucket"
+                readOnly={gcsUseOnlyEnvVars}
+                defaultValue={adminAppContainer.state.gcsBucket}
+                onChange={e => adminAppContainer.changeGcsBucket(e.target.value)}
+              />
+            </td>
+            <td>
+              <input className="form-control" type="text" value={adminAppContainer.state.envGcsBucket || ''} readOnly tabIndex="-1" />
+              <p className="form-text text-muted">
+                {/* eslint-disable-next-line react/no-danger */}
+                <small dangerouslySetInnerHTML={{ __html: t('admin:app_setting.use_env_var_if_empty', { variable: 'GCS_BUCKET' }) }} />
+              </p>
+            </td>
+          </tr>
+          <tr>
+            <th>Name Space</th>
+            <td>
+              <input
+                className="form-control"
+                type="text"
+                name="gcsUploadNamespace"
+                readOnly={gcsUseOnlyEnvVars}
+                defaultValue={adminAppContainer.state.gcsUploadNamespace}
+                onChange={e => adminAppContainer.changeGcsUploadNamespace(e.target.value)}
+              />
+            </td>
+            <td>
+              <input className="form-control" type="text" value={adminAppContainer.state.envGcsUploadNamespace || ''} readOnly tabIndex="-1" />
+              <p className="form-text text-muted">
+                {/* eslint-disable-next-line react/no-danger */}
+                <small dangerouslySetInnerHTML={{ __html: t('admin:app_setting.use_env_var_if_empty', { variable: 'GCS_UPLOAD_NAMESPACE' }) }} />
+              </p>
+            </td>
+          </tr>
+        </tbody>
+      </table>
+    </>
+  );
+
+}
+
+/**
+ * Wrapper component for using unstated
+ */
+const GcsSettingWrapper = withUnstatedContainers(GcsSetting, [AppContainer, AdminAppContainer]);
+
+GcsSetting.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  adminAppContainer: PropTypes.instanceOf(AdminAppContainer).isRequired,
+};
+
+export default withTranslation()(GcsSettingWrapper);

+ 3 - 3
src/client/js/components/Admin/App/MailSetting.jsx

@@ -62,7 +62,7 @@ function MailSetting(props) {
         <label className="text-left text-md-right col-md-3 col-form-label">
           {t('admin:app_setting.transmission_method')}
         </label>
-        <div className="col-md-6">
+        <div className="col-md-6 py-2">
           {transmissionMethods.map((method) => {
               return (
                 <div key={method} className="custom-control custom-radio custom-control-inline">
@@ -70,13 +70,13 @@ function MailSetting(props) {
                     type="radio"
                     className="custom-control-input"
                     name="transmission-method"
-                    id={`transmission-nethod-radio-${method}`}
+                    id={`transmission-method-radio-${method}`}
                     checked={adminAppContainer.state.transmissionMethod === method}
                     onChange={(e) => {
                     adminAppContainer.changeTransmissionMethod(method);
                   }}
                   />
-                  <label className="custom-control-label" htmlFor={`transmission-nethod-radio-${method}`}>{t(`admin:app_setting.${method}_label`)}</label>
+                  <label className="custom-control-label" htmlFor={`transmission-method-radio-${method}`}>{t(`admin:app_setting.${method}_label`)}</label>
                 </div>
               );
             })}

+ 2 - 0
src/client/js/components/BookmarkButton.jsx

@@ -38,6 +38,8 @@ class BookmarkButton extends React.Component {
     return (
       <button
         type="button"
+        href="#"
+        title="Bookmark"
         onClick={this.handleClick}
         className={`btn btn-bookmark border-0
           ${`btn-${this.props.size}`}

+ 1 - 1
src/client/js/components/Navbar/GrowiSubNavigation.jsx

@@ -120,7 +120,7 @@ const PageReactionButtons = ({ appContainer, pageContainer }) => {
   return (
     <>
       {pageUser == null && (
-      <span>
+      <span className="mr-2">
         <LikeButton pageId={pageId} isLiked={isLiked} />
       </span>
       )}

+ 119 - 35
src/client/js/services/AdminAppContainer.js

@@ -20,23 +20,39 @@ export default class AdminAppContainer extends Container {
       confidential: '',
       globalLang: '',
       fileUpload: '',
+
       siteUrl: '',
       envSiteUrl: '',
       isSetSiteUrl: true,
       isMailerSetup: false,
       fromAddress: '',
       transmissionMethod: '',
+
       smtpHost: '',
       smtpPort: '',
       smtpUser: '',
       smtpPassword: '',
       sesAccessKeyId: '',
       sesSecretAccessKey: '',
-      region: '',
-      customEndpoint: '',
-      bucket: '',
-      accessKeyId: '',
-      secretAccessKey: '',
+
+      fileUploadType: '',
+      envFileUploadType: '',
+      isFixedFileUploadByEnvVar: false,
+
+      gcsUseOnlyEnvVars: false,
+      gcsApiKeyJsonPath: '',
+      envGcsApiKeyJsonPath: '',
+      gcsBucket: '',
+      envGcsBucket: '',
+      gcsUploadNamespace: '',
+      envGcsUploadNamespace: '',
+
+      s3Region: '',
+      s3CustomEndpoint: '',
+      s3Bucket: '',
+      s3AccessKeyId: '',
+      s3SecretAccessKey: '',
+
       isEnabledPlugins: true,
     };
 
@@ -73,13 +89,39 @@ export default class AdminAppContainer extends Container {
       smtpPassword: appSettingsParams.smtpPassword,
       sesAccessKeyId: appSettingsParams.sesAccessKeyId,
       sesSecretAccessKey: appSettingsParams.sesSecretAccessKey,
-      region: appSettingsParams.region,
-      customEndpoint: appSettingsParams.customEndpoint,
-      bucket: appSettingsParams.bucket,
-      accessKeyId: appSettingsParams.accessKeyId,
-      secretAccessKey: appSettingsParams.secretAccessKey,
+
+      fileUploadType: appSettingsParams.fileUploadType,
+      envFileUploadType: appSettingsParams.envFileUploadType,
+
+      s3Region: appSettingsParams.s3Region,
+      s3CustomEndpoint: appSettingsParams.s3CustomEndpoint,
+      s3Bucket: appSettingsParams.s3Bucket,
+      s3AccessKeyId: appSettingsParams.s3AccessKeyId,
+      s3SecretAccessKey: appSettingsParams.s3SecretAccessKey,
+      gcsUseOnlyEnvVars: appSettingsParams.gcsUseOnlyEnvVars,
+      gcsApiKeyJsonPath: appSettingsParams.gcsApiKeyJsonPath,
+      gcsBucket: appSettingsParams.gcsBucket,
+      gcsUploadNamespace: appSettingsParams.gcsUploadNamespace,
+      envGcsApiKeyJsonPath: appSettingsParams.envGcsApiKeyJsonPath,
+      envGcsBucket: appSettingsParams.envGcsBucket,
+      envGcsUploadNamespace: appSettingsParams.envGcsUploadNamespace,
       isEnabledPlugins: appSettingsParams.isEnabledPlugins,
     });
+
+    // check is file upload type forced
+    if (this.isFixedFileUploadByEnvVar(appSettingsParams.envFileUploadType)) {
+      this.setState({ fileUploadType: appSettingsParams.envFileUploadType });
+      this.setState({ isFixedFileUploadByEnvVar: true });
+    }
+
+  }
+
+  /**
+   * get isFixedFileUploadByEnvVar
+   * @return {bool} isFixedFileUploadByEnvVar
+   */
+  isFixedFileUploadByEnvVar(envFileUploadType) {
+    return envFileUploadType != null;
   }
 
   /**
@@ -161,52 +203,66 @@ export default class AdminAppContainer extends Container {
   }
 
   /**
-   * Change sesAccessKeyId
+   * Change s3Region
+   */
+  changeS3Region(s3Region) {
+    this.setState({ s3Region });
+  }
+
+  /**
+   * Change s3CustomEndpoint
    */
-  changeSesAccessKeyId(sesAccessKeyId) {
-    this.setState({ sesAccessKeyId });
+  changeS3CustomEndpoint(s3CustomEndpoint) {
+    this.setState({ s3CustomEndpoint });
   }
 
   /**
-   * Change sesSecretAccessKey
+   * Change fileUploadType
    */
-  changeSesSecretAccessKey(sesSecretAccessKey) {
-    this.setState({ sesSecretAccessKey });
+  changeFileUploadType(fileUploadType) {
+    this.setState({ fileUploadType });
   }
 
   /**
    * Change region
    */
-  changeRegion(region) {
-    this.setState({ region });
+  changeS3Bucket(s3Bucket) {
+    this.setState({ s3Bucket });
   }
 
   /**
-   * Change custom endpoint
+   * Change access key id
    */
-  changeCustomEndpoint(customEndpoint) {
-    this.setState({ customEndpoint });
+  changeS3AccessKeyId(s3AccessKeyId) {
+    this.setState({ s3AccessKeyId });
   }
 
   /**
-   * Change bucket name
+   * Change secret access key
    */
-  changeBucket(bucket) {
-    this.setState({ bucket });
+  changeS3SecretAccessKey(s3SecretAccessKey) {
+    this.setState({ s3SecretAccessKey });
   }
 
   /**
-   * Change access key id
+   * Change gcsApiKeyJsonPath
    */
-  changeAccessKeyId(accessKeyId) {
-    this.setState({ accessKeyId });
+  changeGcsApiKeyJsonPath(gcsApiKeyJsonPath) {
+    this.setState({ gcsApiKeyJsonPath });
   }
 
   /**
-   * Change secret access key
+   * Change gcsBucket
+   */
+  changeGcsBucket(gcsBucket) {
+    this.setState({ gcsBucket });
+  }
+
+  /**
+   * Change gcsUploadNamespace
    */
-  changeSecretAccessKey(secretAccessKey) {
-    this.setState({ secretAccessKey });
+  changeGcsUploadNamespace(gcsUploadNamespace) {
+    this.setState({ gcsUploadNamespace });
   }
 
   /**
@@ -302,6 +358,17 @@ export default class AdminAppContainer extends Container {
     return this.appContainer.apiv3.post('/app-settings/smtp-test');
   }
 
+  /**
+   * Update file upload setting
+   * @memberOf AdminAppContainer
+   */
+  updateFileUploadSettingHandler() {
+    if (this.state.fileUploadType === 'aws') {
+      return this.updateAwsSettingHandler();
+    }
+    return this.updateGcsSettingHandler();
+  }
+
   /**
    * Update AWS setting
    * @memberOf AdminAppContainer
@@ -309,11 +376,28 @@ export default class AdminAppContainer extends Container {
    */
   async updateAwsSettingHandler() {
     const response = await this.appContainer.apiv3.put('/app-settings/aws-setting', {
-      region: this.state.region,
-      customEndpoint: this.state.customEndpoint,
-      bucket: this.state.bucket,
-      accessKeyId: this.state.accessKeyId,
-      secretAccessKey: this.state.secretAccessKey,
+      fileUploadType: this.state.fileUploadType,
+      s3Region: this.state.s3Region,
+      s3CustomEndpoint: this.state.s3CustomEndpoint,
+      s3Bucket: this.state.s3Bucket,
+      s3AccessKeyId: this.state.s3AccessKeyId,
+      s3SecretAccessKey: this.state.s3SecretAccessKey,
+    });
+    const { awsSettingParams } = response.data;
+    return awsSettingParams;
+  }
+
+  /**
+   * Update GCS setting
+   * @memberOf AdminAppContainer
+   * @return {Array} Appearance
+   */
+  async updateGcsSettingHandler() {
+    const response = await this.appContainer.apiv3.put('/app-settings/gcs-setting', {
+      fileUploadType: this.state.fileUploadType,
+      gcsApiKeyJsonPath: this.state.gcsApiKeyJsonPath,
+      gcsBucket: this.state.gcsBucket,
+      gcsUploadNamespace: this.state.gcsUploadNamespace,
     });
     const { awsSettingParams } = response.data;
     return awsSettingParams;

+ 72 - 0
src/migrations/20200915035234-rename-s3-config.js

@@ -0,0 +1,72 @@
+require('module-alias/register');
+const logger = require('@alias/logger')('growi:migrate:rename-s3-config');
+
+const mongoose = require('mongoose');
+const config = require('@root/config/migrate');
+
+const { getModelSafely } = require('@commons/util/mongoose-utils');
+
+const awsConfigs = [
+  {
+    oldValue: 'aws:bucket',
+    newValue: 'aws:s3Bucket',
+  },
+  {
+    oldValue: 'aws:region',
+    newValue: 'aws:s3Region',
+  },
+  {
+    oldValue: 'aws:accessKeyId',
+    newValue: 'aws:s3AccessKeyId',
+  },
+  {
+    oldValue: 'aws:secretAccessKey',
+    newValue: 'aws:s3SecretAccessKey',
+  },
+  {
+    oldValue: 'aws:customEndpoint',
+    newValue: 'aws:s3CustomEndpoint',
+  },
+];
+
+module.exports = {
+  async up(db, client) {
+    logger.info('Apply migration');
+    mongoose.connect(config.mongoUri, config.mongodb.options);
+
+    const Config = getModelSafely('Config') || require('@server/models/config')();
+
+    const request = awsConfigs.map((awsConfig) => {
+      return {
+        updateOne: {
+          filter: { key: awsConfig.oldValue },
+          update:  { key: awsConfig.newValue },
+        },
+      };
+    });
+
+    await Config.bulkWrite(request);
+
+    logger.info('Migration has successfully applied');
+  },
+
+  async down(db, client) {
+    logger.info('Rollback migration');
+
+    mongoose.connect(config.mongoUri, config.mongodb.options);
+
+    const Config = getModelSafely('Config') || require('@server/models/config')();
+
+    const request = awsConfigs.map((awsConfig) => {
+      return {
+        updateOne: {
+          filter: { key: awsConfig.newValue },
+          update:  { key: awsConfig.oldValue },
+        },
+      };
+    });
+
+    await Config.bulkWrite(request);
+    logger.info('Migration has been successfully rollbacked');
+  },
+};

+ 15 - 2
src/server/crowi/index.js

@@ -105,6 +105,7 @@ Crowi.prototype.init = async function() {
     this.setupSlack(),
     this.setupCsrf(),
     this.setUpFileUpload(),
+    this.setUpFileUploaderSwitchService(),
     this.setupAttachmentService(),
     this.setUpAcl(),
     this.setUpCustomize(),
@@ -546,12 +547,24 @@ Crowi.prototype.setUpApp = async function() {
 /**
  * setup FileUploadService
  */
-Crowi.prototype.setUpFileUpload = async function() {
-  if (this.fileUploadService == null) {
+Crowi.prototype.setUpFileUpload = async function(isForceUpdate = false) {
+  if (this.fileUploadService == null || isForceUpdate) {
     this.fileUploadService = require('../service/file-uploader')(this);
   }
 };
 
+/**
+ * setup FileUploaderSwitchService
+ */
+Crowi.prototype.setUpFileUploaderSwitchService = async function() {
+  const FileUploaderSwitchService = require('../service/file-uploader-switch');
+  this.fileUploaderSwitchService = new FileUploaderSwitchService(this);
+  // add as a message handler
+  if (this.s2sMessagingService != null) {
+    this.s2sMessagingService.addMessageHandler(this.fileUploaderSwitchService);
+  }
+};
+
 /**
  * setup AttachmentService
  */

+ 5 - 5
src/server/models/config.js

@@ -86,11 +86,11 @@ module.exports = function(crowi) {
       'security:passport-basic:isEnabled' : false,
       'security:passport-basic:isSameUsernameTreatedAsIdenticalUser': false,
 
-      'aws:bucket'          : 'growi',
-      'aws:region'          : 'ap-northeast-1',
-      'aws:accessKeyId'     : undefined,
-      'aws:secretAccessKey' : undefined,
-      'aws:customEndpoint'  : undefined,
+      'aws:s3Bucket'          : 'growi',
+      'aws:s3Region'          : 'ap-northeast-1',
+      'aws:s3AccessKeyId'     : undefined,
+      'aws:s3SecretAccessKey' : undefined,
+      'aws:s3CustomEndpoint'  : undefined,
 
       'mail:from'         : undefined,
       'mail:smtpHost'     : undefined,

+ 115 - 24
src/server/routes/apiv3/app-settings.js

@@ -105,6 +105,28 @@ const ErrorV3 = require('../../models/vo/error-apiv3');
  *          secretAccessKey:
  *            type: string
  *            description: secret key for authentification of AWS
+ *      GcsSettingParams:
+ *        description: GcsSettingParams
+ *        type: object
+ *        properties:
+ *          gcsApiKeyJsonPath:
+ *            type: string
+ *            description: apiKeyJsonPath of gcp
+ *          gcsBucket:
+ *            type: string
+ *            description: bucket name of gcs
+ *          gcsUploadNamespace:
+ *            type: string
+ *            description: name space of gcs
+ *          envGcsApiKeyJsonPath:
+ *            type: string
+ *            description: Path of the JSON file that contains service account key to authenticate to GCP API
+ *          envGcsBucket:
+ *            type: string
+ *            description: Name of the GCS bucket
+ *          envGcsUploadNamespace:
+ *            type: string
+ *            description: Directory name to create in the bucket
  *      PluginSettingParams:
  *        description: PluginSettingParams
  *        type: object
@@ -147,11 +169,16 @@ module.exports = (crowi) => {
       body('sesSecretAccessKey').trim(),
     ],
     awsSetting: [
-      body('region').trim().matches(/^[a-z]+-[a-z]+-\d+$/).withMessage((value, { req }) => req.t('validation.aws_region')),
-      body('customEndpoint').trim().matches(/^(https?:\/\/[^/]+|)$/).withMessage((value, { req }) => req.t('validation.aws_custom_endpoint')),
-      body('bucket').trim(),
-      body('accessKeyId').trim().if(value => value !== '').matches(/^[\da-zA-Z]+$/),
-      body('secretAccessKey').trim(),
+      body('s3Region').trim().matches(/^[a-z]+-[a-z]+-\d+$/).withMessage((value, { req }) => req.t('validation.aws_region')),
+      body('s3CustomEndpoint').trim().matches(/^(https?:\/\/[^/]+|)$/).withMessage((value, { req }) => req.t('validation.aws_custom_endpoint')),
+      body('s3Bucket').trim(),
+      body('s3AccessKeyId').trim().if(value => value !== '').matches(/^[\da-zA-Z]+$/),
+      body('s3SecretAccessKey').trim(),
+    ],
+    gcsSetting: [
+      body('gcsApiKeyJsonPath').trim(),
+      body('gcsBucket').trim(),
+      body('gcsUploadNamespace').trim(),
     ],
     pluginSetting: [
       body('isEnabledPlugins').isBoolean(),
@@ -188,6 +215,7 @@ module.exports = (crowi) => {
       envSiteUrl: crowi.configManager.getConfigFromEnvVars('crowi', 'app:siteUrl'),
       isMailerSetup: crowi.mailService.isMailerSetup,
       fromAddress: crowi.configManager.getConfig('crowi', 'mail:from'),
+
       transmissionMethod: crowi.configManager.getConfig('crowi', 'mail:transmissionMethod'),
       smtpHost: crowi.configManager.getConfig('crowi', 'mail:smtpHost'),
       smtpPort: crowi.configManager.getConfig('crowi', 'mail:smtpPort'),
@@ -195,11 +223,23 @@ module.exports = (crowi) => {
       smtpPassword: crowi.configManager.getConfig('crowi', 'mail:smtpPassword'),
       sesAccessKeyId: crowi.configManager.getConfig('crowi', 'mail:sesAccessKeyId'),
       sesSecretAccessKey: crowi.configManager.getConfig('crowi', 'mail:sesSecretAccessKey'),
-      region: crowi.configManager.getConfig('crowi', 'aws:region'),
-      customEndpoint: crowi.configManager.getConfig('crowi', 'aws:customEndpoint'),
-      bucket: crowi.configManager.getConfig('crowi', 'aws:bucket'),
-      accessKeyId: crowi.configManager.getConfig('crowi', 'aws:accessKeyId'),
-      secretAccessKey: crowi.configManager.getConfig('crowi', 'aws:secretAccessKey'),
+
+      fileUploadType: crowi.configManager.getConfig('crowi', 'app:fileUploadType'),
+      envFileUploadType: crowi.configManager.getConfigFromEnvVars('crowi', 'app:fileUploadType'),
+
+      s3Region: crowi.configManager.getConfig('crowi', 'aws:s3Region'),
+      s3CustomEndpoint: crowi.configManager.getConfig('crowi', 'aws:s3CustomEndpoint'),
+      s3Bucket: crowi.configManager.getConfig('crowi', 'aws:s3Bucket'),
+      s3AccessKeyId: crowi.configManager.getConfig('crowi', 'aws:s3AccessKeyId'),
+      s3SecretAccessKey: crowi.configManager.getConfig('crowi', 'aws:s3SecretAccessKey'),
+      gcsUseOnlyEnvVars: crowi.configManager.getConfig('crowi', 'gcs:isGcsEnvPrioritizes'),
+      gcsApiKeyJsonPath: crowi.configManager.getConfig('crowi', 'gcs:apiKeyJsonPath'),
+      gcsBucket: crowi.configManager.getConfig('crowi', 'gcs:bucket'),
+      gcsUploadNamespace: crowi.configManager.getConfig('crowi', 'gcs:uploadNamespace'),
+      envGcsApiKeyJsonPath: crowi.configManager.getConfigFromEnvVars('crowi', 'gcs:apiKeyJsonPath'),
+      envGcsBucket: crowi.configManager.getConfigFromEnvVars('crowi', 'gcs:bucket'),
+      envGcsUploadNamespace: crowi.configManager.getConfigFromEnvVars('crowi', 'gcs:uploadNamespace'),
+
       isEnabledPlugins: crowi.configManager.getConfig('crowi', 'plugin:isEnabledPlugins'),
     };
     return res.apiv3({ appSettingsParams });
@@ -532,25 +572,25 @@ module.exports = (crowi) => {
    */
   router.put('/aws-setting', loginRequiredStrictly, adminRequired, csrf, validator.awsSetting, apiV3FormValidator, async(req, res) => {
     const requestAwsSettingParams = {
-      'aws:region': req.body.region,
-      'aws:customEndpoint': req.body.customEndpoint,
-      'aws:bucket': req.body.bucket,
-      'aws:accessKeyId': req.body.accessKeyId,
-      'aws:secretAccessKey': req.body.secretAccessKey,
+      'app:fileUploadType': req.body.fileUploadType,
+      'aws:s3Region': req.body.s3Region,
+      'aws:s3CustomEndpoint': req.body.s3CustomEndpoint,
+      'aws:s3Bucket': req.body.s3Bucket,
+      'aws:s3AccessKeyId': req.body.s3AccessKeyId,
+      'aws:s3SecretAccessKey': req.body.s3SecretAccessKey,
     };
 
     try {
-      const { configManager } = crowi;
-
-      // update config without publishing S2sMessage
-      await configManager.updateConfigsInTheSameNamespace('crowi', requestAwsSettingParams, true);
+      await crowi.configManager.updateConfigsInTheSameNamespace('crowi', requestAwsSettingParams, true);
+      await crowi.setUpFileUpload(true);
+      crowi.fileUploaderSwitchService.publishUpdatedMessage();
 
       const awsSettingParams = {
-        region: crowi.configManager.getConfig('crowi', 'aws:region'),
-        customEndpoint: crowi.configManager.getConfig('crowi', 'aws:customEndpoint'),
-        bucket: crowi.configManager.getConfig('crowi', 'aws:bucket'),
-        accessKeyId: crowi.configManager.getConfig('crowi', 'aws:accessKeyId'),
-        secretAccessKey: crowi.configManager.getConfig('crowi', 'aws:secretAccessKey'),
+        s3Region: crowi.configManager.getConfig('crowi', 'aws:s3Region'),
+        s3CustomEndpoint: crowi.configManager.getConfig('crowi', 'aws:s3CustomEndpoint'),
+        s3Bucket: crowi.configManager.getConfig('crowi', 'aws:s3Bucket'),
+        s3AccessKeyId: crowi.configManager.getConfig('crowi', 'aws:s3AccessKeyId'),
+        s3SecretAccessKey: crowi.configManager.getConfig('crowi', 'aws:s3SecretAccessKey'),
       };
       return res.apiv3({ awsSettingParams });
     }
@@ -562,6 +602,57 @@ module.exports = (crowi) => {
 
   });
 
+  /**
+   * @swagger
+   *
+   *    /app-settings/gcs-setting:
+   *      put:
+   *        tags: [AppSettings]
+   *        operationId: updateAppSettingGcsSetting
+   *        summary: /app-settings/gcs-setting
+   *        description: Update gcs setting
+   *        requestBody:
+   *          required: true
+   *          content:
+   *            application/json:
+   *              schema:
+   *                $ref: '#/components/schemas/GcsSettingParams'
+   *        responses:
+   *          200:
+   *            description: Succeeded to update gcs setting
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  $ref: '#/components/schemas/GcsSettingParams'
+   */
+  router.put('/gcs-setting', loginRequiredStrictly, adminRequired, csrf, validator.gcsSetting, apiV3FormValidator, async(req, res) => {
+    const requestGcsSettingParams = {
+      'app:fileUploadType': req.body.fileUploadType,
+      'gcs:apiKeyJsonPath': req.body.gcsApiKeyJsonPath,
+      'gcs:bucket': req.body.gcsBucket,
+      'gcs:uploadNamespace': req.body.gcsUploadNamespace,
+    };
+
+    try {
+      await crowi.configManager.updateConfigsInTheSameNamespace('crowi', requestGcsSettingParams, true);
+      await crowi.setUpFileUpload(true);
+      crowi.fileUploaderSwitchService.publishUpdatedMessage();
+
+      const gcsSettingParams = {
+        gcsApiKeyJsonPath: crowi.configManager.getConfig('crowi', 'gcs:apiKeyJsonPath'),
+        gcsBucket: crowi.configManager.getConfig('crowi', 'gcs:bucket'),
+        gcsUploadNamespace: crowi.configManager.getConfig('crowi', 'gcs:uploadNamespace'),
+      };
+      return res.apiv3({ gcsSettingParams });
+    }
+    catch (err) {
+      const msg = 'Error occurred in updating aws setting';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'update-awsSetting-failed'));
+    }
+
+  });
+
   /**
    * @swagger
    *

+ 3 - 4
src/server/routes/apiv3/bookmarks.js

@@ -54,8 +54,7 @@ const router = express.Router();
 
 module.exports = (crowi) => {
   const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
-  const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
-  const loginRequired = require('../../middlewares/login-required')(crowi, true);
+  const loginRequired = require('../../middlewares/login-required')(crowi);
   const csrf = require('../../middlewares/csrf')(crowi);
   const apiV3FormValidator = require('../../middlewares/apiv3-form-validator')(crowi);
 
@@ -63,7 +62,7 @@ module.exports = (crowi) => {
 
   const validator = {
     bookmarks: [
-      body('pageId').isMongoId(),
+      body('pageId').isString(),
       body('bool').isBoolean(),
     ],
     bookmarkInfo: [
@@ -214,7 +213,7 @@ module.exports = (crowi) => {
    *                schema:
    *                  $ref: '#/components/schemas/Bookmark'
    */
-  router.put('/', accessTokenParser, loginRequiredStrictly, csrf, validator.bookmarks, apiV3FormValidator, async(req, res) => {
+  router.put('/', accessTokenParser, loginRequired, csrf, validator.bookmarks, apiV3FormValidator, async(req, res) => {
     const { pageId, bool } = req.body;
 
     let bookmark;

+ 12 - 6
src/server/service/config-loader.js

@@ -23,12 +23,12 @@ const TYPES = {
  *  So, parameters of these are under consideration.
  */
 const ENV_VAR_NAME_TO_CONFIG_INFO = {
-  // FILE_UPLOAD: {
-  //   ns:      ,
-  //   key:     ,
-  //   type:    ,
-  //   default:
-  // },
+  FILE_UPLOAD: {
+    ns:      'crowi',
+    key:     'app:fileUploadType',
+    type:    TYPES.STRING,
+    default: 'aws',
+  },
   // HACKMD_URI: {
   //   ns:      ,
   //   key:     ,
@@ -344,6 +344,12 @@ const ENV_VAR_NAME_TO_CONFIG_INFO = {
     type:    TYPES.STRING,
     default: null,
   },
+  IS_GCS_ENV_PRIORITIZED: {
+    ns:      'crowi',
+    key:     'gcs:isGcsEnvPrioritizes',
+    type:    TYPES.BOOLEAN,
+    default: false,
+  },
 };
 
 class ConfigLoader {

+ 18 - 0
src/server/service/config-manager.js

@@ -24,6 +24,16 @@ const KEYS_FOR_SAML_USE_ONLY_ENV_OPTION = [
   'security:passport-saml:ABLCRule',
 ];
 
+const KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION = [
+  'app:fileUploadType',
+];
+
+const KEYS_FOR_GCS_USE_ONLY_ENV_OPTION = [
+  'gcs:apiKeyJsonPath',
+  'gcs:bucket',
+  'gcs:uploadNamespace',
+];
+
 class ConfigManager extends S2sMessageHandlable {
 
   constructor(configModel) {
@@ -218,6 +228,14 @@ class ConfigManager extends S2sMessageHandlable {
         KEYS_FOR_SAML_USE_ONLY_ENV_OPTION.includes(key)
         && this.defaultSearch('crowi', 'security:passport-saml:useOnlyEnvVarsForSomeOptions')
       )
+      // file upload option
+      // [TODO GW-4173] control with the env var gcs:isFileUploadEnvPrioritizes
+      || KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION.includes(key)
+      // gcs option
+      || (
+        KEYS_FOR_GCS_USE_ONLY_ENV_OPTION.includes(key)
+        && this.searchOnlyFromEnvVarConfigs('crowi', 'gcs:isGcsEnvPrioritizes')
+      )
     ));
   }
 

+ 60 - 0
src/server/service/file-uploader-switch.js

@@ -0,0 +1,60 @@
+const logger = require('@alias/logger')('growi:service:FileUploader');
+
+const S2sMessage = require('../models/vo/s2s-message');
+const S2sMessageHandlable = require('./s2s-messaging/handlable');
+
+class fileUploaderSwitch extends S2sMessageHandlable {
+
+  constructor(crowi) {
+    super();
+
+    this.crowi = crowi;
+    this.configManager = crowi.configManager;
+    this.s2sMessagingService = crowi.s2sMessagingService;
+    this.appService = crowi.appService;
+    this.xssService = crowi.xssService;
+
+    this.lastLoadedAt = null;
+  }
+
+  /**
+   * @inheritdoc
+   */
+  shouldHandleS2sMessage(s2sMessage) {
+    const { eventName, updatedAt } = s2sMessage;
+    if (eventName !== 'fileUploadServiceUpdated' || updatedAt == null) {
+      return false;
+    }
+
+    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
+  }
+
+  /**
+   * @inheritdoc
+   */
+  async handleS2sMessage(s2sMessage) {
+    const { configManager } = this;
+
+    logger.info('Reset fileupload service by pubsub notification');
+    await configManager.loadConfigs();
+    await this.crowi.setUpFileUpload(true);
+  }
+
+  async publishUpdatedMessage() {
+    const { s2sMessagingService } = this;
+
+    if (s2sMessagingService != null) {
+      const s2sMessage = new S2sMessage('fileUploadServiceUpdated', { updatedAt: new Date() });
+
+      try {
+        await s2sMessagingService.publish(s2sMessage);
+      }
+      catch (e) {
+        logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
+      }
+    }
+  }
+
+}
+
+module.exports = fileUploaderSwitch;

+ 10 - 10
src/server/service/file-uploader/aws.js

@@ -10,11 +10,11 @@ module.exports = function(crowi) {
 
   function getAwsConfig() {
     return {
-      accessKeyId: configManager.getConfig('crowi', 'aws:accessKeyId'),
-      secretAccessKey: configManager.getConfig('crowi', 'aws:secretAccessKey'),
-      region: configManager.getConfig('crowi', 'aws:region'),
-      bucket: configManager.getConfig('crowi', 'aws:bucket'),
-      customEndpoint: configManager.getConfig('crowi', 'aws:customEndpoint'),
+      accessKeyId: configManager.getConfig('crowi', 'aws:s3AccessKeyId'),
+      secretAccessKey: configManager.getConfig('crowi', 'aws:s3SecretAccessKey'),
+      region: configManager.getConfig('crowi', 'aws:s3Region'),
+      bucket: configManager.getConfig('crowi', 'aws:s3Bucket'),
+      customEndpoint: configManager.getConfig('crowi', 'aws:s3CustomEndpoint'),
     };
   }
 
@@ -67,13 +67,13 @@ module.exports = function(crowi) {
   }
 
   lib.isValidUploadSettings = function() {
-    return this.configManager.getConfig('crowi', 'aws:accessKeyId') != null
-      && this.configManager.getConfig('crowi', 'aws:secretAccessKey') != null
+    return this.configManager.getConfig('crowi', 'aws:s3AccessKeyId') != null
+      && this.configManager.getConfig('crowi', 'aws:s3SecretAccessKey') != null
       && (
-        this.configManager.getConfig('crowi', 'aws:region') != null
-          || this.configManager.getConfig('crowi', 'aws:customEndpoint') != null
+        this.configManager.getConfig('crowi', 'aws:s3Region') != null
+          || this.configManager.getConfig('crowi', 'aws:s3CustomEndpoint') != null
       )
-      && this.configManager.getConfig('crowi', 'aws:bucket') != null;
+      && this.configManager.getConfig('crowi', 'aws:s3Bucket') != null;
   };
 
 

+ 13 - 7
src/server/service/file-uploader/index.js

@@ -1,3 +1,5 @@
+const logger = require('@alias/logger')('growi:service:FileUploaderServise');
+
 const envToModuleMappings = {
   aws:     'aws',
   local:   'local',
@@ -9,22 +11,26 @@ const envToModuleMappings = {
   gcs:     'gcs',
 };
 
-class FileUploaderFactory {
+class FileUploadServiceFactory {
+
+  initializeUploader(crowi) {
+    const method = envToModuleMappings[crowi.configManager.getConfig('crowi', 'app:fileUploadType')];
+    const modulePath = `./${method}`;
+    this.uploader = require(modulePath)(crowi);
 
-  getUploader(crowi) {
     if (this.uploader == null) {
-      const method = envToModuleMappings[process.env.FILE_UPLOAD] || 'aws';
-      const modulePath = `./${method}`;
-      this.uploader = require(modulePath)(crowi);
+      logger.warn('Failed to initialize uploader.');
     }
+  }
 
+  getUploader(crowi) {
+    this.initializeUploader(crowi);
     return this.uploader;
   }
 
 }
 
-const factory = new FileUploaderFactory();
-
 module.exports = (crowi) => {
+  const factory = new FileUploadServiceFactory(crowi);
   return factory.getUploader(crowi);
 };

+ 4 - 4
src/server/util/middlewares.js

@@ -155,10 +155,10 @@ module.exports = (crowi) => {
 
   middlewares.awsEnabled = function() {
     return function(req, res, next) {
-      if ((configManager.getConfig('crowi', 'aws:region') !== '' || this.configManager.getConfig('crowi', 'aws:customEndpoint') !== '')
-          && configManager.getConfig('crowi', 'aws:bucket') !== ''
-          && configManager.getConfig('crowi', 'aws:accessKeyId') !== ''
-          && configManager.getConfig('crowi', 'aws:secretAccessKey') !== '') {
+      if ((configManager.getConfig('crowi', 'aws:s3Region') !== '' || this.configManager.getConfig('crowi', 'aws:s3CustomEndpoint') !== '')
+          && configManager.getConfig('crowi', 'aws:s3Bucket') !== ''
+          && configManager.getConfig('crowi', 'aws:s3AccessKeyId') !== ''
+          && configManager.getConfig('crowi', 'aws:s3SecretAccessKey') !== '') {
         req.flash('globalError', req.t('message.aws_sttings_required'));
         return res.redirect('/');
       }