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

Merge branch 'master' into support/apply-bootstrap4

# Conflicts:
#	src/client/js/components/Admin/Customize/CustomizeFunctionSetting.jsx
#	src/client/js/components/PageComment/Comment.jsx
#	src/client/js/components/PageComment/CommentEditor.jsx
#	src/client/styles/scss/_comment.scss
#	src/server/views/layout/layout.html
#	src/server/views/widget/not_found_tabs.html
#	src/server/views/widget/page_tabs.html
#	src/server/views/widget/page_tabs_kibela.html
#	yarn.lock
itizawa 6 лет назад
Родитель
Сommit
b3d6ebb015
52 измененных файлов с 1139 добавлено и 536 удалено
  1. 17 1
      CHANGES.md
  2. 1 0
      config/logger/config.dev.js
  3. 6 6
      package.json
  4. 3 1
      resource/locales/en-US/admin/admin.json
  5. 1 0
      resource/locales/en-US/translation.json
  6. 3 1
      resource/locales/ja/admin/admin.json
  7. 1 0
      resource/locales/ja/translation.json
  8. 2 0
      src/client/js/bootstrap.jsx
  9. 15 0
      src/client/js/components/Admin/Customize/CustomizeFunctionSetting.jsx
  10. 2 2
      src/client/js/components/Admin/Users/RemoveAdminButton.jsx
  11. 2 2
      src/client/js/components/Admin/Users/StatusSuspendedButton.jsx
  12. 1 1
      src/client/js/components/BookmarkButton.jsx
  13. 1 1
      src/client/js/components/LikeButton.jsx
  14. 60 0
      src/client/js/components/Navbar/PersonalDropdown.jsx
  15. 1 1
      src/client/js/components/PageAttachment.jsx
  16. 52 149
      src/client/js/components/PageComment/Comment.jsx
  17. 24 0
      src/client/js/components/PageComment/CommentControl.jsx
  18. 1 3
      src/client/js/components/PageComment/CommentEditor.jsx
  19. 2 3
      src/client/js/components/PageComment/CommentEditorLazyRenderer.jsx
  20. 123 0
      src/client/js/components/PageComment/ReplayComments.jsx
  21. 8 2
      src/client/js/components/PageComments.jsx
  22. 6 2
      src/client/js/components/PageHistory/RevisionDiff.jsx
  23. 1 1
      src/client/js/components/RecentCreated/RecentCreated.jsx
  24. 7 0
      src/client/js/legacy/crowi.js
  25. 11 0
      src/client/js/services/AdminCustomizeContainer.js
  26. 20 10
      src/client/js/services/AppContainer.js
  27. 20 7
      src/client/styles/scss/_comment.scss
  28. 0 5
      src/client/styles/scss/_comment_growi.scss
  29. 0 5
      src/client/styles/scss/_comment_kibela.scss
  30. 0 5
      src/client/styles/scss/_layout_crowi_sidebar.scss
  31. 1 4
      src/client/styles/scss/_page.scss
  32. 1 1
      src/client/styles/scss/style-app.scss
  33. 5 3
      src/linter-checker/test.js
  34. 5 3
      src/linter-checker/test.scss
  35. 4 0
      src/server/crowi/express-init.js
  36. 3 1
      src/server/middleware/access-token-parser.js
  37. 1 1
      src/server/middleware/login-required.js
  38. 65 0
      src/server/middleware/safe-redirect.js
  39. 2 0
      src/server/models/config.js
  40. 6 0
      src/server/routes/apiv3/customize-setting.js
  41. 2 2
      src/server/routes/index.js
  42. 4 20
      src/server/routes/login-passport.js
  43. 27 46
      src/server/routes/login.js
  44. 4 1
      src/server/routes/logout.js
  45. 1 1
      src/server/views/installer.html
  46. 7 2
      src/server/views/layout/layout.html
  47. 4 1
      src/server/views/widget/not_found_tabs.html
  48. 29 5
      src/server/views/widget/page_tabs.html
  49. 29 5
      src/server/views/widget/page_tabs_kibela.html
  50. 4 4
      src/test/middleware/login-required.test.js
  51. 108 0
      src/test/middleware/safe-redirect.test.js
  52. 436 228
      yarn.lock

+ 17 - 1
CHANGES.md

@@ -1,8 +1,24 @@
 # CHANGES
 # CHANGES
 
 
-## v3.6.8-RC
+## v3.6.9-RC
 
 
+* Improvement: Redirection when login/logout
+* Fix: Client crashed when the first login
+    * Introduced by 3.6.8
+
+## v3.6.8
+
+* Improvement: Show page history side-by-side
 * Improvement: Optimize markdown rendering
 * Improvement: Optimize markdown rendering
+* Improvement: Reactify admin pages (Navigation)
+* Fix: Reply comments collapsed are broken
+    * Introduced by 3.6.7
+* Support: Update libs
+    * cross-env
+    * mkdirp
+    * diff2html
+    * jest
+    * stylelint
 
 
 ## v3.6.7
 ## v3.6.7
 
 

+ 1 - 0
config/logger/config.dev.js

@@ -14,6 +14,7 @@ module.exports = {
   'growi:models:external-account': 'debug',
   'growi:models:external-account': 'debug',
   // 'growi:routes:login': 'debug',
   // 'growi:routes:login': 'debug',
   'growi:routes:login-passport': 'debug',
   'growi:routes:login-passport': 'debug',
+  'growi:middleware:safe-redirect': 'debug',
   'growi:service:PassportService': 'debug',
   'growi:service:PassportService': 'debug',
   // 'growi:service:ConfigManager': 'debug',
   // 'growi:service:ConfigManager': 'debug',
   'growi:lib:search': 'debug',
   'growi:lib:search': 'debug',

+ 6 - 6
package.json

@@ -1,6 +1,6 @@
 {
 {
   "name": "growi",
   "name": "growi",
-  "version": "3.6.8-RC",
+  "version": "3.6.9-RC",
   "description": "Team collaboration software using markdown",
   "description": "Team collaboration software using markdown",
   "tags": [
   "tags": [
     "wiki",
     "wiki",
@@ -85,7 +85,7 @@
     "connect-mongo": "^3.0.0",
     "connect-mongo": "^3.0.0",
     "connect-redis": "^3.3.0",
     "connect-redis": "^3.3.0",
     "cookie-parser": "^1.4.3",
     "cookie-parser": "^1.4.3",
-    "cross-env": "^6.0.3",
+    "cross-env": "^7.0.0",
     "csrf": "^3.1.0",
     "csrf": "^3.1.0",
     "date-fns": "^2.0.0",
     "date-fns": "^2.0.0",
     "diff": "^4.0.1",
     "diff": "^4.0.1",
@@ -112,7 +112,7 @@
     "md5": "^2.2.1",
     "md5": "^2.2.1",
     "method-override": "^3.0.0",
     "method-override": "^3.0.0",
     "migrate-mongo": "^7.0.1",
     "migrate-mongo": "^7.0.1",
-    "mkdirp": "~0.5.1",
+    "mkdirp": "^1.0.3",
     "module-alias": "^2.0.6",
     "module-alias": "^2.0.6",
     "mongoose": "5.4.4",
     "mongoose": "5.4.4",
     "mongoose-gridfs": "^1.2.2",
     "mongoose-gridfs": "^1.2.2",
@@ -172,7 +172,7 @@
     "core-js": "=2.6.9",
     "core-js": "=2.6.9",
     "css-loader": "^3.0.0",
     "css-loader": "^3.0.0",
     "csv-to-markdown-table": "^1.0.1",
     "csv-to-markdown-table": "^1.0.1",
-    "diff2html": "^2.3.3",
+    "diff2html": "^3.1.2",
     "eazy-logger": "^3.0.2",
     "eazy-logger": "^3.0.2",
     "eslint": "^6.0.1",
     "eslint": "^6.0.1",
     "eslint-config-weseek": "^1.0.3",
     "eslint-config-weseek": "^1.0.3",
@@ -184,7 +184,7 @@
     "hard-source-webpack-plugin": "^0.13.1",
     "hard-source-webpack-plugin": "^0.13.1",
     "i18next-browser-languagedetector": "^4.0.1",
     "i18next-browser-languagedetector": "^4.0.1",
     "imports-loader": "^0.8.0",
     "imports-loader": "^0.8.0",
-    "jest": "^24.8.0",
+    "jest": "^25.1.0",
     "jquery-slimscroll": "^1.3.8",
     "jquery-slimscroll": "^1.3.8",
     "jquery-ui": "^1.12.1",
     "jquery-ui": "^1.12.1",
     "jquery.cookie": "~1.4.1",
     "jquery.cookie": "~1.4.1",
@@ -230,7 +230,7 @@
     "simple-load-script": "^1.0.2",
     "simple-load-script": "^1.0.2",
     "socket.io-client": "^2.0.3",
     "socket.io-client": "^2.0.3",
     "style-loader": "^1.0.0",
     "style-loader": "^1.0.0",
-    "stylelint": "^12.0.1",
+    "stylelint": "^13.2.0",
     "stylelint-config-recess-order": "^2.0.1",
     "stylelint-config-recess-order": "^2.0.1",
     "swagger-jsdoc": "^3.4.0",
     "swagger-jsdoc": "^3.4.0",
     "swagger2openapi": "^5.3.1",
     "swagger2openapi": "^5.3.1",

+ 3 - 1
resource/locales/en-US/admin/admin.json

@@ -126,7 +126,9 @@
       "recent_created__n_draft_num_desc": "Number of Recently Created Pages & Drafts Displayed",
       "recent_created__n_draft_num_desc": "Number of Recently Created Pages & Drafts Displayed",
       "recently_created_n_draft_num_desc": "Number of recently created pages and drafts displayed on user page",
       "recently_created_n_draft_num_desc": "Number of recently created pages and drafts displayed on user page",
       "stale_notification": "Display Notification on Stale Pages",
       "stale_notification": "Display Notification on Stale Pages",
-      "stale_notification_desc": "Displays the notification to pages more than 1 year since the last update."
+      "stale_notification_desc": "Displays the notification to pages more than 1 year since the last update.",
+      "show_all_reply_comments": "Show all reply comments",
+      "show_all_reply_comments_desc": "When the setting value is off, comments other than the latest two are omitted."
     },
     },
     "code_highlight": "Code Highlight",
     "code_highlight": "Code Highlight",
     "nocdn_desc": "This function is disabled when the environment variable <code>NO_CDN=true</code>.<br>Github style has been forcibly applied.",
     "nocdn_desc": "This function is disabled when the environment variable <code>NO_CDN=true</code>.<br>Github style has been forcibly applied.",

+ 1 - 0
resource/locales/en-US/translation.json

@@ -46,6 +46,7 @@
   "Timeline View": "Timeline",
   "Timeline View": "Timeline",
   "History": "History",
   "History": "History",
   "Presentation Mode": "Presentation",
   "Presentation Mode": "Presentation",
+  "Not available for guest": "Not available for guest",
   "username": "Username",
   "username": "Username",
   "Created": "Created",
   "Created": "Created",
   "Last updated": "Updated",
   "Last updated": "Updated",

+ 3 - 1
resource/locales/ja/admin/admin.json

@@ -126,7 +126,9 @@
       "recent_created__n_draft_num_desc": "最近作成したページと下書きの表示数",
       "recent_created__n_draft_num_desc": "最近作成したページと下書きの表示数",
       "recently_created_n_draft_num_desc": "ホーム画面の Recently Created での、1ページの表示数を設定します。",
       "recently_created_n_draft_num_desc": "ホーム画面の Recently Created での、1ページの表示数を設定します。",
       "stale_notification": "古いページに通知を表示する",
       "stale_notification": "古いページに通知を表示する",
-      "stale_notification_desc": "最後の更新から1年を超えるページへの通知を表示します。"
+      "stale_notification_desc": "最後の更新から1年を超えるページへの通知を表示します。",
+      "show_all_reply_comments": "返信コメントを全て表示する",
+      "show_all_reply_comments_desc": "OFFの場合、最新2件のコメント以外が省略されます。"
     },
     },
     "code_highlight": "コードハイライト",
     "code_highlight": "コードハイライト",
     "nocdn_desc": "この機能は、環境変数 <code>NO_CDN=true</code> の時は無効化されます。<br>GitHub スタイルが適用されています。",
     "nocdn_desc": "この機能は、環境変数 <code>NO_CDN=true</code> の時は無効化されます。<br>GitHub スタイルが適用されています。",

+ 1 - 0
resource/locales/ja/translation.json

@@ -46,6 +46,7 @@
   "Timeline View": "タイムライン表示",
   "Timeline View": "タイムライン表示",
   "History": "更新履歴",
   "History": "更新履歴",
   "Presentation Mode": "プレゼンテーション",
   "Presentation Mode": "プレゼンテーション",
+  "Not available for guest": "ゲストユーザーは利用できません",
   "username": "ユーザー名",
   "username": "ユーザー名",
   "Created": "作成日",
   "Created": "作成日",
   "Last updated": "最終更新",
   "Last updated": "最終更新",

+ 2 - 0
src/client/js/bootstrap.jsx

@@ -4,6 +4,7 @@ import loggerFactory from '@alias/logger';
 import Xss from '@commons/service/xss';
 import Xss from '@commons/service/xss';
 
 
 import HeaderSearchBox from './components/HeaderSearchBox';
 import HeaderSearchBox from './components/HeaderSearchBox';
+import PersonalDropdown from './components/Navbar/PersonalDropdown';
 import StaffCredit from './components/StaffCredit/StaffCredit';
 import StaffCredit from './components/StaffCredit/StaffCredit';
 
 
 import AppContainer from './services/AppContainer';
 import AppContainer from './services/AppContainer';
@@ -37,6 +38,7 @@ appContainer.injectToWindow();
 const componentMappings = {
 const componentMappings = {
   'search-top': <HeaderSearchBox />,
   'search-top': <HeaderSearchBox />,
   'search-sidebar': <HeaderSearchBox crowi={appContainer} />,
   'search-sidebar': <HeaderSearchBox crowi={appContainer} />,
+  'personal-dropdown': <PersonalDropdown />,
 
 
   'staff-credit': <StaffCredit />,
   'staff-credit': <StaffCredit />,
 };
 };

+ 15 - 0
src/client/js/components/Admin/Customize/CustomizeFunctionSetting.jsx

@@ -150,6 +150,21 @@ class CustomizeBehaviorSetting extends React.Component {
               </div>
               </div>
             </div>
             </div>
 
 
+            <div className="form-group row">
+              <div className="col-xs-offset-3 col-xs-6 text-left">
+                <CustomizeFunctionOption
+                  optionId="isAllReplyShown"
+                  label={t('admin:customize_setting.function_options.show_all_reply_comments')}
+                  isChecked={adminCustomizeContainer.state.isAllReplyShown || false}
+                  onChecked={() => { adminCustomizeContainer.switchIsAllReplyShown() }}
+                >
+                  <p className="help-block">
+                    {t('admin:customize_setting.function_options.show_all_reply_comments_desc')}
+                  </p>
+                </CustomizeFunctionOption>
+              </div>
+            </div>
+
             <AdminUpdateButtonRow onClick={this.onClickSubmit} disabled={adminCustomizeContainer.state.retrieveError != null} />
             <AdminUpdateButtonRow onClick={this.onClickSubmit} disabled={adminCustomizeContainer.state.retrieveError != null} />
           </div>
           </div>
         </div>
         </div>

+ 2 - 2
src/client/js/components/Admin/Users/RemoveAdminButton.jsx

@@ -51,11 +51,11 @@ class RemoveAdminButton extends React.Component {
 
 
   render() {
   render() {
     const { user } = this.props;
     const { user } = this.props;
-    const me = this.props.appContainer.me;
+    const { currentUsername } = this.props.appContainer;
 
 
     return (
     return (
       <Fragment>
       <Fragment>
-        {user.username !== me ? this.renderRemoveAdminBtn()
+        {user.username !== currentUsername ? this.renderRemoveAdminBtn()
           : this.renderRemoveAdminAlert()}
           : this.renderRemoveAdminAlert()}
       </Fragment>
       </Fragment>
     );
     );

+ 2 - 2
src/client/js/components/Admin/Users/StatusSuspendedButton.jsx

@@ -50,11 +50,11 @@ class StatusSuspendedButton extends React.Component {
 
 
   render() {
   render() {
     const { user } = this.props;
     const { user } = this.props;
-    const me = this.props.appContainer.me;
+    const { currentUsername } = this.props.appContainer;
 
 
     return (
     return (
       <Fragment>
       <Fragment>
-        {user.username !== me ? this.renderSuspendedBtn()
+        {user.username !== currentUsername ? this.renderSuspendedBtn()
           : this.renderSuspendedAlert()}
           : this.renderSuspendedAlert()}
       </Fragment>
       </Fragment>
     );
     );

+ 1 - 1
src/client/js/components/BookmarkButton.jsx

@@ -56,7 +56,7 @@ export default class BookmarkButton extends React.Component {
   }
   }
 
 
   isUserLoggedIn() {
   isUserLoggedIn() {
-    return this.props.crowi.me != null;
+    return this.props.crowi.currentUserId != null;
   }
   }
 
 
   render() {
   render() {

+ 1 - 1
src/client/js/components/LikeButton.jsx

@@ -37,7 +37,7 @@ class LikeButton extends React.Component {
   }
   }
 
 
   isUserLoggedIn() {
   isUserLoggedIn() {
-    return this.props.appContainer.me != null;
+    return this.props.appContainer.currentUserId != null;
   }
   }
 
 
   render() {
   render() {

+ 60 - 0
src/client/js/components/Navbar/PersonalDropdown.jsx

@@ -0,0 +1,60 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import { withTranslation } from 'react-i18next';
+
+import { createSubscribedElement } from '../UnstatedUtils';
+import AppContainer from '../../services/AppContainer';
+
+import UserPicture from '../User/UserPicture';
+
+const PersonalDropdown = (props) => {
+
+  const { t, appContainer } = props;
+  const user = appContainer.currentUser || {};
+
+  const logoutHandler = () => {
+    const { interceptorManager } = appContainer;
+
+    const context = {
+      user,
+      currentPagePath: decodeURIComponent(window.location.pathname),
+    };
+    interceptorManager.process('logout', context);
+
+    window.location.href = '/logout';
+  };
+
+  return (
+    <>
+      <a className="dropdown-toggle waves-effect waves-light" data-toggle="dropdown">
+        <UserPicture user={user} withoutLink />&nbsp;{user.name}
+      </a>
+      <ul className="dropdown-menu dropdown-menu-right">
+        <li><a href={`/user/${user.username}`}><i className="icon-fw icon-home"></i>{ t('Home') }</a></li>
+        <li><a href="/me"><i className="icon-fw icon-wrench"></i>{ t('User Settings') }</a></li>
+        <li role="separator" className="divider"></li>
+        <li><a href={`/user/${user.username}#user-draft-list`}><i className="icon-fw icon-docs"></i>{ t('List Drafts') }</a></li>
+        <li><a href="/trash"><i className="icon-fw icon-trash"></i>{ t('Deleted Pages') }</a></li>
+        <li role="separator" className="divider"></li>
+        <li><a role="button" onClick={logoutHandler}><i className="icon-fw icon-power"></i>{ t('Sign out') }</a></li>
+      </ul>
+    </>
+  );
+
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const PersonalDropdownWrapper = (props) => {
+  return createSubscribedElement(PersonalDropdown, props, [AppContainer]);
+};
+
+
+PersonalDropdown.propTypes = {
+  t: PropTypes.func.isRequired, //  i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+};
+
+export default withTranslation()(PersonalDropdownWrapper);

+ 1 - 1
src/client/js/components/PageAttachment.jsx

@@ -89,7 +89,7 @@ class PageAttachment extends React.Component {
   }
   }
 
 
   isUserLoggedIn() {
   isUserLoggedIn() {
-    return this.props.appContainer.me != null;
+    return this.props.appContainer.currentUser != null;
   }
   }
 
 
   render() {
   render() {

+ 52 - 149
src/client/js/components/PageComment/Comment.jsx

@@ -3,11 +3,7 @@ import PropTypes from 'prop-types';
 
 
 import { format, formatDistanceStrict } from 'date-fns';
 import { format, formatDistanceStrict } from 'date-fns';
 
 
-import {
-  Button,
-  Collapse,
-  UncontrolledTooltip,
-} from 'reactstrap';
+import { UncontrolledTooltip } from 'reactstrap';
 
 
 import AppContainer from '../../services/AppContainer';
 import AppContainer from '../../services/AppContainer';
 import PageContainer from '../../services/PageContainer';
 import PageContainer from '../../services/PageContainer';
@@ -17,6 +13,7 @@ import RevisionBody from '../Page/RevisionBody';
 import UserPicture from '../User/UserPicture';
 import UserPicture from '../User/UserPicture';
 import Username from '../User/Username';
 import Username from '../User/Username';
 import CommentEditor from './CommentEditor';
 import CommentEditor from './CommentEditor';
+import CommentControl from './CommentControl';
 
 
 /**
 /**
  *
  *
@@ -26,15 +23,14 @@ import CommentEditor from './CommentEditor';
  * @class Comment
  * @class Comment
  * @extends {React.Component}
  * @extends {React.Component}
  */
  */
-class Comment extends React.Component {
+class Comment extends React.PureComponent {
 
 
   constructor(props) {
   constructor(props) {
     super(props);
     super(props);
 
 
     this.state = {
     this.state = {
       html: '',
       html: '',
-      isOlderRepliesShown: false,
-      showReEditorIds: new Set(),
+      isReEdit: false,
     };
     };
 
 
     this.growiRenderer = this.props.appContainer.getRenderer('comment');
     this.growiRenderer = this.props.appContainer.getRenderer('comment');
@@ -43,23 +39,39 @@ class Comment extends React.Component {
     this.isCurrentRevision = this.isCurrentRevision.bind(this);
     this.isCurrentRevision = this.isCurrentRevision.bind(this);
     this.getRootClassName = this.getRootClassName.bind(this);
     this.getRootClassName = this.getRootClassName.bind(this);
     this.getRevisionLabelClassName = this.getRevisionLabelClassName.bind(this);
     this.getRevisionLabelClassName = this.getRevisionLabelClassName.bind(this);
+    this.editBtnClickedHandler = this.editBtnClickedHandler.bind(this);
     this.deleteBtnClickedHandler = this.deleteBtnClickedHandler.bind(this);
     this.deleteBtnClickedHandler = this.deleteBtnClickedHandler.bind(this);
     this.renderText = this.renderText.bind(this);
     this.renderText = this.renderText.bind(this);
     this.renderHtml = this.renderHtml.bind(this);
     this.renderHtml = this.renderHtml.bind(this);
     this.commentButtonClickedHandler = this.commentButtonClickedHandler.bind(this);
     this.commentButtonClickedHandler = this.commentButtonClickedHandler.bind(this);
   }
   }
 
 
-  componentWillMount() {
-    this.renderHtml(this.props.comment.comment);
+
+  initCurrentRenderingContext() {
+    this.currentRenderingContext = {
+      markdown: this.props.comment.comment,
+    };
   }
   }
 
 
-  componentWillReceiveProps(nextProps) {
-    this.renderHtml(nextProps.comment.comment);
+  componentDidMount() {
+    this.initCurrentRenderingContext();
+    this.renderHtml();
   }
   }
 
 
-  // not used
-  setMarkdown(markdown) {
-    this.renderHtml(markdown);
+  componentDidUpdate(prevProps) {
+    const { comment: prevComment } = prevProps;
+    const { comment } = this.props;
+
+    // render only when props.markdown is updated
+    if (comment !== prevComment) {
+      this.initCurrentRenderingContext();
+      this.renderHtml();
+      return;
+    }
+
+    const { interceptorManager } = this.props.appContainer;
+
+    interceptorManager.process('postRenderCommentHtml', this.currentRenderingContext);
   }
   }
 
 
   checkPermissionToControlComment() {
   checkPermissionToControlComment() {
@@ -67,7 +79,7 @@ class Comment extends React.Component {
   }
   }
 
 
   isCurrentUserEqualsToAuthor() {
   isCurrentUserEqualsToAuthor() {
-    return this.props.comment.creator.username === this.props.appContainer.me;
+    return this.props.comment.creator.username === this.props.appContainer.currentUsername;
   }
   }
 
 
   isCurrentRevision() {
   isCurrentRevision() {
@@ -100,18 +112,12 @@ class Comment extends React.Component {
       this.isCurrentRevision() ? 'label-primary' : 'label-default'}`;
       this.isCurrentRevision() ? 'label-primary' : 'label-default'}`;
   }
   }
 
 
-  editBtnClickedHandler(commentId) {
-    const ids = this.state.showReEditorIds.add(commentId);
-    this.setState({ showReEditorIds: ids });
+  editBtnClickedHandler() {
+    this.setState({ isReEdit: !this.state.isReEdit });
   }
   }
 
 
-  commentButtonClickedHandler(commentId) {
-    this.setState((prevState) => {
-      prevState.showReEditorIds.delete(commentId);
-      return {
-        showReEditorIds: prevState.showReEditorIds,
-      };
-    });
+  commentButtonClickedHandler() {
+    this.editBtnClickedHandler();
   }
   }
 
 
   deleteBtnClickedHandler() {
   deleteBtnClickedHandler() {
@@ -135,120 +141,23 @@ class Comment extends React.Component {
     );
     );
   }
   }
 
 
-  toggleOlderReplies() {
-    this.setState((prevState) => {
-      return {
-        showOlderReplies: !prevState.showOlderReplies,
-      };
-    });
-  }
-
-  renderHtml(markdown) {
-    const context = {
-      markdown,
-    };
-
-    const growiRenderer = this.props.growiRenderer;
-    const interceptorManager = this.props.appContainer.interceptorManager;
-    interceptorManager.process('preRenderComment', context)
-      .then(() => { return interceptorManager.process('prePreProcess', context) })
-      .then(() => {
-        context.markdown = growiRenderer.preProcess(context.markdown);
-      })
-      .then(() => { return interceptorManager.process('postPreProcess', context) })
-      .then(() => {
-        const parsedHTML = growiRenderer.process(context.markdown);
-        context.parsedHTML = parsedHTML;
-      })
-      .then(() => { return interceptorManager.process('prePostProcess', context) })
-      .then(() => {
-        context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
-      })
-      .then(() => { return interceptorManager.process('postPostProcess', context) })
-      .then(() => { return interceptorManager.process('preRenderCommentHtml', context) })
-      .then(() => {
-        this.setState({ html: context.parsedHTML });
-      })
-      // process interceptors for post rendering
-      .then(() => { return interceptorManager.process('postRenderCommentHtml', context) });
+  async renderHtml() {
 
 
-  }
+    const { growiRenderer, appContainer } = this.props;
+    const { interceptorManager } = appContainer;
+    const context = this.currentRenderingContext;
 
 
-  renderReply(reply) {
-    return (
-      <div key={reply._id} className="page-comment-reply">
-        <CommentWrapper
-          comment={reply}
-          deleteBtnClicked={this.props.deleteBtnClicked}
-          growiRenderer={this.props.growiRenderer}
-        />
-      </div>
-    );
-  }
-
-  renderReplies() {
-    const layoutType = this.props.appContainer.getConfig().layoutType;
-    const isBaloonStyle = layoutType.match(/crowi-plus|growi|kibela/);
-
-    let replyList = this.props.replyList;
-    if (!isBaloonStyle) {
-      replyList = replyList.slice().reverse();
-    }
-
-    const areThereHiddenReplies = replyList.length > 2;
-
-    const { isOlderRepliesShown } = this.state;
-    const toggleButtonIconName = isOlderRepliesShown ? 'icon-arrow-up' : 'icon-options-vertical';
-    const toggleButtonIcon = <i className={`icon-fw ${toggleButtonIconName}`}></i>;
-    const toggleButtonLabel = isOlderRepliesShown ? '' : 'more';
-    const toggleButton = (
-      <Button
-        color="link"
-        className="page-comments-list-toggle-older"
-        onClick={() => { this.setState({ isOlderRepliesShown: !isOlderRepliesShown }) }}
-      >
-        {toggleButtonIcon} {toggleButtonLabel}
-      </Button>
-    );
-
-    const shownReplies = replyList.slice(replyList.length - 2, replyList.length);
-    const hiddenReplies = replyList.slice(0, replyList.length - 2);
-
-    const hiddenElements = hiddenReplies.map((reply) => {
-      return this.renderReply(reply);
-    });
-
-    const shownElements = shownReplies.map((reply) => {
-      return this.renderReply(reply);
-    });
-
-    return (
-      <React.Fragment>
-        { areThereHiddenReplies && (
-          <div className="page-comments-hidden-replies">
-            <Collapse isOpen={this.state.isOlderRepliesShown}>
-              <div>{hiddenElements}</div>
-            </Collapse>
-            <div className="text-center">{toggleButton}</div>
-          </div>
-        ) }
-
-        {shownElements}
-      </React.Fragment>
-    );
-  }
-
-  renderCommentControl(comment) {
-    return (
-      <div className="page-comment-control">
-        <button type="button" className="btn btn-link p-2" onClick={() => { this.editBtnClickedHandler(comment._id) }}>
-          <i className="ti-pencil"></i>
-        </button>
-        <button type="button" className="btn btn-link p-2 mr-2" onClick={this.deleteBtnClickedHandler}>
-          <i className="ti-close"></i>
-        </button>
-      </div>
-    );
+    await interceptorManager.process('preRenderComment', context);
+    await interceptorManager.process('prePreProcess', context);
+    context.markdown = await growiRenderer.preProcess(context.markdown);
+    await interceptorManager.process('postPreProcess', context);
+    context.parsedHTML = await growiRenderer.process(context.markdown);
+    await interceptorManager.process('prePostProcess', context);
+    context.parsedHTML = await growiRenderer.postProcess(context.parsedHTML);
+    await interceptorManager.process('postPostProcess', context);
+    await interceptorManager.process('preRenderCommentHtml', context);
+    this.setState({ html: context.parsedHTML });
+    await interceptorManager.process('postRenderCommentHtml', context);
   }
   }
 
 
   render() {
   render() {
@@ -260,8 +169,6 @@ class Comment extends React.Component {
     const updatedAt = new Date(comment.updatedAt);
     const updatedAt = new Date(comment.updatedAt);
     const isEdited = createdAt < updatedAt;
     const isEdited = createdAt < updatedAt;
 
 
-    const showReEditor = this.state.showReEditorIds.has(commentId);
-
     const rootClassName = this.getRootClassName(comment);
     const rootClassName = this.getRootClassName(comment);
     const commentBody = isMarkdown ? this.renderRevisionBody() : this.renderText(comment.comment);
     const commentBody = isMarkdown ? this.renderRevisionBody() : this.renderText(comment.comment);
     const revHref = `?revision=${comment.revision}`;
     const revHref = `?revision=${comment.revision}`;
@@ -279,7 +186,7 @@ class Comment extends React.Component {
     return (
     return (
       <React.Fragment>
       <React.Fragment>
 
 
-        {showReEditor ? (
+        {this.state.isReEdit ? (
           <CommentEditor
           <CommentEditor
             growiRenderer={this.growiRenderer}
             growiRenderer={this.growiRenderer}
             currentCommentId={commentId}
             currentCommentId={commentId}
@@ -307,12 +214,12 @@ class Comment extends React.Component {
                 ) }
                 ) }
                 <span className="ml-2"><a className={revisionLavelClassName} href={revHref}>{revFirst8Letters}</a></span>
                 <span className="ml-2"><a className={revisionLavelClassName} href={revHref}>{revFirst8Letters}</a></span>
               </div>
               </div>
-              { this.checkPermissionToControlComment() && this.renderCommentControl(comment) }
+              {this.checkPermissionToControlComment()
+                  && <CommentControl onClickDeleteBtn={this.deleteBtnClickedHandler} onClickEditBtn={this.editBtnClickedHandler} />}
             </div>
             </div>
           </div>
           </div>
-        )
-      }
-        {this.renderReplies()}
+          )
+        }
 
 
       </React.Fragment>
       </React.Fragment>
     );
     );
@@ -334,10 +241,6 @@ Comment.propTypes = {
   comment: PropTypes.object.isRequired,
   comment: PropTypes.object.isRequired,
   growiRenderer: PropTypes.object.isRequired,
   growiRenderer: PropTypes.object.isRequired,
   deleteBtnClicked: PropTypes.func.isRequired,
   deleteBtnClicked: PropTypes.func.isRequired,
-  replyList: PropTypes.array,
-};
-Comment.defaultProps = {
-  replyList: [],
 };
 };
 
 
 export default CommentWrapper;
 export default CommentWrapper;

+ 24 - 0
src/client/js/components/PageComment/CommentControl.jsx

@@ -0,0 +1,24 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+
+const CommentControl = (props) => {
+  return (
+    <div className="page-comment-control">
+      <button type="button" className="btn btn-link p-2" onClick={props.onClickEditBtn}>
+        <i className="ti-pencil"></i>
+      </button>
+      <button type="button" className="btn btn-link p-2 mr-2" onClick={props.onClickDeleteBtn}>
+        <i className="ti-close"></i>
+      </button>
+    </div>
+  );
+};
+
+CommentControl.propTypes = {
+
+  onClickEditBtn: PropTypes.func.isRequired,
+  onClickDeleteBtn: PropTypes.func.isRequired,
+};
+
+export default CommentControl;

+ 1 - 3
src/client/js/components/PageComment/CommentEditor.jsx

@@ -216,8 +216,6 @@ class CommentEditor extends React.Component {
     const { appContainer, commentContainer } = this.props;
     const { appContainer, commentContainer } = this.props;
     const { activeTab } = this.state;
     const { activeTab } = this.state;
 
 
-    const username = appContainer.me;
-    const user = appContainer.findUser(username);
     const commentPreview = this.state.isMarkdown ? this.getCommentHtml() : null;
     const commentPreview = this.state.isMarkdown ? this.getCommentHtml() : null;
     const emojiStrategy = appContainer.getEmojiStrategy();
     const emojiStrategy = appContainer.getEmojiStrategy();
 
 
@@ -246,7 +244,7 @@ class CommentEditor extends React.Component {
         <div className="comment-form">
         <div className="comment-form">
           { isBaloonStyle && (
           { isBaloonStyle && (
             <div className="comment-form-user">
             <div className="comment-form-user">
-              <UserPicture user={user} />
+              <UserPicture user={appContainer.currentUser} />
             </div>
             </div>
           ) }
           ) }
           <div className="comment-form-main">
           <div className="comment-form-main">

+ 2 - 3
src/client/js/components/PageComment/CommentEditorLazyRenderer.jsx

@@ -27,9 +27,8 @@ class CommentEditorLazyRenderer extends React.Component {
 
 
   render() {
   render() {
     const { appContainer } = this.props;
     const { appContainer } = this.props;
-    const username = appContainer.me;
-    const isLoggedIn = username != null;
-    const user = appContainer.findUser(username);
+    const user = appContainer.currentUser;
+    const isLoggedIn = user != null;
 
 
     const layoutType = this.props.appContainer.getConfig().layoutType;
     const layoutType = this.props.appContainer.getConfig().layoutType;
     const isBaloonStyle = layoutType.match(/crowi-plus|growi|kibela/);
     const isBaloonStyle = layoutType.match(/crowi-plus|growi|kibela/);

+ 123 - 0
src/client/js/components/PageComment/ReplayComments.jsx

@@ -0,0 +1,123 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import { Button, Collapse } from 'reactstrap';
+
+import AppContainer from '../../services/AppContainer';
+import PageContainer from '../../services/PageContainer';
+
+import Comment from './Comment';
+
+import { createSubscribedElement } from '../UnstatedUtils';
+
+class ReplayComments extends React.PureComponent {
+
+  constructor() {
+    super();
+
+    this.state = {
+      isOlderRepliesShown: false,
+    };
+
+    this.toggleIsOlderRepliesShown = this.toggleIsOlderRepliesShown.bind(this);
+  }
+
+  toggleIsOlderRepliesShown() {
+    this.setState({ isOlderRepliesShown: !this.state.isOlderRepliesShown });
+  }
+
+  renderReply(reply) {
+    return (
+      <div key={reply._id} className="page-comment-reply">
+        <Comment
+          comment={reply}
+          deleteBtnClicked={this.props.deleteBtnClicked}
+          growiRenderer={this.props.growiRenderer}
+        />
+      </div>
+    );
+  }
+
+  render() {
+
+    const layoutType = this.props.appContainer.getConfig().layoutType;
+    const isBaloonStyle = layoutType.match(/crowi-plus|growi|kibela/);
+
+    const isAllReplyShown = this.props.appContainer.getConfig().isAllReplyShown || false;
+
+    let replyList = this.props.replyList;
+    if (!isBaloonStyle) {
+      replyList = replyList.slice().reverse();
+    }
+
+    if (isAllReplyShown) {
+      return (
+        <React.Fragment>
+          {replyList.map((reply) => {
+            return this.renderReply(reply);
+          })}
+        </React.Fragment>
+      );
+    }
+
+    const areThereHiddenReplies = (replyList.length > 2);
+
+    const { isOlderRepliesShown } = this.state;
+    const toggleButtonIconName = isOlderRepliesShown ? 'icon-arrow-up' : 'icon-options-vertical';
+    const toggleButtonIcon = <i className={`icon-fw ${toggleButtonIconName}`}></i>;
+    const toggleButtonLabel = isOlderRepliesShown ? '' : 'more';
+
+    const shownReplies = replyList.slice(replyList.length - 2, replyList.length);
+    const hiddenReplies = replyList.slice(0, replyList.length - 2);
+
+    const hiddenElements = hiddenReplies.map((reply) => {
+      return this.renderReply(reply);
+    });
+
+    const shownElements = shownReplies.map((reply) => {
+      return this.renderReply(reply);
+    });
+
+    return (
+      <React.Fragment>
+        {areThereHiddenReplies && (
+          <div className="page-comments-hidden-replies">
+            <Collapse in={this.state.isOlderRepliesShown}>
+              <div>{hiddenElements}</div>
+            </Collapse>
+            <div className="text-center">
+              <Button
+                bsStyle="link"
+                className="page-comments-list-toggle-older"
+                onClick={this.toggleIsOlderRepliesShown}
+              >
+                {toggleButtonIcon} {toggleButtonLabel}
+              </Button>
+            </div>
+          </div>
+        )}
+        {shownElements}
+
+      </React.Fragment>
+    );
+  }
+
+}
+
+/**
+ * Wrapper component for using unstated
+ */
+const ReplayCommentsWrapper = (props) => {
+  return createSubscribedElement(ReplayComments, props, [AppContainer, PageContainer]);
+};
+
+ReplayComments.propTypes = {
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
+
+  growiRenderer: PropTypes.object.isRequired,
+  deleteBtnClicked: PropTypes.func.isRequired,
+  replyList: PropTypes.array,
+};
+
+export default ReplayCommentsWrapper;

+ 8 - 2
src/client/js/components/PageComments.jsx

@@ -16,6 +16,7 @@ import { createSubscribedElement } from './UnstatedUtils';
 import CommentEditor from './PageComment/CommentEditor';
 import CommentEditor from './PageComment/CommentEditor';
 import Comment from './PageComment/Comment';
 import Comment from './PageComment/Comment';
 import DeleteCommentModal from './PageComment/DeleteCommentModal';
 import DeleteCommentModal from './PageComment/DeleteCommentModal';
+import ReplayComments from './PageComment/ReplayComments';
 
 
 
 
 /**
 /**
@@ -129,7 +130,7 @@ class PageComments extends React.Component {
   renderThread(comment, replies) {
   renderThread(comment, replies) {
     const commentId = comment._id;
     const commentId = comment._id;
     const showEditor = this.state.showEditorIds.has(commentId);
     const showEditor = this.state.showEditorIds.has(commentId);
-    const isLoggedIn = this.props.appContainer.me != null;
+    const isLoggedIn = this.props.appContainer.currentUser != null;
 
 
     let rootClassNames = 'page-comment-thread';
     let rootClassNames = 'page-comment-thread';
     if (replies.length === 0) {
     if (replies.length === 0) {
@@ -140,11 +141,16 @@ class PageComments extends React.Component {
       <div key={commentId} className={`mb-5 ${rootClassNames}`}>
       <div key={commentId} className={`mb-5 ${rootClassNames}`}>
         <Comment
         <Comment
           comment={comment}
           comment={comment}
-          editBtnClicked={this.confirmToEditComment}
           deleteBtnClicked={this.confirmToDeleteComment}
           deleteBtnClicked={this.confirmToDeleteComment}
           growiRenderer={this.growiRenderer}
           growiRenderer={this.growiRenderer}
+        />
+        {replies.length !== 0 && (
+        <ReplayComments
           replyList={replies}
           replyList={replies}
+          deleteBtnClicked={this.confirmToDeleteComment}
+          growiRenderer={this.growiRenderer}
         />
         />
+        )}
         { !showEditor && isLoggedIn && (
         { !showEditor && isLoggedIn && (
           <div className="text-right">
           <div className="text-right">
             <Button
             <Button

+ 6 - 2
src/client/js/components/PageHistory/RevisionDiff.jsx

@@ -2,7 +2,7 @@ import React from 'react';
 import PropTypes from 'prop-types';
 import PropTypes from 'prop-types';
 
 
 import { createPatch } from 'diff';
 import { createPatch } from 'diff';
-import { Diff2Html } from 'diff2html';
+import { html } from 'diff2html';
 
 
 export default class RevisionDiff extends React.Component {
 export default class RevisionDiff extends React.Component {
 
 
@@ -29,8 +29,12 @@ export default class RevisionDiff extends React.Component {
         previousText,
         previousText,
         currentRevision.body,
         currentRevision.body,
       );
       );
+      const option = {
+        drawFileList: false,
+        outputFormat: 'side-by-side',
+      };
 
 
-      diffViewHTML = Diff2Html.getPrettyHtml(patch);
+      diffViewHTML = html(patch, option);
     }
     }
 
 
     const diffView = { __html: diffViewHTML };
     const diffView = { __html: diffViewHTML };

+ 1 - 1
src/client/js/components/RecentCreated/RecentCreated.jsx

@@ -37,7 +37,7 @@ class RecentCreated extends React.Component {
     const { appContainer, pageContainer } = this.props;
     const { appContainer, pageContainer } = this.props;
     const { pageId } = pageContainer.state;
     const { pageId } = pageContainer.state;
 
 
-    const userId = appContainer.me;
+    const userId = appContainer.currentUserId;
     const limit = appContainer.getConfig().recentCreatedLimit;
     const limit = appContainer.getConfig().recentCreatedLimit;
     const offset = (selectPageNumber - 1) * limit;
     const offset = (selectPageNumber - 1) * limit;
 
 

+ 7 - 0
src/client/js/legacy/crowi.js

@@ -595,6 +595,11 @@ $(() => {
 window.addEventListener('load', (e) => {
 window.addEventListener('load', (e) => {
   const { appContainer } = window;
   const { appContainer } = window;
 
 
+  // do nothing if user is guest
+  if (appContainer.currentUser == null) {
+    return;
+  }
+
   // hash on page
   // hash on page
   if (window.location.hash) {
   if (window.location.hash) {
     if ((window.location.hash === '#edit' || window.location.hash === '#edit-form') && $('.tab-pane#edit').length > 0) {
     if ((window.location.hash === '#edit' || window.location.hash === '#edit-form') && $('.tab-pane#edit').length > 0) {
@@ -618,7 +623,9 @@ window.addEventListener('load', (e) => {
       $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
       $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
     }
     }
   }
   }
+});
 
 
+window.addEventListener('load', (e) => {
   const crowi = window.crowi;
   const crowi = window.crowi;
   if (crowi && crowi.users && crowi.users.length !== 0) {
   if (crowi && crowi.users && crowi.users.length !== 0) {
     const totalUsers = crowi.users.length;
     const totalUsers = crowi.users.length;

+ 11 - 0
src/client/js/services/AdminCustomizeContainer.js

@@ -28,6 +28,7 @@ export default class AdminCustomizeContainer extends Container {
       isEnabledAttachTitleHeader: false,
       isEnabledAttachTitleHeader: false,
       currentRecentCreatedLimit: 10,
       currentRecentCreatedLimit: 10,
       isEnabledStaleNotification: false,
       isEnabledStaleNotification: false,
+      isAllReplyShown: false,
       currentHighlightJsStyleId: '',
       currentHighlightJsStyleId: '',
       isHighlightJsStyleBorderEnabled: false,
       isHighlightJsStyleBorderEnabled: false,
       currentCustomizeTitle: '',
       currentCustomizeTitle: '',
@@ -76,6 +77,7 @@ export default class AdminCustomizeContainer extends Container {
         isEnabledAttachTitleHeader: customizeParams.isEnabledAttachTitleHeader,
         isEnabledAttachTitleHeader: customizeParams.isEnabledAttachTitleHeader,
         currentRecentCreatedLimit: customizeParams.recentCreatedLimit,
         currentRecentCreatedLimit: customizeParams.recentCreatedLimit,
         isEnabledStaleNotification: customizeParams.isEnabledStaleNotification,
         isEnabledStaleNotification: customizeParams.isEnabledStaleNotification,
+        isAllReplyShown: customizeParams.isAllReplyShown,
         currentHighlightJsStyleId: customizeParams.styleName,
         currentHighlightJsStyleId: customizeParams.styleName,
         isHighlightJsStyleBorderEnabled: customizeParams.styleBorder,
         isHighlightJsStyleBorderEnabled: customizeParams.styleBorder,
         currentCustomizeTitle: customizeParams.customizeTitle,
         currentCustomizeTitle: customizeParams.customizeTitle,
@@ -159,6 +161,13 @@ export default class AdminCustomizeContainer extends Container {
     this.setState({ isEnabledStaleNotification:  !this.state.isEnabledStaleNotification });
     this.setState({ isEnabledStaleNotification:  !this.state.isEnabledStaleNotification });
   }
   }
 
 
+  /**
+   * Switch isAllReplyShown
+   */
+  switchIsAllReplyShown() {
+    this.setState({ isAllReplyShown: !this.state.isAllReplyShown });
+  }
+
   /**
   /**
    * Switch highlightJsStyle
    * Switch highlightJsStyle
    */
    */
@@ -289,6 +298,7 @@ export default class AdminCustomizeContainer extends Container {
         isEnabledAttachTitleHeader: this.state.isEnabledAttachTitleHeader,
         isEnabledAttachTitleHeader: this.state.isEnabledAttachTitleHeader,
         recentCreatedLimit: this.state.currentRecentCreatedLimit,
         recentCreatedLimit: this.state.currentRecentCreatedLimit,
         isEnabledStaleNotification: this.state.isEnabledStaleNotification,
         isEnabledStaleNotification: this.state.isEnabledStaleNotification,
+        isAllReplyShown: this.state.isAllReplyShown,
       });
       });
       const { customizedParams } = response.data;
       const { customizedParams } = response.data;
       this.setState({
       this.setState({
@@ -297,6 +307,7 @@ export default class AdminCustomizeContainer extends Container {
         isEnabledAttachTitleHeader: customizedParams.isEnabledAttachTitleHeader,
         isEnabledAttachTitleHeader: customizedParams.isEnabledAttachTitleHeader,
         recentCreatedLimit: customizedParams.currentRecentCreatedLimit,
         recentCreatedLimit: customizedParams.currentRecentCreatedLimit,
         isEnabledStaleNotification: customizedParams.isEnabledStaleNotification,
         isEnabledStaleNotification: customizedParams.isEnabledStaleNotification,
+        isAllReplyShown: customizedParams.isAllReplyShown,
       });
       });
     }
     }
     catch (err) {
     catch (err) {

+ 20 - 10
src/client/js/services/AppContainer.js

@@ -31,13 +31,17 @@ export default class AppContainer extends Container {
 
 
     const body = document.querySelector('body');
     const body = document.querySelector('body');
 
 
-    this.me = body.dataset.currentUsername || null; // will be initialized with null when data is empty string
     this.isAdmin = body.dataset.isAdmin === 'true';
     this.isAdmin = body.dataset.isAdmin === 'true';
     this.csrfToken = body.dataset.csrftoken;
     this.csrfToken = body.dataset.csrftoken;
     this.isPluginEnabled = body.dataset.pluginEnabled === 'true';
     this.isPluginEnabled = body.dataset.pluginEnabled === 'true';
     this.isLoggedin = document.querySelector('body.nologin') == null;
     this.isLoggedin = document.querySelector('body.nologin') == null;
 
 
-    this.config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
+    this.config = JSON.parse(document.getElementById('growi-context-hydrate').textContent || '{}');
+
+    const currentUserElem = document.getElementById('growi-current-user');
+    if (currentUserElem != null) {
+      this.currentUser = JSON.parse(currentUserElem.textContent);
+    }
 
 
     const userAgent = window.navigator.userAgent.toLowerCase();
     const userAgent = window.navigator.userAgent.toLowerCase();
     this.isMobile = /iphone|ipad|android/.test(userAgent);
     this.isMobile = /iphone|ipad|android/.test(userAgent);
@@ -107,6 +111,20 @@ export default class AppContainer extends Container {
     window.crowiPlugin = window.growiPlugin;
     window.crowiPlugin = window.growiPlugin;
   }
   }
 
 
+  get currentUserId() {
+    if (this.currentUser == null) {
+      return null;
+    }
+    return this.currentUser._id;
+  }
+
+  get currentUsername() {
+    if (this.currentUser == null) {
+      return null;
+    }
+    return this.currentUser.username;
+  }
+
   /**
   /**
    * @return {Object} window.Crowi (js/legacy/crowi.js)
    * @return {Object} window.Crowi (js/legacy/crowi.js)
    */
    */
@@ -271,14 +289,6 @@ export default class AppContainer extends Container {
     return users;
     return users;
   }
   }
 
 
-  findUser(username) {
-    if (this.userByName && this.userByName[username]) {
-      return this.userByName[username];
-    }
-
-    return null;
-  }
-
   launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
   launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
     let targetComponent;
     let targetComponent;
     switch (componentKind) {
     switch (componentKind) {

+ 20 - 7
src/client/styles/scss/_comment.scss

@@ -1,10 +1,18 @@
-.page-comment-main {
-  // delete button
-  .page-comment-control {
-    position: absolute;
-    top: 0;
-    right: 0;
-    display: none; // default hidden
+.main-container {
+  .page-comment-main {
+    pointer-events: auto;
+
+    // delete button
+    .page-comment-control {
+      position: absolute;
+      top: 0;
+      right: 0;
+      visibility: hidden;
+    }
+
+    &:hover > .page-comment-control {
+      visibility: visible;
+    }
   }
   }
 }
 }
 
 
@@ -24,6 +32,11 @@
     display: inline-block;
     display: inline-block;
     font-size: 0.9em;
     font-size: 0.9em;
   }
   }
+  .page-comment {
+    padding-top: 50px;
+    margin-top: -50px;
+    pointer-events: none;
+  }
 
 
   .page-comment {
   .page-comment {
     // older comments
     // older comments

+ 0 - 5
src/client/styles/scss/_comment_growi.scss

@@ -101,11 +101,6 @@
     border-left: none;
     border-left: none;
   }
   }
 
 
-  // show when hover
-  .page-comment-main:hover > .page-comment-control {
-    display: block;
-  }
-
   // display cheatsheet for comment form only
   // display cheatsheet for comment form only
   .comment-form {
   .comment-form {
     .editor-cheatsheet {
     .editor-cheatsheet {

+ 0 - 5
src/client/styles/scss/_comment_kibela.scss

@@ -106,11 +106,6 @@
     border-left: none;
     border-left: none;
   }
   }
 
 
-  // show when hover
-  .page-comment-main:hover > .page-comment-control {
-    display: block;
-  }
-
   // display cheatsheet for comment form only
   // display cheatsheet for comment form only
   .comment-form {
   .comment-form {
     .editor-cheatsheet {
     .editor-cheatsheet {

+ 0 - 5
src/client/styles/scss/_layout_crowi_sidebar.scss

@@ -144,11 +144,6 @@
               display: none; // default hidden
               display: none; // default hidden
             }
             }
           }
           }
-
-          // show controls when hover
-          .page-comment-main:hover > .page-comment-control {
-            display: block;
-          }
         }
         }
       }
       }
     }
     }

+ 1 - 4
src/client/styles/scss/_page.scss

@@ -1,5 +1,5 @@
 // import diff2html styles
 // import diff2html styles
-@import '~diff2html/dist/diff2html.css';
+@import '~diff2html/bundles/css/diff2html.min.css';
 
 
 .main-container {
 .main-container {
   // padding controll of .header-wrap and .content-main are moved to _layout and _form
   // padding controll of .header-wrap and .content-main are moved to _layout and _form
@@ -8,7 +8,6 @@
    * header
    * header
    */
    */
   header {
   header {
-
     // the container of h1
     // the container of h1
     div.title-container {
     div.title-container {
       padding-right: 5px;
       padding-right: 5px;
@@ -39,7 +38,6 @@
 
 
     // change button opacity
     // change button opacity
     &:hover {
     &:hover {
-
       .btn.btn-copy,
       .btn.btn-copy,
       .btn-copy-link,
       .btn-copy-link,
       .btn.btn-edit,
       .btn.btn-edit,
@@ -116,7 +114,6 @@
 .main .content-main .revision-history {
 .main .content-main .revision-history {
   .revision-history-list {
   .revision-history-list {
     .revision-history-outer {
     .revision-history-outer {
-
       // add border-top except of first element
       // add border-top except of first element
       &:not(:first-of-type) {
       &:not(:first-of-type) {
         border-top: 1px solid $border;
         border-top: 1px solid $border;

+ 1 - 1
src/client/styles/scss/style-app.scss

@@ -58,7 +58,7 @@
 /*
 /*
  * for Guest User Mode
  * for Guest User Mode
  */
  */
-.dropdown-disabled {
+.dropdown-toggle.dropdown-toggle-disabled {
   cursor: not-allowed;
   cursor: not-allowed;
 }
 }
 
 

+ 5 - 3
src/linter-checker/test.js

@@ -1,13 +1,15 @@
 /*
 /*
  * VSCode の Eslint 設定チェック方法
  * VSCode の Eslint 設定チェック方法
  *
  *
- * 1. VSCode で以下のエラーが表示されていることを確認
+ * 1. .eslilntignore ファイル中の `/src/linter-checker/**` 行を消す
+ * 
+ * 2. VSCode で以下のエラーが表示されていることを確認
  *   - constructor で eslint(space-before-blocks)
  *   - constructor で eslint(space-before-blocks)
  *   - ファイル末尾の ";" で eslint(eol-last)
  *   - ファイル末尾の ";" で eslint(eol-last)
  *
  *
- * 2. VSCode で上書き保存
+ * 3. VSCode で上書き保存
  *
  *
- * 3. 以下のように整形され、全てのエラーが消えていることを確認
+ * 4. 以下のように整形され、全てのエラーが消えていることを確認
  *   - "constructor() {" のように間にスペースが入る
  *   - "constructor() {" のように間にスペースが入る
  *   - ファイル末尾に空行が入る
  *   - ファイル末尾に空行が入る
  *
  *

+ 5 - 3
src/linter-checker/test.scss

@@ -1,13 +1,15 @@
 /*
 /*
  * VSCode の Stylelint 設定チェック方法
  * VSCode の Stylelint 設定チェック方法
  *
  *
- * 1. VSCode で以下のエラーが表示されていることを確認
+ * 1. .stylelintrc.json ファイル中の `src/linter-checker/test.scss` 行を削除
+ * 
+ * 2. VSCode で以下のエラーが表示されていることを確認
  *   - color で stylelint(order/properties-order)
  *   - color で stylelint(order/properties-order)
  *   - ul で stylelint(selector-combinator-space-after)
  *   - ul で stylelint(selector-combinator-space-after)
  *
  *
- * 2. VSCode で上書き保存
+ * 3. VSCode で上書き保存
  *
  *
- * 3. 以下のように整形され、全てのエラーが消えていることを確認
+ * 4. 以下のように整形され、全てのエラーが消えていることを確認
  *   - color が background の上の行にくる
  *   - color が background の上の行にくる
  *   - ul と li の間にスペースが入る
  *   - ul と li の間にスペースが入る
  *
  *

+ 4 - 0
src/server/crowi/express-init.js

@@ -19,6 +19,8 @@ module.exports = function(crowi, app) {
   const i18nSprintf = require('i18next-sprintf-postprocessor');
   const i18nSprintf = require('i18next-sprintf-postprocessor');
   const i18nMiddleware = require('i18next-express-middleware');
   const i18nMiddleware = require('i18next-express-middleware');
 
 
+  const safeRedirect = require('../middleware/safe-redirect')();
+
   const avoidSessionRoutes = require('../routes/avoid-session-routes');
   const avoidSessionRoutes = require('../routes/avoid-session-routes');
   const i18nUserSettingDetector = require('../util/i18nUserSettingDetector');
   const i18nUserSettingDetector = require('../util/i18nUserSettingDetector');
 
 
@@ -113,6 +115,8 @@ module.exports = function(crowi, app) {
 
 
   app.use(flash());
   app.use(flash());
 
 
+  app.use(safeRedirect);
+
   const middlewares = require('../util/middlewares')(crowi, app);
   const middlewares = require('../util/middlewares')(crowi, app);
 
 
   app.use(middlewares.swigFilters(swig));
   app.use(middlewares.swigFilters(swig));

+ 3 - 1
src/server/middleware/access-token-parser.js

@@ -16,7 +16,9 @@ module.exports = (crowi) => {
     logger.debug('accessToken is', accessToken);
     logger.debug('accessToken is', accessToken);
 
 
     const user = await User.findUserByApiToken(accessToken);
     const user = await User.findUserByApiToken(accessToken);
-    req.user = user;
+    // transforming attributes
+    // see User model
+    req.user = user.toObject();
     req.skipCsrfVerify = true;
     req.skipCsrfVerify = true;
 
 
     logger.debug('Access token parsed: skipCsrfVerify');
     logger.debug('Access token parsed: skipCsrfVerify');

+ 1 - 1
src/server/middleware/login-required.js

@@ -42,7 +42,7 @@ module.exports = (crowi, isGuestAllowed = false) => {
       return res.sendStatus(403);
       return res.sendStatus(403);
     }
     }
 
 
-    req.session.jumpTo = req.originalUrl;
+    req.session.redirectTo = req.originalUrl;
     return res.redirect('/login');
     return res.redirect('/login');
   };
   };
 
 

+ 65 - 0
src/server/middleware/safe-redirect.js

@@ -0,0 +1,65 @@
+/**
+ * Redirect with prevention from Open Redirect
+ *
+ * Usage: app.use(require('middleware/safe-redirect')(['example.com', 'some.example.com:8080']))
+ */
+
+const loggerFactory = require('@alias/logger');
+
+const logger = loggerFactory('growi:middleware:safe-redirect');
+
+/**
+ * Check whether the redirect url host is in specified whitelist
+ * @param {Array<string>} whitelistOfHosts
+ * @param {string} redirectToFqdn
+ */
+function isInWhitelist(whitelistOfHosts, redirectToFqdn) {
+  if (whitelistOfHosts == null || whitelistOfHosts.length === 0) {
+    return false;
+  }
+
+  const redirectUrl = new URL(redirectToFqdn);
+  return whitelistOfHosts.includes(redirectUrl.hostname) || whitelistOfHosts.includes(redirectUrl.host);
+}
+
+
+module.exports = (whitelistOfHosts) => {
+
+  return function(req, res, next) {
+
+    // extend res object
+    res.safeRedirect = function(redirectTo) {
+      if (redirectTo == null) {
+        return res.redirect('/');
+      }
+
+      try {
+        // check inner redirect
+        const redirectUrl = new URL(redirectTo, `${req.protocol}://${req.get('host')}`);
+        if (redirectUrl.hostname === req.hostname) {
+          logger.debug(`Requested redirect URL (${redirectTo}) is local.`);
+          return res.redirect(redirectUrl.href);
+        }
+        logger.debug(`Requested redirect URL (${redirectTo}) is NOT local.`);
+
+        // check whitelisted redirect
+        const isWhitelisted = isInWhitelist(whitelistOfHosts, redirectTo);
+        if (isWhitelisted) {
+          logger.debug(`Requested redirect URL (${redirectTo}) is in whitelist.`, `whitelist=${whitelistOfHosts}`);
+          return res.redirect(redirectTo);
+        }
+        logger.debug(`Requested redirect URL (${redirectTo}) is NOT in whitelist.`, `whitelist=${whitelistOfHosts}`);
+      }
+      catch (err) {
+        logger.warn(`Requested redirect URL (${redirectTo}) is invalid.`, err);
+      }
+
+      logger.warn(`Requested redirect URL (${redirectTo}) is UNSAFE, redirecting to root page.`);
+      return res.redirect('/');
+    };
+
+    next();
+
+  };
+
+};

+ 2 - 0
src/server/models/config.js

@@ -109,6 +109,7 @@ module.exports = function(crowi) {
       'customize:isEnabledAttachTitleHeader' : false,
       'customize:isEnabledAttachTitleHeader' : false,
       'customize:showRecentCreatedNumber' : 10,
       'customize:showRecentCreatedNumber' : 10,
       'customize:isEnabledStaleNotification': false,
       'customize:isEnabledStaleNotification': false,
+      'customize:isAllReplyShown': false,
 
 
       'importer:esa:team_name': undefined,
       'importer:esa:team_name': undefined,
       'importer:esa:access_token': undefined,
       'importer:esa:access_token': undefined,
@@ -188,6 +189,7 @@ module.exports = function(crowi) {
       pageBreakCustomSeparator: crowi.configManager.getConfig('markdown', 'markdown:presentation:pageBreakCustomSeparator'),
       pageBreakCustomSeparator: crowi.configManager.getConfig('markdown', 'markdown:presentation:pageBreakCustomSeparator'),
       isEnabledXssPrevention: crowi.configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
       isEnabledXssPrevention: crowi.configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
       isEnabledTimeline: crowi.configManager.getConfig('crowi', 'customize:isEnabledTimeline'),
       isEnabledTimeline: crowi.configManager.getConfig('crowi', 'customize:isEnabledTimeline'),
+      isAllReplyShown: crowi.configManager.getConfig('crowi', 'customize:isAllReplyShown'),
       xssOption: crowi.configManager.getConfig('markdown', 'markdown:xss:option'),
       xssOption: crowi.configManager.getConfig('markdown', 'markdown:xss:option'),
       tagWhiteList: crowi.xssService.getTagWhiteList(),
       tagWhiteList: crowi.xssService.getTagWhiteList(),
       attrWhiteList: crowi.xssService.getAttrWhiteList(),
       attrWhiteList: crowi.xssService.getAttrWhiteList(),

+ 6 - 0
src/server/routes/apiv3/customize-setting.js

@@ -49,6 +49,8 @@ const ErrorV3 = require('../../models/vo/error-apiv3');
  *            type: number
  *            type: number
  *          isEnabledStaleNotification:
  *          isEnabledStaleNotification:
  *            type: boolean
  *            type: boolean
+ *          isAllReplyShown:
+ *            type: boolean
  *      CustomizeHighlight:
  *      CustomizeHighlight:
  *        description: CustomizeHighlight
  *        description: CustomizeHighlight
  *        type: object
  *        type: object
@@ -112,6 +114,7 @@ module.exports = (crowi) => {
       body('isEnabledAttachTitleHeader').isBoolean(),
       body('isEnabledAttachTitleHeader').isBoolean(),
       body('recentCreatedLimit').isInt().isInt({ min: 1, max: 1000 }),
       body('recentCreatedLimit').isInt().isInt({ min: 1, max: 1000 }),
       body('isEnabledStaleNotification').isBoolean(),
       body('isEnabledStaleNotification').isBoolean(),
+      body('isAllReplyShown').isBoolean(),
     ],
     ],
     customizeTitle: [
     customizeTitle: [
       body('customizeTitle').isString(),
       body('customizeTitle').isString(),
@@ -164,6 +167,7 @@ module.exports = (crowi) => {
       isEnabledAttachTitleHeader: await crowi.configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader'),
       isEnabledAttachTitleHeader: await crowi.configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader'),
       recentCreatedLimit: await crowi.configManager.getConfig('crowi', 'customize:showRecentCreatedNumber'),
       recentCreatedLimit: await crowi.configManager.getConfig('crowi', 'customize:showRecentCreatedNumber'),
       isEnabledStaleNotification: await crowi.configManager.getConfig('crowi', 'customize:isEnabledStaleNotification'),
       isEnabledStaleNotification: await crowi.configManager.getConfig('crowi', 'customize:isEnabledStaleNotification'),
+      isAllReplyShown: await crowi.configManager.getConfig('crowi', 'customize:isAllReplyShown'),
       styleName: await crowi.configManager.getConfig('crowi', 'customize:highlightJsStyle'),
       styleName: await crowi.configManager.getConfig('crowi', 'customize:highlightJsStyle'),
       styleBorder: await crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
       styleBorder: await crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
       customizeTitle: await crowi.configManager.getConfig('crowi', 'customize:title'),
       customizeTitle: await crowi.configManager.getConfig('crowi', 'customize:title'),
@@ -329,6 +333,7 @@ module.exports = (crowi) => {
       'customize:isEnabledAttachTitleHeader': req.body.isEnabledAttachTitleHeader,
       'customize:isEnabledAttachTitleHeader': req.body.isEnabledAttachTitleHeader,
       'customize:showRecentCreatedNumber': req.body.recentCreatedLimit,
       'customize:showRecentCreatedNumber': req.body.recentCreatedLimit,
       'customize:isEnabledStaleNotification': req.body.isEnabledStaleNotification,
       'customize:isEnabledStaleNotification': req.body.isEnabledStaleNotification,
+      'customize:isAllReplyShown': req.body.isAllReplyShown,
     };
     };
 
 
     try {
     try {
@@ -339,6 +344,7 @@ module.exports = (crowi) => {
         isEnabledAttachTitleHeader: await crowi.configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader'),
         isEnabledAttachTitleHeader: await crowi.configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader'),
         recentCreatedLimit: await crowi.configManager.getConfig('crowi', 'customize:showRecentCreatedNumber'),
         recentCreatedLimit: await crowi.configManager.getConfig('crowi', 'customize:showRecentCreatedNumber'),
         isEnabledStaleNotification: await crowi.configManager.getConfig('crowi', 'customize:isEnabledStaleNotification'),
         isEnabledStaleNotification: await crowi.configManager.getConfig('crowi', 'customize:isEnabledStaleNotification'),
+        isAllReplyShown: await crowi.configManager.getConfig('crowi', 'customize:isAllReplyShown'),
       };
       };
       return res.apiv3({ customizedParams });
       return res.apiv3({ customizedParams });
     }
     }

+ 2 - 2
src/server/routes/index.js

@@ -47,14 +47,14 @@ module.exports = function(crowi, app) {
   }
   }
 
 
   app.get('/login/error/:reason'     , login.error);
   app.get('/login/error/:reason'     , login.error);
-  app.get('/login'                   , middlewares.applicationInstalled    , login.login);
+  app.get('/login'                   , middlewares.applicationInstalled     , login.preLogin, login.login);
   app.get('/login/invited'           , login.invited);
   app.get('/login/invited'           , login.invited);
   app.post('/login/activateInvited'  , form.invited                         , csrf, login.invited);
   app.post('/login/activateInvited'  , form.invited                         , csrf, login.invited);
   app.post('/login'                  , form.login                           , csrf, loginPassport.loginWithLocal, loginPassport.loginWithLdap, loginPassport.loginFailure);
   app.post('/login'                  , form.login                           , csrf, loginPassport.loginWithLocal, loginPassport.loginWithLdap, loginPassport.loginFailure);
   app.post('/_api/login/testLdap'    , loginRequiredStrictly , form.login , loginPassport.testLdapCredentials);
   app.post('/_api/login/testLdap'    , loginRequiredStrictly , form.login , loginPassport.testLdapCredentials);
 
 
   app.post('/register'               , form.register                        , csrf, login.register);
   app.post('/register'               , form.register                        , csrf, login.register);
-  app.get('/register'                , middlewares.applicationInstalled    , login.register);
+  app.get('/register'                , middlewares.applicationInstalled     , login.preLogin, login.register);
   app.get('/logout'                  , logout.logout);
   app.get('/logout'                  , logout.logout);
 
 
   app.get('/admin'                          , loginRequiredStrictly , adminRequired , admin.index);
   app.get('/admin'                          , loginRequiredStrictly , adminRequired , admin.index);

+ 4 - 20
src/server/routes/login-passport.js

@@ -4,7 +4,6 @@ module.exports = function(crowi, app) {
   const debug = require('debug')('growi:routes:login-passport');
   const debug = require('debug')('growi:routes:login-passport');
   const logger = require('@alias/logger')('growi:routes:login-passport');
   const logger = require('@alias/logger')('growi:routes:login-passport');
   const passport = require('passport');
   const passport = require('passport');
-  const { URL } = require('url');
   const ExternalAccount = crowi.model('ExternalAccount');
   const ExternalAccount = crowi.model('ExternalAccount');
   const passportService = crowi.passportService;
   const passportService = crowi.passportService;
 
 
@@ -22,25 +21,10 @@ module.exports = function(crowi, app) {
       }
       }
     });
     });
 
 
-    const jumpTo = req.session.jumpTo;
-    if (jumpTo) {
-      req.session.jumpTo = null;
-
-      // prevention from open redirect
-      try {
-        const redirectUrl = new URL(jumpTo, `${req.protocol}://${req.get('host')}`);
-        if (redirectUrl.hostname === req.hostname) {
-          return res.redirect(redirectUrl);
-        }
-        logger.warn('Requested redirect URL is invalid, redirect to root page');
-      }
-      catch (err) {
-        logger.warn('Requested redirect URL is invalid, redirect to root page', err);
-        return res.redirect('/');
-      }
-    }
-
-    return res.redirect('/');
+    const { redirectTo } = req.session;
+    // remove session.redirectTo
+    delete req.session.redirectTo;
+    return res.safeRedirect(redirectTo);
   };
   };
 
 
   /**
   /**

+ 27 - 46
src/server/routes/login.js

@@ -15,7 +15,9 @@ module.exports = function(crowi, app) {
   const actions = {};
   const actions = {};
 
 
   const loginSuccess = function(req, res, userData) {
   const loginSuccess = function(req, res, userData) {
-    req.user = req.session.user = userData;
+    // transforming attributes
+    // see User model
+    req.user = req.session.user = userData.toObject();
 
 
     // update lastLoginAt
     // update lastLoginAt
     userData.updateLastLoginAt(new Date(), (err, uData) => {
     userData.updateLastLoginAt(new Date(), (err, uData) => {
@@ -28,30 +30,10 @@ module.exports = function(crowi, app) {
       return res.redirect('/me/password');
       return res.redirect('/me/password');
     }
     }
 
 
-    const jumpTo = req.session.jumpTo;
-    if (jumpTo) {
-      req.session.jumpTo = null;
-
-      // prevention from open redirect
-      try {
-        const redirectUrl = new URL(jumpTo, `${req.protocol}://${req.get('host')}`);
-        if (redirectUrl.hostname === req.hostname) {
-          return res.redirect(redirectUrl);
-        }
-        logger.warn('Requested redirect URL is invalid, redirect to root page');
-      }
-      catch (err) {
-        logger.warn('Requested redirect URL is invalid, redirect to root page', err);
-        return res.redirect('/');
-      }
-    }
-
-    return res.redirect('/');
-  };
-
-  const loginFailure = function(req, res) {
-    req.flash('warningMessage', 'Sign in failure.');
-    return res.redirect('/login');
+    const { redirectTo } = req.session;
+    // remove session.redirectTo
+    delete req.session.redirectTo;
+    return res.safeRedirect(redirectTo);
   };
   };
 
 
   actions.error = function(req, res) {
   actions.error = function(req, res) {
@@ -72,30 +54,29 @@ module.exports = function(crowi, app) {
     });
     });
   };
   };
 
 
-  actions.login = function(req, res) {
-    const loginForm = req.body.loginForm;
+  actions.preLogin = function(req, res, next) {
+    // user has already logged in
+    if (req.user != null) {
+      const { redirectTo } = req.session;
+      // remove session.redirectTo
+      delete req.session.redirectTo;
+      return res.safeRedirect(redirectTo);
+    }
 
 
-    if (req.method == 'POST' && req.form.isValid) {
-      const username = loginForm.username;
-      const password = loginForm.password;
-
-      // find user
-      User.findUserByUsernameOrEmail(username, password, (err, user) => {
-        if (err) { return loginFailure(req, res) }
-        // check existence and password
-        if (!user || !user.isPasswordValid(password)) {
-          return loginFailure(req, res);
-        }
-        return loginSuccess(req, res, user);
-      });
+    // set referer to 'redirectTo'
+    if (req.session.redirectTo == null && req.headers.referer != null) {
+      req.session.redirectTo = req.headers.referer;
     }
     }
-    else { // method GET
-      if (req.form) {
-        debug(req.form.errors);
-      }
-      return res.render('login', {
-      });
+
+    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) {

+ 4 - 1
src/server/routes/logout.js

@@ -2,7 +2,10 @@ module.exports = function(crowi, app) {
   return {
   return {
     logout(req, res) {
     logout(req, res) {
       req.session.destroy();
       req.session.destroy();
-      return res.redirect('/');
+
+      // redirect
+      const redirectTo = req.headers.referer || '/';
+      return res.safeRedirect(redirectTo);
     },
     },
   };
   };
 };
 };

+ 1 - 1
src/server/views/installer.html

@@ -86,7 +86,7 @@
 </body>
 </body>
 {% endblock %}
 {% endblock %}
 
 
-<script type="application/json" id="crowi-context-hydrate">
+<script type="application/json" id="growi-context-hydrate">
 {{ local_config|json|safe|preventXss }}
 {{ local_config|json|safe|preventXss }}
 </script>
 </script>
 
 

+ 7 - 2
src/server/views/layout/layout.html

@@ -63,7 +63,6 @@
 <body
 <body
   class="{% block html_base_css %}{% endblock %}
   class="{% block html_base_css %}{% endblock %}
       {% if !getConfig('crowi', 'customize:layout') || 'crowi' === getConfig('crowi', 'customize:layout') %}crowi{% elseif !getConfig('crowi', 'customize:layout') || 'kibela' === getConfig('crowi', 'customize:layout') %}kibela{% else %}growi{% endif %}"
       {% if !getConfig('crowi', 'customize:layout') || 'crowi' === getConfig('crowi', 'customize:layout') %}crowi{% elseif !getConfig('crowi', 'customize:layout') || 'kibela' === getConfig('crowi', 'customize:layout') %}kibela{% else %}growi{% endif %}"
-  data-me="{{ user._id.toString() }}"
   data-is-admin="{{ user.admin }}"
   data-is-admin="{{ user.admin }}"
   data-plugin-enabled="{{ getConfig('crowi', 'plugin:isEnabledPlugins') }}"
   data-plugin-enabled="{{ getConfig('crowi', 'plugin:isEnabledPlugins') }}"
   {% block html_base_attr %}{% endblock %}
   {% block html_base_attr %}{% endblock %}
@@ -230,10 +229,16 @@
 </body>
 </body>
 {% endblock %}
 {% endblock %}
 
 
-<script type="application/json" id="crowi-context-hydrate">
+<script type="application/json" id="growi-context-hydrate">
 {{ local_config|json|safe|preventXss }}
 {{ local_config|json|safe|preventXss }}
 </script>
 </script>
 
 
+{% if user != null %}
+  <script type="application/json" id="growi-current-user">
+  {{ user|json|safe|preventXss }}
+  </script>
+{% endif %}
+
 {% block custom_script %}
 {% block custom_script %}
 <script>
 <script>
   {{ customizeService.getCustomScript() }}
   {{ customizeService.getCustomScript() }}

+ 4 - 1
src/server/views/widget/not_found_tabs.html

@@ -7,7 +7,10 @@
 
 
   {% if !isTrashPage() and !page.isDeleted() %}
   {% if !isTrashPage() and !page.isDeleted() %}
   <li class="nav-item grw-nav-main-left-tab">
   <li class="nav-item grw-nav-main-left-tab">
-    <a {% if user %}href="#edit" data-toggle="tab"{% endif %} class="nav-link edit-button {% if not user %}edit-button-disabled{% endif %}">
+    <a
+      {% if user %} href="#edit" data-toggle="tab" class="edit-button" {% endif %}
+      {% if not user %} class="edit-button edit-button-disabled" data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}" {% endif %}
+    >
       <i class="icon-note"></i> {{ t('Create') }}
       <i class="icon-note"></i> {{ t('Create') }}
     </a>
     </a>
   </li>
   </li>

+ 29 - 5
src/server/views/widget/page_tabs.html

@@ -12,13 +12,25 @@
 
 
   {% if !isTrashPage() %}
   {% if !isTrashPage() %}
   <li class="nav-item grw-main-nav-item-left grw-nav-item-edit">
   <li class="nav-item grw-main-nav-item-left grw-nav-item-edit">
-    <a {% if user %}href="#edit" role="tab" data-toggle="tab" {% endif %} class="nav-link edit-button {% if not user %}edit-button-disabled{% endif %}">
+    <a
+      {% if user %} href="#edit" data-toggle="tab" class="edit-button" {% endif %}
+      {% if not user %}
+        class="edit-button edit-button-disabled"
+        data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+      {% endif %}
+    >
       <i class="icon-note"></i> {{ t('Edit') }}
       <i class="icon-note"></i> {{ t('Edit') }}
     </a>
     </a>
   </li>
   </li>
   {% if isHackmdSetup() %}
   {% if isHackmdSetup() %}
-  <li class="nav-item grw-main-nav-item-left grw-nav-item-hackmd">
-    <a {% if user %}href="#hackmd" role="tab" data-toggle="tab" {% endif %} class="nav-link {% if not user %}edit-button-disabled{% endif %}">
+  <li class="nav-item grw-main-nav-item-left grw-nav-tab-hackmd">
+    <a
+      {% if user %} href="#hackmd" data-toggle="tab" class="edit-button" {% endif %}
+      {% if not user %}
+        class="edit-button edit-button-disabled"
+        data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+      {% endif %}
+    >
       <i class="fa fa-file-text-o"></i> {{ t('HackMD') }}
       <i class="fa fa-file-text-o"></i> {{ t('HackMD') }}
     </a>
     </a>
   </li>
   </li>
@@ -38,7 +50,13 @@
   {% if !isTrashPage() %}
   {% if !isTrashPage() %}
     {% if page.isPortal() %}
     {% if page.isPortal() %}
     <li class="nav-item">
     <li class="nav-item">
-      <a class="btn nav-link dropdown-toggle {% if not user %}dropdown-disabled{% endif %}" {% if user %}data-toggle="dropdown" {% endif %}>
+      <a
+        {% if user %} role="button" class="dropdown-toggle" data-toggle="dropdown" {% endif %}
+        {% if not user %}
+          class="dropdown-toggle dropdown-toggle-disabled"
+          data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+        {% endif %}
+      >
         <i class="icon-options-vertical"></i>
         <i class="icon-options-vertical"></i>
       </a>
       </a>
       <div class="dropdown-menu dropdown-menu-right">
       <div class="dropdown-menu dropdown-menu-right">
@@ -54,7 +72,13 @@
     </li>
     </li>
     {% else %}
     {% else %}
     <li class="nav-item dropdown">
     <li class="nav-item dropdown">
-      <a class="btn nav-link dropdown-toggle {% if not user %}dropdown-disabled{% endif %}" {% if user %}data-toggle="dropdown"{% endif %}>
+      <a
+        {% if user %} role="button" class="dropdown-toggle" data-toggle="dropdown" {% endif %}
+        {% if not user %}
+          class="dropdown-toggle dropdown-toggle-disabled"
+          data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+        {% endif %}
+      >
         <i class="icon-options-vertical"></i>
         <i class="icon-options-vertical"></i>
       </a>
       </a>
       <div class="dropdown-menu dropdown-menu-right">
       <div class="dropdown-menu dropdown-menu-right">

+ 29 - 5
src/server/views/widget/page_tabs_kibela.html

@@ -12,13 +12,25 @@
 
 
   {% if !isTrashPage() %}
   {% if !isTrashPage() %}
   <li class="grw-nav-main-left-tab nav-tab-edit">
   <li class="grw-nav-main-left-tab nav-tab-edit">
-    <a {% if user %}href="#edit" data-toggle="tab"{% endif %} class="nav-link edit-button {% if not user %}edit-button-disabled{% endif %}">
+    <a
+      {% if user %} href="#edit" data-toggle="tab" class="edit-button" {% endif %}
+      {% if not user %}
+        class="edit-button edit-button-disabled"
+        data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+      {% endif %}
+    >
       <i class="icon-note"></i> {{ t('Edit') }}
       <i class="icon-note"></i> {{ t('Edit') }}
     </a>
     </a>
   </li>
   </li>
   {% if isHackmdSetup() %}
   {% if isHackmdSetup() %}
   <li class="grw-nav-main-left-tab nav-tab-hackmd">
   <li class="grw-nav-main-left-tab nav-tab-hackmd">
-    <a {% if user %}href="#hackmd" data-toggle="tab"{% endif %} class="nav-link {% if not user %}edit-button-disabled{% endif %}">
+    <a
+      {% if user %} href="#hackmd" data-toggle="tab" class="edit-button" {% endif %}
+      {% if not user %}
+        class="edit-button edit-button-disabled"
+        data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+      {% endif %}
+    >
       <i class="fa fa-file-text-o"></i> {{ t('HackMD') }}
       <i class="fa fa-file-text-o"></i> {{ t('HackMD') }}
     </a>
     </a>
   </li>
   </li>
@@ -30,8 +42,14 @@
   #}
   #}
   {% if !isTrashPage() %}
   {% if !isTrashPage() %}
     {% if page.isPortal() %}
     {% if page.isPortal() %}
-    <li class="dropdown float-right">
-      <a class="dropdown-toggle {% if not user %}dropdown-disabled{% endif %}" {% if user %}data-toggle="dropdown" href="#"{% endif %}>
+    <li class="float-right dropdown">
+      <a
+        {% if user %} role="button" class="dropdown-toggle" data-toggle="dropdown" {% endif %}
+        {% if not user %}
+          class="dropdown-toggle dropdown-toggle-disabled"
+          data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+        {% endif %}
+      >
         <i class="icon-options-vertical"></i>
         <i class="icon-options-vertical"></i>
       </a>
       </a>
       <ul class="dropdown-menu">
       <ul class="dropdown-menu">
@@ -44,7 +62,13 @@
     </li>
     </li>
     {% else %}
     {% else %}
     <li class="dropdown float-right">
     <li class="dropdown float-right">
-      <a class="dropdown-toggle {% if not user %}dropdown-disabled{% endif %}" {% if user %}data-toggle="dropdown" href="#"{% endif %}>
+      <a
+        {% if user %} role="button" class="dropdown-toggle" data-toggle="dropdown" {% endif %}
+        {% if not user %}
+          class="dropdown-toggle dropdown-toggle-disabled"
+          data-toggle="tooltip" data-placement="top" data-container="body" title="{{ t('Not available for guest') }}"
+        {% endif %}
+      >
         <i class="icon-options-vertical"></i>
         <i class="icon-options-vertical"></i>
       </a>
       </a>
       <ul class="dropdown-menu">
       <ul class="dropdown-menu">

+ 4 - 4
src/test/middleware/login-required.test.js

@@ -101,7 +101,7 @@ describe('loginRequired', () => {
       expect(res.redirect).toHaveBeenCalledTimes(1);
       expect(res.redirect).toHaveBeenCalledTimes(1);
       expect(res.redirect).toHaveBeenCalledWith('/login');
       expect(res.redirect).toHaveBeenCalledWith('/login');
       expect(result).toBe('redirect');
       expect(result).toBe('redirect');
-      expect(req.session.jumpTo).toBe('original url 1');
+      expect(req.session.redirectTo).toBe('original url 1');
     });
     });
 
 
     test('pass user who logged in', () => {
     test('pass user who logged in', () => {
@@ -119,7 +119,7 @@ describe('loginRequired', () => {
       expect(res.redirect).not.toHaveBeenCalled();
       expect(res.redirect).not.toHaveBeenCalled();
       expect(next).toHaveBeenCalledTimes(1);
       expect(next).toHaveBeenCalledTimes(1);
       expect(result).toBe('next');
       expect(result).toBe('next');
-      expect(req.session.jumpTo).toBe(undefined);
+      expect(req.session.redirectTo).toBe(undefined);
     });
     });
 
 
     /* eslint-disable indent */
     /* eslint-disable indent */
@@ -142,7 +142,7 @@ describe('loginRequired', () => {
       expect(res.redirect).toHaveBeenCalledTimes(1);
       expect(res.redirect).toHaveBeenCalledTimes(1);
       expect(res.redirect).toHaveBeenCalledWith(expectedPath);
       expect(res.redirect).toHaveBeenCalledWith(expectedPath);
       expect(result).toBe('redirect');
       expect(result).toBe('redirect');
-      expect(req.session.jumpTo).toBe(undefined);
+      expect(req.session.redirectTo).toBe(undefined);
     });
     });
     /* eslint-disable indent */
     /* eslint-disable indent */
 
 
@@ -163,7 +163,7 @@ describe('loginRequired', () => {
       expect(res.redirect).toHaveBeenCalledTimes(1);
       expect(res.redirect).toHaveBeenCalledTimes(1);
       expect(res.redirect).toHaveBeenCalledWith('/login');
       expect(res.redirect).toHaveBeenCalledWith('/login');
       expect(result).toBe('redirect');
       expect(result).toBe('redirect');
-      expect(req.session.jumpTo).toBe('original url 1');
+      expect(req.session.redirectTo).toBe('original url 1');
     });
     });
 
 
   });
   });

+ 108 - 0
src/test/middleware/safe-redirect.test.js

@@ -0,0 +1,108 @@
+/* eslint-disable arrow-body-style */
+
+describe('safeRedirect', () => {
+  let safeRedirect;
+
+  const whitelistOfHosts = [
+    'white1.example.com:8080',
+    'white2.example.com',
+  ];
+
+  beforeEach(async(done) => {
+    safeRedirect = require('@server/middleware/safe-redirect')(whitelistOfHosts);
+    done();
+  });
+
+  describe('res.safeRedirect', () => {
+    // setup req/res/next
+    const req = {
+      protocol: 'http',
+      hostname: 'example.com',
+      get: jest.fn().mockReturnValue('example.com'),
+    };
+    const res = {
+      redirect: jest.fn().mockReturnValue('redirect'),
+    };
+    const next = jest.fn();
+
+    test('redirects to \'/\' because specified url causes open redirect vulnerability', () => {
+      safeRedirect(req, res, next);
+
+      const result = res.safeRedirect('//evil.example.com');
+
+      expect(next).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledWith('host');
+      expect(res.redirect).toHaveBeenCalledTimes(1);
+      expect(res.redirect).toHaveBeenCalledWith('/');
+      expect(result).toBe('redirect');
+    });
+
+    test('redirects to \'/\' because specified host without port is not in whitelist', () => {
+      safeRedirect(req, res, next);
+
+      const result = res.safeRedirect('http://white1.example.com/path/to/page');
+
+      expect(next).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledWith('host');
+      expect(res.redirect).toHaveBeenCalledTimes(1);
+      expect(res.redirect).toHaveBeenCalledWith('/');
+      expect(result).toBe('redirect');
+    });
+
+    test('redirects to the specified local url', () => {
+      safeRedirect(req, res, next);
+
+      const result = res.safeRedirect('/path/to/page');
+
+      expect(next).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledWith('host');
+      expect(res.redirect).toHaveBeenCalledTimes(1);
+      expect(res.redirect).toHaveBeenCalledWith('http://example.com/path/to/page');
+      expect(result).toBe('redirect');
+    });
+
+    test('redirects to the specified local url (fqdn)', () => {
+      safeRedirect(req, res, next);
+
+      const result = res.safeRedirect('http://example.com/path/to/page');
+
+      expect(next).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledWith('host');
+      expect(res.redirect).toHaveBeenCalledTimes(1);
+      expect(res.redirect).toHaveBeenCalledWith('http://example.com/path/to/page');
+      expect(result).toBe('redirect');
+    });
+
+    test('redirects to the specified whitelisted url (white1.example.com:8080)', () => {
+      safeRedirect(req, res, next);
+
+      const result = res.safeRedirect('http://white1.example.com:8080/path/to/page');
+
+      expect(next).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledWith('host');
+      expect(res.redirect).toHaveBeenCalledTimes(1);
+      expect(res.redirect).toHaveBeenCalledWith('http://white1.example.com:8080/path/to/page');
+      expect(result).toBe('redirect');
+    });
+
+    test('redirects to the specified whitelisted url (white2.example.com:8080)', () => {
+      safeRedirect(req, res, next);
+
+      const result = res.safeRedirect('http://white2.example.com:8080/path/to/page');
+
+      expect(next).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledTimes(1);
+      expect(req.get).toHaveBeenCalledWith('host');
+      expect(res.redirect).toHaveBeenCalledTimes(1);
+      expect(res.redirect).toHaveBeenCalledWith('http://white2.example.com:8080/path/to/page');
+      expect(result).toBe('redirect');
+    });
+
+  });
+
+});

Разница между файлами не показана из-за своего большого размера
+ 436 - 228
yarn.lock


Некоторые файлы не были показаны из-за большого количества измененных файлов