jam411 il y a 3 ans
Parent
commit
b3569035ca
27 fichiers modifiés avec 677 ajouts et 575 suppressions
  1. 12 12
      packages/app/package.json
  2. 25 10
      packages/app/public/static/locales/en_US/translation.json
  3. 19 4
      packages/app/public/static/locales/ja_JP/translation.json
  4. 19 4
      packages/app/public/static/locales/zh_CN/translation.json
  5. 25 25
      packages/app/src/components/Fab.tsx
  6. 0 217
      packages/app/src/components/InstallerForm.jsx
  7. 231 0
      packages/app/src/components/InstallerForm.tsx
  8. 101 55
      packages/app/src/components/LoginForm.tsx
  9. 4 3
      packages/app/src/components/Navbar/GrowiContextualSubNavigation.tsx
  10. 15 1
      packages/app/src/components/Navbar/GrowiSubNavigation.module.scss
  11. 1 2
      packages/app/src/components/PagePathNav.tsx
  12. 1 1
      packages/app/src/pages/utils/commons.ts
  13. 9 7
      packages/app/src/server/middlewares/login-form-validator.ts
  14. 8 8
      packages/app/src/server/middlewares/register-form-validator.ts
  15. 11 1
      packages/app/src/server/routes/apiv3/index.js
  16. 76 0
      packages/app/src/server/routes/apiv3/installer.ts
  17. 1 4
      packages/app/src/server/routes/index.js
  18. 0 70
      packages/app/src/server/routes/installer.js
  19. 113 90
      packages/app/src/server/routes/login-passport.js
  20. 1 9
      packages/app/src/server/routes/login.js
  21. 1 1
      packages/app/src/server/service/installer.ts
  22. 0 9
      packages/app/src/styles/_on-edit.scss
  23. 0 20
      packages/app/src/styles/atoms/_buttons.scss
  24. 2 0
      packages/app/src/styles/atoms/_custom_control.scss
  25. 0 13
      packages/app/src/styles/atoms/_nav.scss
  26. 0 4
      packages/app/src/styles/atoms/_pre.scss
  27. 2 5
      packages/app/src/styles/style-next.scss

+ 12 - 12
packages/app/package.json

@@ -150,6 +150,7 @@
     "prom-client": "^13.0.0",
     "prom-client": "^13.0.0",
     "rate-limiter-flexible": "^2.3.7",
     "rate-limiter-flexible": "^2.3.7",
     "react": "^18.2.0",
     "react": "^18.2.0",
+    "react-bootstrap-typeahead": "^5.2.2",
     "react-card-flip": "^1.0.10",
     "react-card-flip": "^1.0.10",
     "react-datepicker": "^4.7.0",
     "react-datepicker": "^4.7.0",
     "react-dnd": "^14.0.5",
     "react-dnd": "^14.0.5",
@@ -159,6 +160,9 @@
     "react-markdown": "^8.0.3",
     "react-markdown": "^8.0.3",
     "react-multiline-clamp": "^2.0.0",
     "react-multiline-clamp": "^2.0.0",
     "react-syntax-highlighter": "^15.5.0",
     "react-syntax-highlighter": "^15.5.0",
+    "react-use-ripple": "^1.5.2",
+    "react-scroll": "^1.8.7",
+    "reactstrap": "^8.9.0",
     "reconnecting-websocket": "^4.4.0",
     "reconnecting-websocket": "^4.4.0",
     "redis": "^3.0.2",
     "redis": "^3.0.2",
     "rehype-katex": "^6.0.2",
     "rehype-katex": "^6.0.2",
@@ -172,12 +176,17 @@
     "remark-math": "^5.1.1",
     "remark-math": "^5.1.1",
     "remark-wiki-link": "^1.0.4",
     "remark-wiki-link": "^1.0.4",
     "rimraf": "^3.0.0",
     "rimraf": "^3.0.0",
+    "simplebar-react": "^2.3.6",
     "socket.io": "^4.2.0",
     "socket.io": "^4.2.0",
+    "sticky-events": "^3.4.11",
     "stream-to-promise": "^3.0.0",
     "stream-to-promise": "^3.0.0",
     "string-width": "=4.2.2",
     "string-width": "=4.2.2",
     "superjson": "^1.9.1",
     "superjson": "^1.9.1",
     "swagger-jsdoc": "^6.1.0",
     "swagger-jsdoc": "^6.1.0",
     "swig-templates": "^2.0.2",
     "swig-templates": "^2.0.2",
+    "swr": "^1.3.0",
+    "throttle-debounce": "^3.0.1",
+    "toastr": "^2.1.2",
     "uglifycss": "^0.0.29",
     "uglifycss": "^0.0.29",
     "universal-bunyan": "^0.9.2",
     "universal-bunyan": "^0.9.2",
     "unzipper": "^0.10.5",
     "unzipper": "^0.10.5",
@@ -185,7 +194,8 @@
     "usehooks-ts": "^2.6.0",
     "usehooks-ts": "^2.6.0",
     "validator": "^13.7.0",
     "validator": "^13.7.0",
     "ws": "^8.3.0",
     "ws": "^8.3.0",
-    "xss": "^1.0.6"
+    "xss": "^1.0.6",
+    "unstated": "^2.1.1"
   },
   },
   "// comments for defDependencies": {
   "// comments for defDependencies": {
     "@handsontable/react": "v3 requires handsontable >= 7.0.0.",
     "@handsontable/react": "v3 requires handsontable >= 7.0.0.",
@@ -231,31 +241,21 @@
     "penpal": "^4.0.0",
     "penpal": "^4.0.0",
     "plantuml-encoder": "^1.2.5",
     "plantuml-encoder": "^1.2.5",
     "prettier": "^1.19.1",
     "prettier": "^1.19.1",
-    "react-bootstrap-typeahead": "^5.2.2",
     "react-codemirror2": "^6.0.0",
     "react-codemirror2": "^6.0.0",
     "react-copy-to-clipboard": "^5.0.1",
     "react-copy-to-clipboard": "^5.0.1",
     "react-dropzone": "^11.2.4",
     "react-dropzone": "^11.2.4",
     "react-frame-component": "^4.0.0",
     "react-frame-component": "^4.0.0",
     "react-hotkeys": "^2.0.0",
     "react-hotkeys": "^2.0.0",
-    "react-scroll": "^1.8.7",
-    "react-use-ripple": "^1.5.2",
     "react-waypoint": "^10.1.0",
     "react-waypoint": "^10.1.0",
-    "reactstrap": "^8.9.0",
     "rehype-rewrite": "^3.0.6",
     "rehype-rewrite": "^3.0.6",
     "replacestream": "^4.0.3",
     "replacestream": "^4.0.3",
     "reveal.js": "^4.3.1",
     "reveal.js": "^4.3.1",
     "sass": "^1.53.0",
     "sass": "^1.53.0",
     "simple-line-icons": "^2.5.5",
     "simple-line-icons": "^2.5.5",
     "simple-load-script": "^1.0.2",
     "simple-load-script": "^1.0.2",
-    "simplebar-react": "^2.3.6",
     "socket.io-client": "^4.2.0",
     "socket.io-client": "^4.2.0",
-    "sticky-events": "^3.4.11",
     "swagger2openapi": "^5.3.1",
     "swagger2openapi": "^5.3.1",
-    "swr": "^1.3.0",
-    "throttle-debounce": "^3.0.1",
-    "toastr": "^2.1.2",
     "ts-node-dev": "^2.0.0",
     "ts-node-dev": "^2.0.0",
-    "tsc-alias": "^1.2.9",
-    "unstated": "^2.1.1"
+    "tsc-alias": "^1.2.9"
   }
   }
 }
 }

+ 25 - 10
packages/app/public/static/locales/en_US/translation.json

@@ -191,7 +191,9 @@
     "setup": "Setup",
     "setup": "Setup",
     "create_initial_account": "Create an initial account",
     "create_initial_account": "Create an initial account",
     "initial_account_will_be_administrator_automatically": "The initial account will be administrator automatically.",
     "initial_account_will_be_administrator_automatically": "The initial account will be administrator automatically.",
-    "unavaliable_user_id": "This 'User ID' is unavailable."
+    "unavaliable_user_id": "This 'User ID' is unavailable.",
+    "failed_to_install": "Failed to install GROWI. Please try again.",
+    "failed_to_login_after_install": "Failed to login after installation. Redirecting to the login form ..."
   },
   },
   "breaking_changes": {
   "breaking_changes": {
     "v346_using_basic_auth": "Basic Authentication currently in use will <strong>no longer be available</strong> in the near future. Remove settings from %s"
     "v346_using_basic_auth": "Basic Authentication currently in use will <strong>no longer be available</strong> in the near future. Remove settings from %s"
@@ -689,9 +691,19 @@
     "fail_to_save_access_token": "Failed to save access_token. Please try again.",
     "fail_to_save_access_token": "Failed to save access_token. Please try again.",
     "fail_to_fetch_access_token": "Failed to fetch access_token. Please do connect again.",
     "fail_to_fetch_access_token": "Failed to fetch access_token. Please do connect again.",
     "successfully_disconnected": "Successfully Disconnected!",
     "successfully_disconnected": "Successfully Disconnected!",
-    "strategy_has_not_been_set_up": "{{strategy}} has not been set up",
+    "strategy_has_not_been_set_up": {
+      "LocalStrategy"  : "LocalStrategy has not been set up",
+      "LdapStrategy"   : "LdapStrategy has not been set up",
+      "GoogleStrategy" : "GoogleStrategy has not been set up",
+      "GitHubStrategy" : "GitHubStrategy has not been set up",
+      "TwitterStrategy": "TwitterStrategy has not been set up",
+      "OidcStrategy"   : "OidcStrategy has not been set up",
+      "SamlStrategy"   : "SamlStrategy has not been set up",
+      "Basic"          : "Basic has not been set up"
+    },
+    "ldap_user_not_valid": "Ldap user is no valid",
+    "external_account_not_exist": "Failed to find or create External account",
     "maximum_number_of_users": "Can not register more than the maximum number of users.",
     "maximum_number_of_users": "Can not register more than the maximum number of users.",
-    "database_error": "Database Server Error occured",
     "sign_in_failure": "Sign in failure.",
     "sign_in_failure": "Sign in failure.",
     "aws_sttings_required": "AWS settings required to use this function. Please ask the administrator.",
     "aws_sttings_required": "AWS settings required to use this function. Please ask the administrator.",
     "application_already_installed": "Application already installed.",
     "application_already_installed": "Application already installed.",
@@ -713,13 +725,16 @@
     "user_already_loggedin": "You cannot create a new account when you are logged in.",
     "user_already_loggedin": "You cannot create a new account when you are logged in.",
     "registration_closed": "You are not authorized to create a new account.",
     "registration_closed": "You are not authorized to create a new account.",
     "Username has invalid characters": "Username has invalid characters.",
     "Username has invalid characters": "Username has invalid characters.",
-    "Username field is required": "User ID field is required",
-    "Name field is required": "Name field is required",
-    "Email format is invalid": "Email format is invalid",
-    "Email field is required": "Email field is required",
-    "Password has invalid character": "Password has invalid character",
-    "Password minimum character should be more than 8 characters": "Password minimum character should be more than 8 characters",
-    "Password field is required": "Password field is required"
+    "Username field is required": "User ID field is required.",
+    "Name field is required": "Name field is required.",
+    "Email format is invalid": "Email format is invalid.",
+    "Email field is required": "Email field is required.",
+    "Password has invalid character": "Password has invalid character.",
+    "Password minimum character should be more than 8 characters": "Password minimum character should be more than 8 characters.",
+    "Password field is required": "Password field is required.",
+    "Username or E-mail has invalid characters": "Username or E-mail has invalid characters.",
+    "Password minimum character should be more than 6 characters": "Password minimum character should be more than 6 characters.",
+    "user_not_found": "User not found."
   },
   },
   "grid_edit":{
   "grid_edit":{
     "create_bootstrap_4_grid":"Create Bootstrap 4 Grid",
     "create_bootstrap_4_grid":"Create Bootstrap 4 Grid",

+ 19 - 4
packages/app/public/static/locales/ja_JP/translation.json

@@ -184,7 +184,9 @@
     "setup": "セットアップ",
     "setup": "セットアップ",
     "create_initial_account": "最初のアカウントの作成",
     "create_initial_account": "最初のアカウントの作成",
     "initial_account_will_be_administrator_automatically": "初めに作成するアカウントは、自動的に管理者権限が付与されます",
     "initial_account_will_be_administrator_automatically": "初めに作成するアカウントは、自動的に管理者権限が付与されます",
-    "unavaliable_user_id": "このユーザーIDは利用できません。"
+    "unavaliable_user_id": "このユーザーIDは利用できません。",
+    "failed_to_install": "GROWI のインストールに失敗しました。再度お試しください。",
+    "failed_to_login_after_install": "インストール後、ログインに失敗しました。ログインフォームに遷移しています ..."
   },
   },
   "breaking_changes": {
   "breaking_changes": {
     "v346_using_basic_auth": "現在利用中の Basic 認証機能は、近い将来<strong>廃止されます</strong>。%s から設定を削除してください。"
     "v346_using_basic_auth": "現在利用中の Basic 認証機能は、近い将来<strong>廃止されます</strong>。%s から設定を削除してください。"
@@ -680,9 +682,19 @@
     "fail_to_save_access_token": "アクセストークンの保存に失敗しました、再度お試しください。",
     "fail_to_save_access_token": "アクセストークンの保存に失敗しました、再度お試しください。",
     "fail_to_fetch_access_token": "アクセストークンの取得に失敗しました、再度お試しください。",
     "fail_to_fetch_access_token": "アクセストークンの取得に失敗しました、再度お試しください。",
     "successfully_disconnected": "切断に成功しました!",
     "successfully_disconnected": "切断に成功しました!",
-    "strategy_has_not_been_set_up": "{{strategy}} はセットアップされていません。",
+    "strategy_has_not_been_set_up": {
+      "LocalStrategy"  : "LocalStrategy はセットアップされていません。",
+      "LdapStrategy"   : "LdapStrategy はセットアップされていません。",
+      "GoogleStrategy" : "GoogleStrategy はセットアップされていません。",
+      "GitHubStrategy" : "GitHubStrategy はセットアップされていません。",
+      "TwitterStrategy": "TwitterStrategy はセットアップされていません。",
+      "OidcStrategy"   : "OidcStrategy はセットアップされていません。",
+      "SamlStrategy"   : "SamlStrategy はセットアップされていません。",
+      "Basic"          : "Basic はセットアップされていません。"
+    },
+    "ldap_user_not_valid": "Ldap user is no valid",
+    "external_account_not_exist": "外部アカウントが見つからない、または作成に失敗しました",
     "maximum_number_of_users": "ユーザー数が上限を超えたためアクティベートできません。",
     "maximum_number_of_users": "ユーザー数が上限を超えたためアクティベートできません。",
-    "database_error":"データベースサーバーに問題があります。",
     "sign_in_failure": "ログインに失敗しました。",
     "sign_in_failure": "ログインに失敗しました。",
     "aws_sttings_required": "この機能にはAWS設定が必要です。管理者に訪ねて下さい。",
     "aws_sttings_required": "この機能にはAWS設定が必要です。管理者に訪ねて下さい。",
     "application_already_installed": "アプリケーションのインストールが完了しました。",
     "application_already_installed": "アプリケーションのインストールが完了しました。",
@@ -710,7 +722,10 @@
     "Email field is required": "メールアドレスは必須項目です",
     "Email field is required": "メールアドレスは必須項目です",
     "Password has invalid character": "パスワードに無効な文字があります",
     "Password has invalid character": "パスワードに無効な文字があります",
     "Password minimum character should be more than 8 characters": "パスワードの最小文字数は8文字以上です",
     "Password minimum character should be more than 8 characters": "パスワードの最小文字数は8文字以上です",
-    "Password field is required": "パスワードの欄は必ず入力してください"
+    "Password field is required": "パスワードの欄は必ず入力してください",
+    "Username or E-mail has invalid characters": "ユーザー名または、メールアドレスに無効な文字があります",
+    "Password minimum character should be more than 6 characters": "パスワードの最小文字数は6文字以上です",
+    "user_not_found": "ユーザーが見つかりません"
   },
   },
   "grid_edit":{
   "grid_edit":{
     "create_bootstrap_4_grid":"Bootstrap 4 グリッドを作成",
     "create_bootstrap_4_grid":"Bootstrap 4 グリッドを作成",

+ 19 - 4
packages/app/public/static/locales/zh_CN/translation.json

@@ -186,7 +186,9 @@
 		"setup": "安装",
 		"setup": "安装",
 		"create_initial_account": "创建初始用户",
 		"create_initial_account": "创建初始用户",
 		"initial_account_will_be_administrator_automatically": "初始帐户将自动成为管理员。",
 		"initial_account_will_be_administrator_automatically": "初始帐户将自动成为管理员。",
-		"unavaliable_user_id": "用户ID不可用"
+		"unavaliable_user_id": "用户ID不可用",
+    "failed_to_install": "GROWI安装失败。请再试一次。",
+    "failed_to_login_after_install": "安装后登录失败。重定向到登录表格..."
 	},
 	},
 	"breaking_changes": {
 	"breaking_changes": {
 		"v346_using_basic_auth": "当前使用的基本身份验证在不久的将来将不再可用。从%s中删除设置"
 		"v346_using_basic_auth": "当前使用的基本身份验证在不久的将来将不再可用。从%s中删除设置"
@@ -736,9 +738,19 @@
 		"fail_to_save_access_token": "无法保存访问令牌。请再试一次。",
 		"fail_to_save_access_token": "无法保存访问令牌。请再试一次。",
 		"fail_to_fetch_access_token": "无法获取访问令牌。请重新连接。",
 		"fail_to_fetch_access_token": "无法获取访问令牌。请重新连接。",
 		"successfully_disconnected": "成功断开连接!",
 		"successfully_disconnected": "成功断开连接!",
-		"strategy_has_not_been_set_up": "{{strategy}尚未设置",
+    "strategy_has_not_been_set_up": {
+      "LocalStrategy"  : "LocalStrategy 尚未设置",
+      "LdapStrategy"   : "LdapStrategy 尚未设置",
+      "GoogleStrategy" : "GoogleStrategy 尚未设置",
+      "GitHubStrategy" : "GitHubStrategy 尚未设置",
+      "TwitterStrategy": "TwitterStrategy 尚未设置",
+      "OidcStrategy"   : "OidcStrategy 尚未设置",
+      "SamlStrategy"   : "SamlStrategy 尚未设置",
+      "Basic"          : "Basic 尚未设置"
+     },
+    "ldap_user_not_valid": "Ldap user is no valid",
+    "external_account_not_exist": "查找或创建外部账户失败",
 		"maximum_number_of_users": "注册的用户数不能超过最大值。",
 		"maximum_number_of_users": "注册的用户数不能超过最大值。",
-		"database_error": "发生数据库服务器错误",
 		"sign_in_failure": "登录失败。",
 		"sign_in_failure": "登录失败。",
 		"aws_sttings_required": "使用此功能所需的AWS设置。请询问管理员。",
 		"aws_sttings_required": "使用此功能所需的AWS设置。请询问管理员。",
 		"application_already_installed": "应用程序已安装。",
 		"application_already_installed": "应用程序已安装。",
@@ -766,7 +778,10 @@
     "Email field is required": "电子邮件字段是必需的",
     "Email field is required": "电子邮件字段是必需的",
     "Password has invalid character": "密码有无效字符",
     "Password has invalid character": "密码有无效字符",
     "Password minimum character should be more than 8 characters": "密码最小字符应超过8个字符",
     "Password minimum character should be more than 8 characters": "密码最小字符应超过8个字符",
-    "Password field is required": "密码字段是必需的"
+    "Password field is required": "密码字段是必需的",
+    "Username or E-mail has invalid characters": "用户名或电子邮件有无效的字符",
+    "Password minimum character should be more than 6 characters": "密码最小字符应超过6个字符",
+    "user_not_found": "未找到用户"
 	},
 	},
   "grid_edit":{
   "grid_edit":{
     "create_bootstrap_4_grid":"创建Bootstrap 4网格",
     "create_bootstrap_4_grid":"创建Bootstrap 4网格",

+ 25 - 25
packages/app/src/components/Fab.tsx

@@ -15,7 +15,7 @@ import { ReturnTopIcon } from './Icons/ReturnTopIcon';
 
 
 import styles from './Fab.module.scss';
 import styles from './Fab.module.scss';
 
 
-// const logger = loggerFactory('growi:cli:Fab');
+const logger = loggerFactory('growi:cli:Fab');
 
 
 export const Fab = (): JSX.Element => {
 export const Fab = (): JSX.Element => {
 
 
@@ -33,30 +33,30 @@ export const Fab = (): JSX.Element => {
   /*
   /*
   * Comment out to prevent err >>> TypeError: Cannot read properties of null (reading 'bottom')
   * Comment out to prevent err >>> TypeError: Cannot read properties of null (reading 'bottom')
   */
   */
-  // const stickyChangeHandler = useCallback((event) => {
-  //   logger.debug('StickyEvents.CHANGE detected');
-
-  //   const newAnimateClasses = event.detail.isSticky ? 'animated fadeInUp faster' : 'animated fadeOut faster';
-  //   const newButtonClasses = event.detail.isSticky ? '' : 'disabled grw-pointer-events-none';
-
-  //   setAnimateClasses(newAnimateClasses);
-  //   setButtonClasses(newButtonClasses);
-  // }, []);
-
-  // // setup effect by sticky event
-  // useEffect(() => {
-  //   // sticky
-  //   // See: https://github.com/ryanwalters/sticky-events
-  //   const stickyEvents = new StickyEvents({ stickySelector: '#grw-fav-sticky-trigger' });
-  //   const { stickySelector } = stickyEvents;
-  //   const elem = document.querySelector(stickySelector);
-  //   elem.addEventListener(StickyEvents.CHANGE, stickyChangeHandler);
-
-  //   // return clean up handler
-  //   return () => {
-  //     elem.removeEventListener(StickyEvents.CHANGE, stickyChangeHandler);
-  //   };
-  // }, [stickyChangeHandler]);
+  const stickyChangeHandler = useCallback((event) => {
+    logger.debug('StickyEvents.CHANGE detected');
+
+    const newAnimateClasses = event.detail.isSticky ? 'animated fadeInUp faster' : 'animated fadeOut faster';
+    const newButtonClasses = event.detail.isSticky ? '' : 'disabled grw-pointer-events-none';
+
+    setAnimateClasses(newAnimateClasses);
+    setButtonClasses(newButtonClasses);
+  }, []);
+
+  // setup effect by sticky event
+  useEffect(() => {
+    // sticky
+    // See: https://github.com/ryanwalters/sticky-events
+    const stickyEvents = new StickyEvents({ stickySelector: '#grw-fav-sticky-trigger' });
+    const { stickySelector } = stickyEvents;
+    const elem = document.querySelector(stickySelector);
+    elem.addEventListener(StickyEvents.CHANGE, stickyChangeHandler);
+
+    // return clean up handler
+    return () => {
+      elem.removeEventListener(StickyEvents.CHANGE, stickyChangeHandler);
+    };
+  }, [stickyChangeHandler]);
 
 
   if (currentPath == null) {
   if (currentPath == null) {
     return <></>;
     return <></>;

+ 0 - 217
packages/app/src/components/InstallerForm.jsx

@@ -1,217 +0,0 @@
-import React from 'react';
-
-import i18next from 'i18next';
-import { useTranslation, i18n } from 'next-i18next';
-import PropTypes from 'prop-types';
-
-import { i18n as i18nConfig } from '^/config/next-i18next.config';
-
-import { useCsrfToken } from '~/stores/context';
-
-class InstallerForm extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      isValidUserName: true,
-      isSubmittingDisabled: false,
-    };
-    this.checkUserName = this.checkUserName.bind(this);
-
-    this.submitHandler = this.submitHandler.bind(this);
-  }
-
-  checkUserName(event) {
-    const axios = require('axios').create({
-      headers: {
-        'Content-Type': 'application/json',
-        'X-Requested-With': 'XMLHttpRequest',
-      },
-      responseType: 'json',
-    });
-    axios.get('/_api/v3/check-username', { params: { username: event.target.value } })
-      .then((res) => { return this.setState({ isValidUserName: res.data.valid }) });
-  }
-
-  submitHandler() {
-    if (this.state.isSubmittingDisabled) {
-      return;
-    }
-
-    this.setState({ isSubmittingDisabled: true });
-    setTimeout(() => {
-      this.setState({ isSubmittingDisabled: false });
-    }, 3000);
-  }
-
-  render() {
-    const { t } = this.props;
-    const hasErrorClass = this.state.isValidUserName ? '' : ' has-error';
-    const unavailableUserId = this.state.isValidUserName
-      ? ''
-      : <span><i className="icon-fw icon-ban" />{ this.props.t('installer.unavaliable_user_id') }</span>;
-
-    return (
-      <div data-testid="installerForm" className={`noLogin-dialog p-3 mx-auto${hasErrorClass}`}>
-        <div className="row">
-          <div className="col-md-12">
-            <p className="alert alert-success">
-              <strong>{ this.props.t('installer.create_initial_account') }</strong><br />
-              <small>{ this.props.t('installer.initial_account_will_be_administrator_automatically') }</small>
-            </p>
-          </div>
-        </div>
-        <div className="row">
-          <form role="form" action="/installer" method="post" id="register-form" className="col-md-12" onSubmit={this.submitHandler}>
-            <div className="dropdown mb-3">
-              <div className="d-flex dropdown-with-icon">
-                <i className="icon-bubbles border-0 rounded-0" />
-                <button
-                  type="button"
-                  className="btn btn-secondary dropdown-toggle text-right w-100 border-0 shadow-none"
-                  id="dropdownLanguage"
-                  data-testid="dropdownLanguage"
-                  data-toggle="dropdown"
-                  aria-haspopup="true"
-                  aria-expanded="true"
-                >
-                  <span className="float-left">
-                    {t('meta.display_name')}
-                  </span>
-                </button>
-                <input
-                  type="hidden"
-                  name="registerForm[app:globalLang]"
-                />
-                <div className="dropdown-menu" aria-labelledby="dropdownLanguage">
-                  {
-                    i18nConfig.locales.map((locale) => {
-                      const fixedT = i18n.getFixedT(locale);
-                      i18n.loadLanguages(i18nConfig.locales);
-
-                      return (
-                        <button
-                          key={locale}
-                          data-testid={`dropdownLanguageMenu-${locale}`}
-                          className="dropdown-item"
-                          type="button"
-                          onClick={() => { i18next.changeLanguage(locale) }}
-                        >
-                          {fixedT('meta.display_name')}
-                        </button>
-                      );
-                    })
-                  }
-                </div>
-              </div>
-            </div>
-
-            <div className={`input-group mb-3${hasErrorClass}`}>
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-user" /></span>
-              </div>
-              <input
-                data-testid="tiUsername"
-                type="text"
-                className="form-control"
-                placeholder={this.props.t('User ID')}
-                name="registerForm[username]"
-                defaultValue={this.props.userName}
-                // onBlur={this.checkUserName} // need not to check username before installation -- 2020.07.24 Yuki Takei
-                required
-              />
-            </div>
-            <p className="form-text">{ unavailableUserId }</p>
-
-            <div className="input-group mb-3">
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-tag" /></span>
-              </div>
-              <input
-                data-testid="tiName"
-                type="text"
-                className="form-control"
-                placeholder={this.props.t('Name')}
-                name="registerForm[name]"
-                defaultValue={this.props.name}
-                required
-              />
-            </div>
-
-            <div className="input-group mb-3">
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-envelope" /></span>
-              </div>
-              <input
-                data-testid="tiEmail"
-                type="email"
-                className="form-control"
-                placeholder={this.props.t('Email')}
-                name="registerForm[email]"
-                defaultValue={this.props.email}
-                required
-              />
-            </div>
-
-            <div className="input-group mb-3">
-              <div className="input-group-prepend">
-                <span className="input-group-text"><i className="icon-lock" /></span>
-              </div>
-              <input
-                data-testid="tiPassword"
-                type="password"
-                className="form-control"
-                placeholder={this.props.t('Password')}
-                name="registerForm[password]"
-                required
-              />
-            </div>
-
-            <input type="hidden" name="_csrf" value={this.props.csrfToken} />
-
-            <div className="input-group mt-4 mb-3 d-flex justify-content-center">
-              <button
-                data-testid="btnSubmit"
-                type="submit"
-                className="btn-fill btn btn-register"
-                id="register"
-                disabled={this.state.isSubmittingDisabled}
-              >
-                <div className="eff"></div>
-                <span className="btn-label"><i className="icon-user-follow" /></span>
-                <span className="btn-label-text">{ this.props.t('Create') }</span>
-              </button>
-            </div>
-
-            <div className="input-group mt-4 d-flex justify-content-center">
-              <a href="https://growi.org" className="link-growi-org">
-                <span className="growi">GROWI</span>.<span className="org">ORG</span>
-              </a>
-            </div>
-          </form>
-        </div>
-      </div>
-    );
-  }
-
-}
-
-InstallerForm.propTypes = {
-  // i18next
-  t: PropTypes.func.isRequired,
-  // for input value
-  userName: PropTypes.string,
-  name: PropTypes.string,
-  email: PropTypes.string,
-  csrfToken: PropTypes.string,
-};
-
-const InstallerFormWrapperFC = (props) => {
-  const { t } = useTranslation();
-  const { data: csrfToken } = useCsrfToken();
-
-  return <InstallerForm t={t} csrfToken={csrfToken} {...props} />;
-};
-
-export default InstallerFormWrapperFC;

+ 231 - 0
packages/app/src/components/InstallerForm.tsx

@@ -0,0 +1,231 @@
+import {
+  FormEventHandler, memo, useCallback, useState,
+} from 'react';
+
+import i18next from 'i18next';
+import { useTranslation, i18n } from 'next-i18next';
+
+import { i18n as i18nConfig } from '^/config/next-i18next.config';
+
+import { toastError } from '~/client/util/apiNotification';
+import { apiv3Post } from '~/client/util/apiv3-client';
+
+const InstallerForm = memo((): JSX.Element => {
+  const { t } = useTranslation();
+
+  const [isValidUserName, setValidUserName] = useState(true);
+  const [isSubmittingDisabled, setSubmittingDisabled] = useState(false);
+
+  const checkUserName = useCallback(async(event) => {
+    const axios = require('axios').create({
+      headers: {
+        'Content-Type': 'application/json',
+        'X-Requested-With': 'XMLHttpRequest',
+      },
+      responseType: 'json',
+    });
+    const res = await axios.get('/_api/v3/check-username', { params: { username: event.target.value } });
+    setValidUserName(res.data.valid);
+  }, []);
+
+  const submitHandler: FormEventHandler = useCallback(async(e: any) => {
+    e.preventDefault();
+
+    if (isSubmittingDisabled) {
+      return;
+    }
+
+    setSubmittingDisabled(true);
+    setTimeout(() => {
+      setSubmittingDisabled(false);
+    }, 3000);
+
+    if (e.target.elements == null) {
+      return;
+    }
+
+    const formData = e.target.elements;
+
+    const {
+      'registerForm[username]': { value: username },
+      'registerForm[name]': { value: name },
+      'registerForm[email]': { value: email },
+      'registerForm[password]': { value: password },
+    } = formData;
+
+    const data = {
+      registerForm: {
+        username,
+        name,
+        email,
+        password,
+        'app:globalLang': formData['registerForm[app:globalLang]'].value,
+      },
+    };
+
+    try {
+      await apiv3Post('/installer', data);
+      window.location.href = '/';
+    }
+    catch (errs) {
+      const err = errs[0];
+      const code = err.code;
+
+      if (code === 'failed_to_login_after_install') {
+        toastError(t('installer.failed_to_login_after_install'));
+        setTimeout(() => { window.location.href = '/login' }, 700); // Wait 700 ms to show toastr
+      }
+
+      toastError(t('installer.failed_to_install'));
+    }
+  }, [isSubmittingDisabled, t]);
+
+  const hasErrorClass = isValidUserName ? '' : ' has-error';
+  const unavailableUserId = isValidUserName
+    ? ''
+    : <span><i className="icon-fw icon-ban" />{ t('installer.unavaliable_user_id') }</span>;
+
+  return (
+    <div data-testid="installerForm" className={`noLogin-dialog p-3 mx-auto${hasErrorClass}`}>
+      <div className="row">
+        <div className="col-md-12">
+          <p className="alert alert-success">
+            <strong>{ t('installer.create_initial_account') }</strong><br />
+            <small>{ t('installer.initial_account_will_be_administrator_automatically') }</small>
+          </p>
+        </div>
+      </div>
+      <div className="row">
+        <form role="form" id="register-form" className="col-md-12" onSubmit={submitHandler}>
+          <div className="dropdown mb-3">
+            <div className="d-flex dropdown-with-icon">
+              <i className="icon-bubbles border-0 rounded-0" />
+              <button
+                type="button"
+                className="btn btn-secondary dropdown-toggle text-right w-100 border-0 shadow-none"
+                id="dropdownLanguage"
+                data-testid="dropdownLanguage"
+                data-toggle="dropdown"
+                aria-haspopup="true"
+                aria-expanded="true"
+              >
+                <span className="float-left">
+                  {t('meta.display_name')}
+                </span>
+              </button>
+              <input
+                type="hidden"
+                name="registerForm[app:globalLang]"
+              />
+              <div className="dropdown-menu" aria-labelledby="dropdownLanguage">
+                {
+                  i18nConfig.locales.map((locale) => {
+                    let fixedT;
+                    if (i18n != null) {
+                      fixedT = i18n.getFixedT(locale);
+                      i18n.loadLanguages(i18nConfig.locales);
+                    }
+
+                    return (
+                      <button
+                        key={locale}
+                        data-testid={`dropdownLanguageMenu-${locale}`}
+                        className="dropdown-item"
+                        type="button"
+                        onClick={() => { i18next.changeLanguage(locale) }}
+                      >
+                        {fixedT?.('meta.display_name')}
+                      </button>
+                    );
+                  })
+                }
+              </div>
+            </div>
+          </div>
+
+          <div className={`input-group mb-3${hasErrorClass}`}>
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-user" /></span>
+            </div>
+            <input
+              data-testid="tiUsername"
+              type="text"
+              className="form-control"
+              placeholder={t('User ID')}
+              name="registerForm[username]"
+              // onBlur={checkUserName} // need not to check username before installation -- 2020.07.24 Yuki Takei
+              required
+            />
+          </div>
+          <p className="form-text">{ unavailableUserId }</p>
+
+          <div className="input-group mb-3">
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-tag" /></span>
+            </div>
+            <input
+              data-testid="tiName"
+              type="text"
+              className="form-control"
+              placeholder={t('Name')}
+              name="registerForm[name]"
+              required
+            />
+          </div>
+
+          <div className="input-group mb-3">
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-envelope" /></span>
+            </div>
+            <input
+              data-testid="tiEmail"
+              type="email"
+              className="form-control"
+              placeholder={t('Email')}
+              name="registerForm[email]"
+              required
+            />
+          </div>
+
+          <div className="input-group mb-3">
+            <div className="input-group-prepend">
+              <span className="input-group-text"><i className="icon-lock" /></span>
+            </div>
+            <input
+              data-testid="tiPassword"
+              type="password"
+              className="form-control"
+              placeholder={t('Password')}
+              name="registerForm[password]"
+              required
+            />
+          </div>
+
+          <div className="input-group mt-4 mb-3 d-flex justify-content-center">
+            <button
+              data-testid="btnSubmit"
+              type="submit"
+              className="btn-fill btn btn-register"
+              id="register"
+              disabled={isSubmittingDisabled}
+            >
+              <div className="eff"></div>
+              <span className="btn-label"><i className="icon-user-follow" /></span>
+              <span className="btn-label-text">{ t('Create') }</span>
+            </button>
+          </div>
+
+          <div className="input-group mt-4 d-flex justify-content-center">
+            <a href="https://growi.org" className="link-growi-org">
+              <span className="growi">GROWI</span>.<span className="org">ORG</span>
+            </a>
+          </div>
+        </form>
+      </div>
+    </div>
+  );
+});
+
+InstallerForm.displayName = 'InstallerForm';
+
+export default InstallerForm;

+ 101 - 55
packages/app/src/components/LoginForm.tsx

@@ -7,7 +7,6 @@ import { useRouter } from 'next/router';
 import ReactCardFlip from 'react-card-flip';
 import ReactCardFlip from 'react-card-flip';
 
 
 import { apiv3Post } from '~/client/util/apiv3-client';
 import { apiv3Post } from '~/client/util/apiv3-client';
-import { useCsrfToken } from '~/stores/context';
 
 
 type LoginFormProps = {
 type LoginFormProps = {
   username?: string,
   username?: string,
@@ -26,22 +25,25 @@ type LoginFormProps = {
 export const LoginForm = (props: LoginFormProps): JSX.Element => {
 export const LoginForm = (props: LoginFormProps): JSX.Element => {
   const { t } = useTranslation();
   const { t } = useTranslation();
   const router = useRouter();
   const router = useRouter();
-  const { data: csrfToken } = useCsrfToken();
 
 
   const {
   const {
     isLocalStrategySetup, isLdapStrategySetup, isPasswordResetEnabled, isRegistrationEnabled,
     isLocalStrategySetup, isLdapStrategySetup, isPasswordResetEnabled, isRegistrationEnabled,
-    isEmailAuthenticationEnabled, registrationMode, registrationWhiteList, isMailerSetup,
+    isEmailAuthenticationEnabled, registrationMode, registrationWhiteList, isMailerSetup, objOfIsExternalAuthEnableds,
   } = props;
   } = props;
   const isLocalOrLdapStrategiesEnabled = isLocalStrategySetup || isLdapStrategySetup;
   const isLocalOrLdapStrategiesEnabled = isLocalStrategySetup || isLdapStrategySetup;
-  // const isSomeExternalAuthEnabled = Object.values(objOfIsExternalAuthEnableds).some(elem => elem);
-  const isSomeExternalAuthEnabled = true;
+  const isSomeExternalAuthEnabled = Object.values(objOfIsExternalAuthEnableds).some(elem => elem);
 
 
   // states
   // states
   const [isRegistering, setIsRegistering] = useState(false);
   const [isRegistering, setIsRegistering] = useState(false);
-  const [username, setUsername] = useState('');
-  const [name, setName] = useState('');
-  const [email, setEmail] = useState('');
-  const [password, setPassword] = useState('');
+  // For Login
+  const [usernameForLogin, setUsernameForLogin] = useState('');
+  const [passwordForLogin, setPasswordForLogin] = useState('');
+  const [loginErrors, setLoginErrors] = useState<Error[]>([]);
+  // For Register
+  const [usernameForRegister, setUsernameForRegister] = useState('');
+  const [nameForRegister, setNameForRegister] = useState('');
+  const [emailForRegister, setEmailForRegister] = useState('');
+  const [passwordForRegister, setPasswordForRegister] = useState('');
   const [registerErrors, setRegisterErrors] = useState<Error[]>([]);
   const [registerErrors, setRegisterErrors] = useState<Error[]>([]);
 
 
   useEffect(() => {
   useEffect(() => {
@@ -57,49 +59,86 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
 
 
     window.location.href = `/passport/${auth}`;
     window.location.href = `/passport/${auth}`;
   }, []);
   }, []);
+
+  const handleLoginWithLocalSubmit = useCallback(async(e) => {
+    e.preventDefault();
+
+    const loginForm = {
+      username: usernameForLogin,
+      password: passwordForLogin,
+    };
+
+    try {
+      const res = await apiv3Post('/login', { loginForm });
+      const { redirectTo } = res.data;
+      router.push(redirectTo);
+    }
+    catch (err) {
+      setLoginErrors(err);
+    }
+    return;
+
+  }, [passwordForLogin, router, usernameForLogin]);
+
   const renderLocalOrLdapLoginForm = useCallback(() => {
   const renderLocalOrLdapLoginForm = useCallback(() => {
     const { isLdapStrategySetup } = props;
     const { isLdapStrategySetup } = props;
-
     return (
     return (
-      <form role="form" action="/login" method="post">
-        <div className="input-group">
-          <div className="input-group-prepend">
-            <span className="input-group-text">
-              <i className="icon-user"></i>
-            </span>
-          </div>
-          <input type="text" className="form-control rounded-0" data-testid="tiUsernameForLogin" placeholder="Username or E-mail" name="loginForm[username]" />
-          {isLdapStrategySetup && (
-            <div className="input-group-append">
-              <small className="input-group-text text-success">
-                <i className="icon-fw icon-check"></i> LDAP
-              </small>
+      <>
+        {
+          loginErrors != null && loginErrors.length > 0 && (
+            <p className="alert alert-danger">
+              {loginErrors.map((err, index) => {
+                return (
+                  <span key={index}>
+                    {t(err.message)}<br/>
+                  </span>
+                );
+              })}
+            </p>
+          )
+        }
+        <form role="form" onSubmit={handleLoginWithLocalSubmit} id="login-form">
+          <div className="input-group">
+            <div className="input-group-prepend">
+              <span className="input-group-text">
+                <i className="icon-user"></i>
+              </span>
             </div>
             </div>
-          )}
-        </div>
+            <input type="text" className="form-control rounded-0" data-testid="tiUsernameForLogin" placeholder="Username or E-mail"
+              onChange={(e) => { setUsernameForLogin(e.target.value) }} name="usernameForLogin" />
+            {isLdapStrategySetup && (
+              <div className="input-group-append">
+                <small className="input-group-text text-success">
+                  <i className="icon-fw icon-check"></i> LDAP
+                </small>
+              </div>
+            )}
+          </div>
 
 
-        <div className="input-group">
-          <div className="input-group-prepend">
-            <span className="input-group-text">
-              <i className="icon-lock"></i>
-            </span>
+          <div className="input-group">
+            <div className="input-group-prepend">
+              <span className="input-group-text">
+                <i className="icon-lock"></i>
+              </span>
+            </div>
+            <input type="password" className="form-control rounded-0" data-testid="tiPasswordForLogin" placeholder="Password"
+              onChange={(e) => { setPasswordForLogin(e.target.value) }} name="passwordForLogin" />
           </div>
           </div>
-          <input type="password" className="form-control rounded-0" data-testid="tiPasswordForLogin" placeholder="Password" name="loginForm[password]" />
-        </div>
 
 
-        <div className="input-group my-4">
-          <input type="hidden" name="_csrf" value={csrfToken} />
-          <button type="submit" id="login" className="btn btn-fill rounded-0 login mx-auto" data-testid="btnSubmitForLogin">
-            <div className="eff"></div>
-            <span className="btn-label">
-              <i className="icon-login"></i>
-            </span>
-            <span className="btn-label-text">{t('Sign in')}</span>
-          </button>
-        </div>
-      </form>
+          <div className="input-group my-4">
+            <button type="submit" id="login" className="btn btn-fill rounded-0 login mx-auto" data-testid="btnSubmitForLogin">
+              <div className="eff"></div>
+              <span className="btn-label">
+                <i className="icon-login"></i>
+              </span>
+              <span className="btn-label-text">{t('Sign in')}</span>
+            </button>
+          </div>
+        </form>
+      </>
     );
     );
-  }, [csrfToken, props, t]);
+  }, [handleLoginWithLocalSubmit, loginErrors, props, t]);
+
   const renderExternalAuthInput = useCallback((auth) => {
   const renderExternalAuthInput = useCallback((auth) => {
     const authIconNames = {
     const authIconNames = {
       google: 'google',
       google: 'google',
@@ -124,6 +163,7 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
       </div>
       </div>
     );
     );
   }, [handleLoginWithExternalAuth, t]);
   }, [handleLoginWithExternalAuth, t]);
+
   const renderExternalAuthLoginForm = useCallback(() => {
   const renderExternalAuthLoginForm = useCallback(() => {
     const { isLocalStrategySetup, isLdapStrategySetup, objOfIsExternalAuthEnableds } = props;
     const { isLocalStrategySetup, isLdapStrategySetup, objOfIsExternalAuthEnableds } = props;
     const isExternalAuthCollapsible = isLocalStrategySetup || isLdapStrategySetup;
     const isExternalAuthCollapsible = isLocalStrategySetup || isLdapStrategySetup;
@@ -163,10 +203,10 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
     e.preventDefault();
     e.preventDefault();
 
 
     const registerForm = {
     const registerForm = {
-      username,
-      name,
-      email,
-      password,
+      username: usernameForRegister,
+      name: nameForRegister,
+      email: emailForRegister,
+      password: passwordForRegister,
     };
     };
     try {
     try {
       const res = await apiv3Post(requestPath, { registerForm });
       const res = await apiv3Post(requestPath, { registerForm });
@@ -180,7 +220,12 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
       }
       }
     }
     }
     return;
     return;
-  }, [email, name, password, router, username]);
+  }, [emailForRegister, nameForRegister, passwordForRegister, router, usernameForRegister]);
+
+  const resetLoginErrors = useCallback(() => {
+    if (loginErrors.length === 0) return;
+    setLoginErrors([]);
+  }, [loginErrors.length]);
 
 
   const resetRegisterErrors = useCallback(() => {
   const resetRegisterErrors = useCallback(() => {
     if (registerErrors.length === 0) return;
     if (registerErrors.length === 0) return;
@@ -189,8 +234,9 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
 
 
   const switchForm = useCallback(() => {
   const switchForm = useCallback(() => {
     setIsRegistering(!isRegistering);
     setIsRegistering(!isRegistering);
+    resetLoginErrors();
     resetRegisterErrors();
     resetRegisterErrors();
-  }, [isRegistering, resetRegisterErrors]);
+  }, [isRegistering, resetLoginErrors, resetRegisterErrors]);
 
 
   const renderRegisterForm = useCallback(() => {
   const renderRegisterForm = useCallback(() => {
     let registerAction = '/register';
     let registerAction = '/register';
@@ -222,7 +268,7 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
               {registerErrors.map((err, index) => {
               {registerErrors.map((err, index) => {
                 return (
                 return (
                   <span key={index}>
                   <span key={index}>
-                    {t(`message.${err.message}`)}<br/>
+                    {t(err.message)}<br/>
                   </span>
                   </span>
                 );
                 );
               })}
               })}
@@ -244,7 +290,7 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
                 <input
                 <input
                   type="text"
                   type="text"
                   className="form-control rounded-0"
                   className="form-control rounded-0"
-                  onChange={(e) => { setUsername(e.target.value) }}
+                  onChange={(e) => { setUsernameForRegister(e.target.value) }}
                   placeholder={t('User ID')}
                   placeholder={t('User ID')}
                   name="username"
                   name="username"
                   defaultValue={props.username}
                   defaultValue={props.username}
@@ -263,7 +309,7 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
                 {/* name */}
                 {/* name */}
                 <input type="text"
                 <input type="text"
                   className="form-control rounded-0"
                   className="form-control rounded-0"
-                  onChange={(e) => { setName(e.target.value) }}
+                  onChange={(e) => { setNameForRegister(e.target.value) }}
                   placeholder={t('Name')}
                   placeholder={t('Name')}
                   name="name"
                   name="name"
                   defaultValue={props.name}
                   defaultValue={props.name}
@@ -281,7 +327,7 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
             {/* email */}
             {/* email */}
             <input type="email"
             <input type="email"
               className="form-control rounded-0"
               className="form-control rounded-0"
-              onChange={(e) => { setEmail(e.target.value) }}
+              onChange={(e) => { setEmailForRegister(e.target.value) }}
               placeholder={t('Email')}
               placeholder={t('Email')}
               name="email"
               name="email"
               defaultValue={props.email}
               defaultValue={props.email}
@@ -315,7 +361,7 @@ export const LoginForm = (props: LoginFormProps): JSX.Element => {
                 {/* Password */}
                 {/* Password */}
                 <input type="password"
                 <input type="password"
                   className="form-control rounded-0"
                   className="form-control rounded-0"
-                  onChange={(e) => { setPassword(e.target.value) }}
+                  onChange={(e) => { setPasswordForRegister(e.target.value) }}
                   placeholder={t('Password')}
                   placeholder={t('Password')}
                   name="password"
                   name="password"
                   required />
                   required />

+ 4 - 3
packages/app/src/components/Navbar/GrowiContextualSubNavigation.tsx

@@ -39,7 +39,6 @@ import { Skelton } from '../Skelton';
 import { GrowiSubNavigation } from './GrowiSubNavigation';
 import { GrowiSubNavigation } from './GrowiSubNavigation';
 import { SubNavButtonsProps } from './SubNavButtons';
 import { SubNavButtonsProps } from './SubNavButtons';
 
 
-
 import PageEditorModeManagerStyles from './PageEditorModeManager.module.scss';
 import PageEditorModeManagerStyles from './PageEditorModeManager.module.scss';
 
 
 
 
@@ -47,9 +46,11 @@ const PageEditorModeManager = dynamic(
   () => import('./PageEditorModeManager'),
   () => import('./PageEditorModeManager'),
   { ssr: false, loading: () => <Skelton additionalClass={`${PageEditorModeManagerStyles['grw-page-editor-mode-manager-skelton']}`} /> },
   { ssr: false, loading: () => <Skelton additionalClass={`${PageEditorModeManagerStyles['grw-page-editor-mode-manager-skelton']}`} /> },
 );
 );
+// TODO: If enable skeleton, we get hydration error when create a page from PageCreateModal
+// { ssr: false, loading: () => <Skelton additionalClass='btn-skelton py-2' /> },
 const SubNavButtons = dynamic<SubNavButtonsProps>(
 const SubNavButtons = dynamic<SubNavButtonsProps>(
   () => import('./SubNavButtons').then(mod => mod.SubNavButtons),
   () => import('./SubNavButtons').then(mod => mod.SubNavButtons),
-  { ssr: false, loading: () => <Skelton additionalClass='btn-skelton py-2' /> },
+  { ssr: false, loading: () => <></> },
 );
 );
 
 
 
 
@@ -309,10 +310,10 @@ const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps):
         />
         />
       );
       );
     };
     };
+
     return (
     return (
       <>
       <>
         <div className="d-flex flex-column align-items-end justify-content-center py-md-2" style={{ gap: `${isCompactMode ? '5px' : '7px'}` }}>
         <div className="d-flex flex-column align-items-end justify-content-center py-md-2" style={{ gap: `${isCompactMode ? '5px' : '7px'}` }}>
-
           { isViewMode && (
           { isViewMode && (
             <div className="h-50 w-100">
             <div className="h-50 w-100">
               { pageId != null && (
               { pageId != null && (

+ 15 - 1
packages/app/src/components/Navbar/GrowiSubNavigation.module.scss

@@ -44,6 +44,21 @@
       }
       }
     }
     }
 
 
+    .btn-copy {
+      &:not(:hover):not(:active) {
+        background-color: transparent !important;
+      }
+      opacity: 0.5;
+    }
+
+    .btn-edit-tags {
+      opacity: 0.5;
+
+      &.no-tags {
+        opacity: 0.7;
+      }
+    }
+
     .btn-skelton {
     .btn-skelton {
       @extend %subnav-buttons-height;
       @extend %subnav-buttons-height;
       width: 100%;
       width: 100%;
@@ -109,7 +124,6 @@
   &:global {
   &:global {
     &:hover {
     &:hover {
       .btn-copy,
       .btn-copy,
-      .btn-edit,
       .btn-edit-tags {
       .btn-edit-tags {
         // change button opacity
         // change button opacity
         opacity: unset;
         opacity: unset;

+ 1 - 2
packages/app/src/components/PagePathNav.tsx

@@ -7,8 +7,6 @@ import { useIsNotFound } from '~/stores/context';
 
 
 import LinkedPagePath from '../models/linked-page-path';
 import LinkedPagePath from '../models/linked-page-path';
 
 
-import PagePathHierarchicalLink from './PagePathHierarchicalLink';
-
 const { isTrashPage } = pagePathUtils;
 const { isTrashPage } = pagePathUtils;
 
 
 type Props = {
 type Props = {
@@ -19,6 +17,7 @@ type Props = {
 }
 }
 
 
 const CopyDropdown = dynamic(() => import('./Page/CopyDropdown'), { ssr: false });
 const CopyDropdown = dynamic(() => import('./Page/CopyDropdown'), { ssr: false });
+const PagePathHierarchicalLink = dynamic(() => import('./PagePathHierarchicalLink'), { ssr: false });
 
 
 const PagePathNav: FC<Props> = (props: Props) => {
 const PagePathNav: FC<Props> = (props: Props) => {
   const {
   const {

+ 1 - 1
packages/app/src/pages/utils/commons.ts

@@ -44,7 +44,7 @@ export const getServerSideCommonProps: GetServerSideProps<CommonProps> = async(c
     namespacesRequired: ['translation'],
     namespacesRequired: ['translation'],
     currentPathname,
     currentPathname,
     appTitle: appService.getAppTitle(),
     appTitle: appService.getAppTitle(),
-    siteUrl: appService.getSiteUrl(),
+    siteUrl: configManager.getConfig('crowi', 'app:siteUrl'), // DON'T USE appService.getSiteUrl()
     confidential: appService.getAppConfidential() || '',
     confidential: appService.getAppConfidential() || '',
     theme: configManager.getConfig('crowi', 'customize:theme'),
     theme: configManager.getConfig('crowi', 'customize:theme'),
     customTitleTemplate: customizeService.customTitleTemplate,
     customTitleTemplate: customizeService.customTitleTemplate,

+ 9 - 7
packages/app/src/server/middlewares/login-form-validator.ts

@@ -49,18 +49,18 @@ export const loginRules = () => {
   return [
   return [
     body('loginForm.username')
     body('loginForm.username')
       .matches(/^[\da-zA-Z\-_.+@]+$/)
       .matches(/^[\da-zA-Z\-_.+@]+$/)
-      .withMessage('Username or E-mail has invalid characters')
+      .withMessage('message.Username or E-mail has invalid characters')
       .not()
       .not()
       .isEmpty()
       .isEmpty()
-      .withMessage('Username field is required'),
+      .withMessage('message.Username field is required'),
     body('loginForm.password')
     body('loginForm.password')
       .matches(/^[\x20-\x7F]*$/)
       .matches(/^[\x20-\x7F]*$/)
-      .withMessage('Password has invalid character')
+      .withMessage('message.Password has invalid character')
       .isLength({ min: 6 })
       .isLength({ min: 6 })
-      .withMessage('Password minimum character should be more than 6 characters')
+      .withMessage('message.Password minimum character should be more than 6 characters')
       .not()
       .not()
       .isEmpty()
       .isEmpty()
-      .withMessage('Password field is required'),
+      .withMessage('message.Password field is required'),
   ];
   ];
 };
 };
 
 
@@ -78,8 +78,10 @@ export const loginValidation = (req, res, next) => {
   const extractedErrors: string[] = [];
   const extractedErrors: string[] = [];
   errors.array().map(err => extractedErrors.push(err.msg));
   errors.array().map(err => extractedErrors.push(err.msg));
 
 
-  req.flash('errorMessages', extractedErrors);
-  Object.assign(form, { isValid: false });
+  Object.assign(form, {
+    isValid: false,
+    errors: extractedErrors,
+  });
   req.form = form;
   req.form = form;
 
 
   return next();
   return next();

+ 8 - 8
packages/app/src/server/middlewares/register-form-validator.ts

@@ -6,24 +6,24 @@ export const registerRules = () => {
   return [
   return [
     body('registerForm.username')
     body('registerForm.username')
       .matches(/^[\da-zA-Z\-_.]+$/)
       .matches(/^[\da-zA-Z\-_.]+$/)
-      .withMessage('Username has invalid characters')
+      .withMessage('message.Username has invalid characters')
       .not()
       .not()
       .isEmpty()
       .isEmpty()
-      .withMessage('Username field is required'),
-    body('registerForm.name').not().isEmpty().withMessage('Name field is required'),
+      .withMessage('message.Username field is required'),
+    body('registerForm.name').not().isEmpty().withMessage('message.Name field is required'),
     body('registerForm.email')
     body('registerForm.email')
       .isEmail()
       .isEmail()
-      .withMessage('Email format is invalid')
+      .withMessage('message.Email format is invalid')
       .exists()
       .exists()
-      .withMessage('Email field is required'),
+      .withMessage('message.Email field is required'),
     body('registerForm.password')
     body('registerForm.password')
       .matches(/^[\x20-\x7F]*$/)
       .matches(/^[\x20-\x7F]*$/)
-      .withMessage('Password has invalid character')
+      .withMessage('message.Password has invalid character')
       .isLength({ min: PASSOWRD_MINIMUM_NUMBER })
       .isLength({ min: PASSOWRD_MINIMUM_NUMBER })
-      .withMessage('Password minimum character should be more than 8 characters')
+      .withMessage('message.Password minimum character should be more than 8 characters')
       .not()
       .not()
       .isEmpty()
       .isEmpty()
-      .withMessage('Password field is required'),
+      .withMessage('message.Password field is required'),
     body('registerForm[app:globalLang]'),
     body('registerForm[app:globalLang]'),
   ];
   ];
 };
 };

+ 11 - 1
packages/app/src/server/routes/apiv3/index.js

@@ -16,7 +16,7 @@ const router = express.Router();
 const routerForAdmin = express.Router();
 const routerForAdmin = express.Router();
 const routerForAuth = express.Router();
 const routerForAuth = express.Router();
 
 
-module.exports = (crowi, app) => {
+module.exports = (crowi, app, isInstalled) => {
 
 
   // add custom functions to express response
   // add custom functions to express response
   require('./response')(express, crowi);
   require('./response')(express, crowi);
@@ -44,6 +44,10 @@ module.exports = (crowi, app) => {
   const applicationInstalled = require('../../middlewares/application-installed')(crowi);
   const applicationInstalled = require('../../middlewares/application-installed')(crowi);
   const addActivity = generateAddActivityMiddleware(crowi);
   const addActivity = generateAddActivityMiddleware(crowi);
   const login = require('../login')(crowi, app);
   const login = require('../login')(crowi, app);
+  const loginPassport = require('../login-passport')(crowi, app);
+
+  routerForAuth.post('/login', applicationInstalled, loginFormValidator.loginRules(), loginFormValidator.loginValidation,
+    addActivity, loginPassport.loginWithLocal, loginPassport.loginWithLdap, loginPassport.cannotLoginErrorHadnler, loginPassport.loginFailure);
 
 
   routerForAuth.use('/logout', require('./logout')(crowi));
   routerForAuth.use('/logout', require('./logout')(crowi));
 
 
@@ -53,6 +57,12 @@ module.exports = (crowi, app) => {
   routerForAuth.post('/invited/activateInvited',
   routerForAuth.post('/invited/activateInvited',
     applicationInstalled, loginFormValidator.inviteRules(), loginFormValidator.inviteValidation, login.invited);
     applicationInstalled, loginFormValidator.inviteRules(), loginFormValidator.inviteValidation, login.invited);
 
 
+  // installer
+  if (!isInstalled) {
+    routerForAdmin.use('/installer', require('./installer')(crowi));
+    return [router, routerForAdmin, routerForAuth];
+  }
+
   router.use('/in-app-notification', require('./in-app-notification')(crowi));
   router.use('/in-app-notification', require('./in-app-notification')(crowi));
 
 
   router.use('/personal-setting', require('./personal-setting')(crowi));
   router.use('/personal-setting', require('./personal-setting')(crowi));

+ 76 - 0
packages/app/src/server/routes/apiv3/installer.ts

@@ -0,0 +1,76 @@
+import express, { Request, Router } from 'express';
+
+import { SupportedAction } from '~/interfaces/activity';
+import ErrorV3 from '~/server/models/vo/error-apiv3';
+import loggerFactory from '~/utils/logger';
+
+import Crowi from '../../crowi';
+import { generateAddActivityMiddleware } from '../../middlewares/add-activity';
+import { apiV3FormValidator } from '../../middlewares/apiv3-form-validator';
+import { registerRules } from '../../middlewares/register-form-validator';
+import { InstallerService, FailedToCreateAdminUserError } from '../../service/installer';
+
+import { ApiV3Response } from './interfaces/apiv3-response';
+
+
+const logger = loggerFactory('growi:routes:apiv3:installer');
+
+
+type FormRequest = Request & { form: any, logIn: any };
+
+module.exports = (crowi: Crowi): Router => {
+  const addActivity = generateAddActivityMiddleware(crowi);
+
+  const activityEvent = crowi.event('activity');
+
+  const router = express.Router();
+
+  // eslint-disable-next-line max-len
+  router.post('/', registerRules(), apiV3FormValidator, addActivity, async(req: FormRequest, res: ApiV3Response) => {
+    const appService = crowi.appService;
+    if (appService == null) {
+      return res.apiv3Err(new ErrorV3('GROWI cannot be installed due to an internal error', 'app_service_not_setup'), 500);
+    }
+    const registerForm = req.body.registerForm || {};
+
+    const name = registerForm.name;
+    const username = registerForm.username;
+    const email = registerForm.email;
+    const password = registerForm.password;
+    const language = registerForm['app:globalLang'] || 'en_US';
+
+    const installerService = new InstallerService(crowi);
+
+    let adminUser;
+    try {
+      adminUser = await installerService.install({
+        name,
+        username,
+        email,
+        password,
+      }, language);
+    }
+    catch (err) {
+      if (err instanceof FailedToCreateAdminUserError) {
+        return res.apiv3Err(new ErrorV3(err.message, 'failed_to_create_admin_user'));
+      }
+      return res.apiv3Err(new ErrorV3(err, 'failed_to_install'));
+    }
+
+    await appService.setupAfterInstall();
+
+    const parameters = { action: SupportedAction.ACTION_USER_REGISTRATION_SUCCESS };
+    activityEvent.emit('update', res.locals.activity._id, parameters);
+
+    // login with passport
+    req.logIn(adminUser, (err) => {
+      if (err != null) {
+        return res.apiv3Err(new ErrorV3(err, 'failed_to_login_after_install'));
+      }
+
+      return res.apiv3({ message: 'Installation completed (Logged in as an admin user)' });
+    });
+  });
+
+  return router;
+};

+ 1 - 4
packages/app/src/server/routes/index.js

@@ -61,7 +61,7 @@ module.exports = function(crowi, app) {
 
 
   /* eslint-disable max-len, comma-spacing, no-multi-spaces */
   /* eslint-disable max-len, comma-spacing, no-multi-spaces */
 
 
-  const [apiV3Router, apiV3AdminRouter, apiV3AuthRouter] = require('./apiv3')(crowi, app);
+  const [apiV3Router, apiV3AdminRouter, apiV3AuthRouter] = require('./apiv3')(crowi, app, isInstalled);
 
 
   app.use('/api-docs', require('./apiv3/docs')(crowi, app));
   app.use('/api-docs', require('./apiv3/docs')(crowi, app));
 
 
@@ -81,7 +81,6 @@ module.exports = function(crowi, app) {
   app.get('/login/error/:reason'      , applicationInstalled, login.error);
   app.get('/login/error/:reason'      , applicationInstalled, login.error);
   app.get('/login'                    , applicationInstalled, login.preLogin, next.delegateToNext);
   app.get('/login'                    , applicationInstalled, login.preLogin, next.delegateToNext);
   app.get('/invited'                  , applicationInstalled, next.delegateToNext);
   app.get('/invited'                  , applicationInstalled, next.delegateToNext);
-  // app.post('/invited/activateInvited' , applicationInstalled, loginFormValidator.inviteRules(), loginFormValidator.inviteValidation, csrfProtection, login.invited);
   app.post('/login'                   , applicationInstalled, loginFormValidator.loginRules(), loginFormValidator.loginValidation, csrfProtection,  addActivity, loginPassport.loginWithLocal, loginPassport.loginWithLdap, loginPassport.loginFailure);
   app.post('/login'                   , applicationInstalled, loginFormValidator.loginRules(), loginFormValidator.loginValidation, csrfProtection,  addActivity, loginPassport.loginWithLocal, loginPassport.loginWithLdap, loginPassport.loginFailure);
 
 
   app.get('/register'                 , applicationInstalled, login.preLogin, login.register);
   app.get('/register'                 , applicationInstalled, login.preLogin, login.register);
@@ -92,9 +91,7 @@ module.exports = function(crowi, app) {
 
 
   // installer
   // installer
   if (!isInstalled) {
   if (!isInstalled) {
-    const installer = require('./installer')(crowi);
     app.get('/installer'              , applicationNotInstalled, next.delegateToNext);
     app.get('/installer'              , applicationNotInstalled, next.delegateToNext);
-    app.post('/installer'             , applicationNotInstalled , registerFormValidator.registerRules(), registerFormValidator.registerValidation, csrfProtection, addActivity, installer.install);
     return;
     return;
   }
   }
 
 

+ 0 - 70
packages/app/src/server/routes/installer.js

@@ -1,70 +0,0 @@
-import { SupportedAction } from '~/interfaces/activity';
-import loggerFactory from '~/utils/logger';
-
-import { InstallerService, FailedToCreateAdminUserError } from '../service/installer';
-
-const logger = loggerFactory('growi:routes:installer');
-
-module.exports = function(crowi) {
-
-  const actions = {};
-
-  const activityEvent = crowi.event('activity');
-
-  actions.index = function(req, res) {
-    return res.render('installer');
-  };
-
-  actions.install = async function(req, res, next) {
-    const registerForm = req.body.registerForm || {};
-
-    if (!req.form.isValid) {
-      return res.render('installer');
-    }
-
-    const name = registerForm.name;
-    const username = registerForm.username;
-    const email = registerForm.email;
-    const password = registerForm.password;
-    const language = registerForm['app:globalLang'] || 'en_US';
-
-    const installerService = new InstallerService(crowi);
-
-    let adminUser;
-    try {
-      adminUser = await installerService.install({
-        name,
-        username,
-        email,
-        password,
-      }, language);
-    }
-    catch (err) {
-      if (err instanceof FailedToCreateAdminUserError) {
-        req.form.errors.push(req.t('message.failed_to_create_admin_user', { errMessage: err.message }));
-      }
-      return res.render('installer');
-    }
-
-    const appService = crowi.appService;
-    appService.setupAfterInstall();
-
-    // login with passport
-    req.logIn(adminUser, (err) => {
-      if (err) {
-        req.flash('successMessage', req.t('message.complete_to_install1'));
-        req.session.redirectTo = '/';
-        return res.redirect('/login');
-      }
-
-      req.flash('successMessage', req.t('message.complete_to_install2'));
-
-      const parameters = { action: SupportedAction.ACTION_USER_REGISTRATION_SUCCESS };
-      activityEvent.emit('update', res.locals.activity._id, parameters);
-
-      return res.redirect('/');
-    });
-  };
-
-  return actions;
-};

+ 113 - 90
packages/app/src/server/routes/login-passport.js

@@ -2,6 +2,8 @@ import { SupportedAction } from '~/interfaces/activity';
 import { NullUsernameToBeRegisteredError } from '~/server/models/errors';
 import { NullUsernameToBeRegisteredError } from '~/server/models/errors';
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
+import ErrorV3 from '../models/vo/error-apiv3';
+
 /* eslint-disable no-use-before-define */
 /* eslint-disable no-use-before-define */
 
 
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
@@ -15,6 +17,74 @@ module.exports = function(crowi, app) {
 
 
   const ApiResponse = require('../util/apiResponse');
   const ApiResponse = require('../util/apiResponse');
 
 
+  const promisifiedPassportAuthentication = (strategyName, req, res) => {
+    return new Promise((resolve, reject) => {
+      passport.authenticate(strategyName, (err, response, info) => {
+        if (res.headersSent) { // dirty hack -- 2017.09.25
+          return; //              cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
+        }
+
+        logger.debug(`--- authenticate with ${strategyName} strategy ---`);
+
+        if (err) {
+          logger.error(`'${strategyName}' passport authentication error: `, err);
+          reject(err);
+        }
+
+        logger.debug('response', response);
+        logger.debug('info', info);
+
+        // authentication failure
+        if (!response) {
+          reject(response);
+        }
+
+        resolve(response);
+      })(req, res);
+    });
+  };
+
+  const getOrCreateUser = async(req, res, userInfo, providerId) => {
+    // get option
+    const isSameUsernameTreatedAsIdenticalUser = crowi.passportService.isSameUsernameTreatedAsIdenticalUser(providerId);
+    const isSameEmailTreatedAsIdenticalUser = crowi.passportService.isSameEmailTreatedAsIdenticalUser(providerId);
+
+    try {
+      // find or register(create) user
+      const externalAccount = await ExternalAccount.findOrRegister(
+        providerId,
+        userInfo.id,
+        userInfo.username,
+        userInfo.name,
+        userInfo.email,
+        isSameUsernameTreatedAsIdenticalUser,
+        isSameEmailTreatedAsIdenticalUser,
+      );
+      return externalAccount;
+    }
+    catch (err) {
+      /* eslint-disable no-else-return */
+      if (err instanceof NullUsernameToBeRegisteredError) {
+        logger.error(err.message);
+        throw Error(err.message);
+      }
+      else if (err.name === 'DuplicatedUsernameException') {
+        if (isSameEmailTreatedAsIdenticalUser || isSameUsernameTreatedAsIdenticalUser) {
+          // associate to existing user
+          debug(`ExternalAccount '${userInfo.username}' will be created and bound to the exisiting User account`);
+          return ExternalAccount.associate(providerId, userInfo.id, err.user);
+        }
+        logger.error('provider-DuplicatedUsernameException', providerId);
+        throw Error(`provider-DuplicatedUsernameException: ${providerId}`);
+      }
+      else if (err.name === 'UserUpperLimitException') {
+        logger.error(err.message);
+        throw Error(err.message);
+      }
+      /* eslint-enable no-else-return */
+    }
+  };
+
   /**
   /**
    * success handler
    * success handler
    * @param {*} req
    * @param {*} req
@@ -44,7 +114,7 @@ module.exports = function(crowi, app) {
     };
     };
     await crowi.activityService.createActivity(parameters);
     await crowi.activityService.createActivity(parameters);
 
 
-    return res.safeRedirect(redirectTo);
+    return res.apiv3({ redirectTo });
   };
   };
 
 
   /**
   /**
@@ -61,13 +131,23 @@ module.exports = function(crowi, app) {
     return res.redirect('/login');
     return res.redirect('/login');
   };
   };
 
 
+  const cannotLoginErrorHadnler = (req, res, next) => {
+    // this is called when all login method is somehow failed without invoking 'return next(<any Error>)'
+    const err = res.locals.err != null ? res.locals.err : Error('message.sign_in_failure');
+    return next(err);
+  };
+
   /**
   /**
    * middleware for login failure
    * middleware for login failure
    * @param {*} req
    * @param {*} req
    * @param {*} res
    * @param {*} res
    */
    */
-  const loginFailure = (req, res) => {
-    return loginFailureHandler(req, res, req.t('message.sign_in_failure'));
+  const loginFailure = (error, req, res, next) => {
+
+    const parameters = { action: SupportedAction.ACTION_USER_LOGIN_FAILURE };
+    activityEvent.emit('update', res.locals.activity._id, parameters);
+
+    return res.apiv3Err(error, error.code);
   };
   };
 
 
   /**
   /**
@@ -95,13 +175,11 @@ module.exports = function(crowi, app) {
   const loginWithLdap = async(req, res, next) => {
   const loginWithLdap = async(req, res, next) => {
     if (!passportService.isLdapStrategySetup) {
     if (!passportService.isLdapStrategySetup) {
       debug('LdapStrategy has not been set up');
       debug('LdapStrategy has not been set up');
-      return next();
+      return res.apiv3Err('message.strategy_has_not_been_set_up.LdapStrategy', 405);
     }
     }
 
 
     if (!req.form.isValid) {
     if (!req.form.isValid) {
-      debug('invalid form');
-      return res.render('login', {
-      });
+      return next(req.form.errors);
     }
     }
 
 
     const providerId = 'ldap';
     const providerId = 'ldap';
@@ -113,12 +191,12 @@ module.exports = function(crowi, app) {
     }
     }
     catch (err) {
     catch (err) {
       debug(err.message);
       debug(err.message);
-      return next();
+      return next(err);
     }
     }
 
 
     // check groups for LDAP
     // check groups for LDAP
     if (!isValidLdapUserByGroupFilter(ldapAccountInfo)) {
     if (!isValidLdapUserByGroupFilter(ldapAccountInfo)) {
-      return next();
+      return next(ErrorV3('message.ldap_user_not_valid', 400));
     }
     }
 
 
     /*
     /*
@@ -141,16 +219,27 @@ module.exports = function(crowi, app) {
       email: mailToBeRegistered,
       email: mailToBeRegistered,
     };
     };
 
 
-    const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
-    if (!externalAccount) {
-      return next();
+    let externalAccount;
+    try {
+      externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
+    }
+    catch (error) {
+      return next(error);
+    }
+
+    // just in case the returned value is null or undefined
+    if (externalAccount == null) {
+      return next(Error('message.external_account_not_exist'));
     }
     }
 
 
     const user = await externalAccount.getPopulatedUser();
     const user = await externalAccount.getPopulatedUser();
 
 
     // login
     // login
     await req.logIn(user, (err) => {
     await req.logIn(user, (err) => {
-      if (err) { debug(err.message); return next() }
+      if (err) {
+        debug(err.message);
+        return next(err);
+      }
 
 
       return loginSuccessHandler(req, res, user, SupportedAction.ACTION_USER_LOGIN_WITH_LDAP);
       return loginSuccessHandler(req, res, user, SupportedAction.ACTION_USER_LOGIN_WITH_LDAP);
     });
     });
@@ -221,13 +310,11 @@ module.exports = function(crowi, app) {
   const loginWithLocal = (req, res, next) => {
   const loginWithLocal = (req, res, next) => {
     if (!passportService.isLocalStrategySetup) {
     if (!passportService.isLocalStrategySetup) {
       debug('LocalStrategy has not been set up');
       debug('LocalStrategy has not been set up');
-      req.flash('warningMessage', req.t('message.strategy_has_not_been_set_up', { strategy: 'LocalStrategy' }));
-      return next();
+      return res.apiv3Err('message.strategy_has_not_been_set_up.LocalStrategy', 405);
     }
     }
 
 
     if (!req.form.isValid) {
     if (!req.form.isValid) {
-      return res.render('login', {
-      });
+      return next(req.form.errors);
     }
     }
 
 
     passport.authenticate('local', (err, user, info) => {
     passport.authenticate('local', (err, user, info) => {
@@ -237,12 +324,16 @@ module.exports = function(crowi, app) {
 
 
       if (err) { // DB Error
       if (err) { // DB Error
         logger.error('Database Server Error: ', err);
         logger.error('Database Server Error: ', err);
-        req.flash('warningMessage', req.t('message.database_error'));
-        return next(); // pass and the flash message is displayed when all of authentications are failed.
+        return next(err);
+      }
+      if (!user) {
+        return next();
       }
       }
-      if (!user) { return next() }
       req.logIn(user, (err) => {
       req.logIn(user, (err) => {
-        if (err) { debug(err.message); return next() }
+        if (err) {
+          debug(err.message);
+          return next(err);
+        }
 
 
         return loginSuccessHandler(req, res, user, SupportedAction.ACTION_USER_LOGIN_WITH_LOCAL);
         return loginSuccessHandler(req, res, user, SupportedAction.ACTION_USER_LOGIN_WITH_LOCAL);
       });
       });
@@ -560,76 +651,8 @@ module.exports = function(crowi, app) {
     });
     });
   };
   };
 
 
-  const promisifiedPassportAuthentication = (strategyName, req, res) => {
-    return new Promise((resolve, reject) => {
-      passport.authenticate(strategyName, (err, response, info) => {
-        if (res.headersSent) { // dirty hack -- 2017.09.25
-          return; //              cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
-        }
-
-        logger.debug(`--- authenticate with ${strategyName} strategy ---`);
-
-        if (err) {
-          logger.error(`'${strategyName}' passport authentication error: `, err);
-          reject(err);
-        }
-
-        logger.debug('response', response);
-        logger.debug('info', info);
-
-        // authentication failure
-        if (!response) {
-          reject(response);
-        }
-
-        resolve(response);
-      })(req, res);
-    });
-  };
-
-  const getOrCreateUser = async(req, res, userInfo, providerId) => {
-    // get option
-    const isSameUsernameTreatedAsIdenticalUser = crowi.passportService.isSameUsernameTreatedAsIdenticalUser(providerId);
-    const isSameEmailTreatedAsIdenticalUser = crowi.passportService.isSameEmailTreatedAsIdenticalUser(providerId);
-
-    try {
-      // find or register(create) user
-      const externalAccount = await ExternalAccount.findOrRegister(
-        providerId,
-        userInfo.id,
-        userInfo.username,
-        userInfo.name,
-        userInfo.email,
-        isSameUsernameTreatedAsIdenticalUser,
-        isSameEmailTreatedAsIdenticalUser,
-      );
-      return externalAccount;
-    }
-    catch (err) {
-      /* eslint-disable no-else-return */
-      if (err instanceof NullUsernameToBeRegisteredError) {
-        req.flash('warningMessage', req.t(`message.${err.message}`));
-        return;
-      }
-      else if (err.name === 'DuplicatedUsernameException') {
-        if (isSameEmailTreatedAsIdenticalUser || isSameUsernameTreatedAsIdenticalUser) {
-          // associate to existing user
-          debug(`ExternalAccount '${userInfo.username}' will be created and bound to the exisiting User account`);
-          return ExternalAccount.associate(providerId, userInfo.id, err.user);
-        }
-
-        req.flash('provider-DuplicatedUsernameException', providerId);
-        return;
-      }
-      else if (err.name === 'UserUpperLimitException') {
-        req.flash('warningMessage', req.t('message.maximum_number_of_users'));
-        return;
-      }
-      /* eslint-enable no-else-return */
-    }
-  };
-
   return {
   return {
+    cannotLoginErrorHadnler,
     loginFailure,
     loginFailure,
     loginWithLdap,
     loginWithLdap,
     testLdapCredentials,
     testLdapCredentials,

+ 1 - 9
packages/app/src/server/routes/login.js

@@ -102,14 +102,6 @@ module.exports = function(crowi, app) {
     next();
     next();
   };
   };
 
 
-  actions.login = function(req, res) {
-    if (req.form) {
-      debug(req.form.errors);
-    }
-
-    return res.render('login', {});
-  };
-
   actions.register = function(req, res) {
   actions.register = function(req, res) {
     if (req.user != null) {
     if (req.user != null) {
       return res.apiv3Err('user_already_logged_in', 403);
       return res.apiv3Err('user_already_logged_in', 403);
@@ -122,7 +114,7 @@ module.exports = function(crowi, app) {
 
 
     if (!req.form.isValid) {
     if (!req.form.isValid) {
       const errors = req.form.errors;
       const errors = req.form.errors;
-      return res.apiv3Err(errors, 401);
+      return res.apiv3Err(errors, 400);
     }
     }
 
 
     const registerForm = req.form.registerForm || {};
     const registerForm = req.form.registerForm || {};

+ 1 - 1
packages/app/src/server/service/installer.ts

@@ -109,7 +109,7 @@ export class InstallerService {
     return configManager.updateConfigsInTheSameNamespace('crowi', initialConfig, true);
     return configManager.updateConfigsInTheSameNamespace('crowi', initialConfig, true);
   }
   }
 
 
-  async install(firstAdminUserToSave: IUser, globalLang: Lang, options?: AutoInstallOptions): Promise<IUser> {
+  async install(firstAdminUserToSave: Pick<IUser, 'name' | 'username' | 'email' | 'password'>, globalLang: Lang, options?: AutoInstallOptions): Promise<IUser> {
     await this.initDB(globalLang, options);
     await this.initDB(globalLang, options);
 
 
     // TODO typescriptize models/user.js and remove eslint-disable-next-line
     // TODO typescriptize models/user.js and remove eslint-disable-next-line

+ 0 - 9
packages/app/src/styles/_on-edit.scss

@@ -165,15 +165,6 @@ body.on-edit {
     }
     }
   }
   }
 
 
-  .nav:hover {
-    .btn-copy,
-    .btn-edit,
-    .btn-edit-tags {
-      // change button opacity
-      opacity: unset;
-    }
-  }
-
   .grw-copy-dropdown {
   .grw-copy-dropdown {
     .btn-copy {
     .btn-copy {
       padding: 3px !important; // overwrite padding
       padding: 3px !important; // overwrite padding

+ 0 - 20
packages/app/src/styles/atoms/_buttons.scss

@@ -1,26 +1,6 @@
 @use '../bootstrap/init' as bs;
 @use '../bootstrap/init' as bs;
 @use '../mixins';
 @use '../mixins';
 
 
-.btn-copy,
-.btn-edit {
-  &:not(:hover):not(:active) {
-    background-color: transparent !important;
-  }
-  opacity: 0.5;
-}
-
-.btn-edit-tags {
-  opacity: 0.5;
-
-  &.no-tags {
-    opacity: 0.7;
-  }
-}
-
-.rounded-pill-weak {
-  border-radius: 60px;
-}
-
 // fill button style
 // fill button style
 .btn.btn-fill {
 .btn.btn-fill {
   position: relative;
   position: relative;

+ 2 - 0
packages/app/src/styles/atoms/_custom_control.scss

@@ -1,3 +1,5 @@
+@use '../bootstrap/init' as *;
+
 .custom-checkbox .custom-control-label::before {
 .custom-checkbox .custom-control-label::before {
   border-radius: $border-radius !important;
   border-radius: $border-radius !important;
 }
 }

+ 0 - 13
packages/app/src/styles/atoms/_nav.scss

@@ -1,13 +0,0 @@
-.nav-tabs .grw-main-nav-item-left {
-  width: $grw-nav-main-left-tab-width;
-  text-align: center;
-
-  @include media-breakpoint-down(sm) {
-    width: $grw-nav-main-left-tab-width-mobile;
-  }
-
-  .nav-link {
-    padding-right: 0;
-    padding-left: 0;
-  }
-}

+ 0 - 4
packages/app/src/styles/atoms/_pre.scss

@@ -1,4 +0,0 @@
-pre {
-  padding: 0.5em;
-  border-radius: $border-radius;
-}

+ 2 - 5
packages/app/src/styles/style-next.scss

@@ -27,11 +27,8 @@
 
 
 // atoms
 // atoms
 @import 'atoms/buttons';
 @import 'atoms/buttons';
-// @import 'atoms/code';
-// @import 'atoms/nav';
-// @import 'atoms/pre';
-// @import 'atoms/spinners';
-// @import 'atoms/custom_control';
+@import 'atoms/spinners';
+@import 'atoms/custom_control';
 
 
 // // molecules
 // // molecules
 // @import 'molecules/copy-dropdown';
 // @import 'molecules/copy-dropdown';