Ver código fonte

apply to src/server/routes

Yuki Takei 7 anos atrás
pai
commit
e22ceec21c

+ 5 - 0
.eslintrc.js

@@ -43,6 +43,10 @@ module.exports = {
         ignoreTrailingComments: true,
         ignoreTrailingComments: true,
       },
       },
     ],
     ],
+    'newline-per-chained-call': [
+      'error',
+      { ignoreChainWithDepth: 2 }
+    ],
     'no-continue': 'off',
     'no-continue': 'off',
     'no-param-reassign': [
     'no-param-reassign': [
       'error',
       'error',
@@ -100,6 +104,7 @@ module.exports = {
       'error',
       'error',
       { args: 'none' },
       { args: 'none' },
     ],
     ],
+    'radix': 'off',
     'react/destructuring-assignment': 'off',
     'react/destructuring-assignment': 'off',
     'react/forbid-prop-types': 'off',
     'react/forbid-prop-types': 'off',
     'react/no-unused-prop-types': 'off',
     'react/no-unused-prop-types': 'off',

+ 20 - 13
src/server/routes/attachment.js

@@ -1,4 +1,6 @@
-const debug = require('debug')('growi:routss:attachment');
+/* eslint-disable no-use-before-define */
+
+
 const logger = require('@alias/logger')('growi:routes:attachment');
 const logger = require('@alias/logger')('growi:routes:attachment');
 
 
 const path = require('path');
 const path = require('path');
@@ -21,6 +23,7 @@ module.exports = function(crowi, app) {
    */
    */
   async function isAccessibleByViewer(user, attachment) {
   async function isAccessibleByViewer(user, attachment) {
     if (attachment.page != null) {
     if (attachment.page != null) {
+      // eslint-disable-next-line no-return-await
       return await Page.isAccessiblePageByViewer(attachment.page, user);
       return await Page.isAccessiblePageByViewer(attachment.page, user);
     }
     }
     return true;
     return true;
@@ -34,12 +37,12 @@ module.exports = function(crowi, app) {
    */
    */
   async function isDeletableByUser(user, attachment) {
   async function isDeletableByUser(user, attachment) {
     const ownerId = attachment.creator._id || attachment.creator;
     const ownerId = attachment.creator._id || attachment.creator;
-    if (attachment.page == null) {  // when profile image
+    if (attachment.page == null) { // when profile image
       return user.id === ownerId.toString();
       return user.id === ownerId.toString();
     }
     }
-    else {
-      return await Page.isAccessiblePageByViewer(attachment.page, user);
-    }
+
+    // eslint-disable-next-line no-return-await
+    return await Page.isAccessiblePageByViewer(attachment.page, user);
   }
   }
 
 
   /**
   /**
@@ -103,7 +106,9 @@ module.exports = function(crowi, app) {
       throw new Error('File storage reaches limit');
       throw new Error('File storage reaches limit');
     }
     }
 
 
-    const fileStream = fs.createReadStream(file.path, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
+    const fileStream = fs.createReadStream(file.path, {
+      flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true,
+    });
 
 
     // create an Attachment document and upload file
     // create an Attachment document and upload file
     let attachment;
     let attachment;
@@ -112,7 +117,7 @@ module.exports = function(crowi, app) {
     }
     }
     catch (err) {
     catch (err) {
       // delete temporary file
       // delete temporary file
-      fs.unlink(file.path, function(err) { if (err) { logger.error('Error while deleting tmp file.') } });
+      fs.unlink(file.path, (err) => { if (err) { logger.error('Error while deleting tmp file.') } });
       throw err;
       throw err;
     }
     }
 
 
@@ -182,11 +187,13 @@ module.exports = function(crowi, app) {
       return res.json(ApiResponse.error('Parameters page_id is required.'));
       return res.json(ApiResponse.error('Parameters page_id is required.'));
     }
     }
 
 
-    let attachments = await Attachment.find({page: id})
-      .sort({'updatedAt': 1})
+    let attachments = await Attachment.find({ page: id })
+      .sort({ updatedAt: 1 })
       .populate({ path: 'creator', select: User.USER_PUBLIC_FIELDS, populate: User.IMAGE_POPULATION });
       .populate({ path: 'creator', select: User.USER_PUBLIC_FIELDS, populate: User.IMAGE_POPULATION });
 
 
-    attachments = attachments.map(attachment => attachment.toObject({ virtuals: true }));
+    attachments = attachments.map((attachment) => {
+      return attachment.toObject({ virtuals: true });
+    });
 
 
     return res.json(ApiResponse.success({ attachments }));
     return res.json(ApiResponse.success({ attachments }));
   };
   };
@@ -198,7 +205,7 @@ module.exports = function(crowi, app) {
    */
    */
   api.limit = async function(req, res) {
   api.limit = async function(req, res) {
     const isUploadable = await fileUploader.checkCapacity(req.query.fileSize);
     const isUploadable = await fileUploader.checkCapacity(req.query.fileSize);
-    return res.json(ApiResponse.success({isUploadable: isUploadable}));
+    return res.json(ApiResponse.success({ isUploadable }));
   };
   };
 
 
   /**
   /**
@@ -228,7 +235,7 @@ module.exports = function(crowi, app) {
     if (pageId == null) {
     if (pageId == null) {
       logger.debug('Create page before file upload');
       logger.debug('Create page before file upload');
 
 
-      page = await Page.create(path, '# '  + path, req.user, {grant: Page.GRANT_OWNER});
+      page = await Page.create(path, `# ${path}`, req.user, { grant: Page.GRANT_OWNER });
       pageCreated = true;
       pageCreated = true;
       pageId = page._id;
       pageId = page._id;
     }
     }
@@ -254,7 +261,7 @@ module.exports = function(crowi, app) {
     const result = {
     const result = {
       page: page.toObject(),
       page: page.toObject(),
       attachment: attachment.toObject({ virtuals: true }),
       attachment: attachment.toObject({ virtuals: true }),
-      pageCreated: pageCreated,
+      pageCreated,
     };
     };
 
 
     return res.json(ApiResponse.success(result));
     return res.json(ApiResponse.success(result));

+ 12 - 14
src/server/routes/bookmark.js

@@ -1,12 +1,10 @@
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
-  'use strict';
-
   const debug = require('debug')('growi:routes:bookmark');
   const debug = require('debug')('growi:routes:bookmark');
   const Bookmark = crowi.model('Bookmark');
   const Bookmark = crowi.model('Bookmark');
   const Page = crowi.model('Page');
   const Page = crowi.model('Page');
   const ApiResponse = require('../util/apiResponse');
   const ApiResponse = require('../util/apiResponse');
   const ApiPaginate = require('../util/apiPaginate');
   const ApiPaginate = require('../util/apiPaginate');
-  let actions = {};
+  const actions = {};
   actions.api = {};
   actions.api = {};
 
 
   /**
   /**
@@ -17,17 +15,17 @@ module.exports = function(crowi, app) {
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    */
    */
   actions.api.get = function(req, res) {
   actions.api.get = function(req, res) {
-    let pageId = req.query.page_id;
+    const pageId = req.query.page_id;
 
 
     Bookmark.findByPageIdAndUserId(pageId, req.user)
     Bookmark.findByPageIdAndUserId(pageId, req.user)
-      .then(function(data) {
+      .then((data) => {
         debug('bookmark found', pageId, data);
         debug('bookmark found', pageId, data);
-        let result = {};
+        const result = {};
 
 
         result.bookmark = data;
         result.bookmark = data;
         return res.json(ApiResponse.success(result));
         return res.json(ApiResponse.success(result));
       })
       })
-      .catch(function(err) {
+      .catch((err) => {
         return res.json(ApiResponse.error(err));
         return res.json(ApiResponse.error(err));
       });
       });
   };
   };
@@ -36,14 +34,14 @@ module.exports = function(crowi, app) {
    *
    *
    */
    */
   actions.api.list = function(req, res) {
   actions.api.list = function(req, res) {
-    let paginateOptions = ApiPaginate.parseOptions(req.query);
+    const paginateOptions = ApiPaginate.parseOptions(req.query);
 
 
-    let options = Object.assign(paginateOptions, { populatePage: true });
+    const options = Object.assign(paginateOptions, { populatePage: true });
     Bookmark.findByUserId(req.user._id, options)
     Bookmark.findByUserId(req.user._id, options)
-      .then(function(result) {
+      .then((result) => {
         return res.json(ApiResponse.success(result));
         return res.json(ApiResponse.success(result));
       })
       })
-      .catch(function(err) {
+      .catch((err) => {
         return res.json(ApiResponse.error(err));
         return res.json(ApiResponse.error(err));
       });
       });
   };
   };
@@ -80,14 +78,14 @@ module.exports = function(crowi, app) {
    * @apiParam {String} page_id Page Id.
    * @apiParam {String} page_id Page Id.
    */
    */
   actions.api.remove = function(req, res) {
   actions.api.remove = function(req, res) {
-    let pageId = req.body.page_id;
+    const pageId = req.body.page_id;
 
 
     Bookmark.removeBookmark(pageId, req.user)
     Bookmark.removeBookmark(pageId, req.user)
-      .then(function(data) {
+      .then((data) => {
         debug('Bookmark removed.', data); // if the bookmark is not exists, this 'data' is null
         debug('Bookmark removed.', data); // if the bookmark is not exists, this 'data' is null
         return res.json(ApiResponse.success());
         return res.json(ApiResponse.success());
       })
       })
-      .catch(function(err) {
+      .catch((err) => {
         return res.json(ApiResponse.error(err));
         return res.json(ApiResponse.error(err));
       });
       });
   };
   };

+ 16 - 18
src/server/routes/comment.js

@@ -1,18 +1,16 @@
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
-  'use strict';
+  const logger = require('@alias/logger')('growi:routes:comment');
+  const Comment = crowi.model('Comment');
+  const User = crowi.model('User');
+  const Page = crowi.model('Page');
+  const ApiResponse = require('../util/apiResponse');
+  const globalNotificationService = crowi.getGlobalNotificationService();
 
 
-  const logger = require('@alias/logger')('growi:routes:comment')
-    , Comment = crowi.model('Comment')
-    , User = crowi.model('User')
-    , Page = crowi.model('Page')
-    , ApiResponse = require('../util/apiResponse')
-    , globalNotificationService = crowi.getGlobalNotificationService()
-    , actions = {}
-    , api = {};
+  const actions = {};
+  const api = {};
 
 
   actions.api = api;
   actions.api = api;
 
 
-
   /**
   /**
    * @api {get} /comments.get Get comments of the page of the revision
    * @api {get} /comments.get Get comments of the page of the revision
    * @apiName GetComments
    * @apiName GetComments
@@ -46,10 +44,10 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     const comments = await fetcher.populate(
     const comments = await fetcher.populate(
-      { path: 'creator', select: User.USER_PUBLIC_FIELDS, populate: User.IMAGE_POPULATION }
+      { path: 'creator', select: User.USER_PUBLIC_FIELDS, populate: User.IMAGE_POPULATION },
     );
     );
 
 
-    res.json(ApiResponse.success({comments}));
+    res.json(ApiResponse.success({ comments }));
   };
   };
 
 
   /**
   /**
@@ -84,17 +82,17 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     const createdComment = await Comment.create(pageId, req.user._id, revisionId, comment, position, isMarkdown)
     const createdComment = await Comment.create(pageId, req.user._id, revisionId, comment, position, isMarkdown)
-      .catch(function(err) {
+      .catch((err) => {
         return res.json(ApiResponse.error(err));
         return res.json(ApiResponse.error(err));
       });
       });
 
 
     // update page
     // update page
     const page = await Page.findOneAndUpdate({ _id: pageId }, {
     const page = await Page.findOneAndUpdate({ _id: pageId }, {
       lastUpdateUser: req.user,
       lastUpdateUser: req.user,
-      updatedAt: new Date()
+      updatedAt: new Date(),
     });
     });
 
 
-    res.json(ApiResponse.success({comment: createdComment}));
+    res.json(ApiResponse.success({ comment: createdComment }));
 
 
     const path = page.path;
     const path = page.path;
 
 
@@ -107,16 +105,16 @@ module.exports = function(crowi, app) {
       const channels = slackNotificationForm.slackChannels;
       const channels = slackNotificationForm.slackChannels;
 
 
       if (channels) {
       if (channels) {
-        page.updateSlackChannel(channels).catch(err => {
+        page.updateSlackChannel(channels).catch((err) => {
           logger.error('Error occured in updating slack channels: ', err);
           logger.error('Error occured in updating slack channels: ', err);
         });
         });
 
 
-        const promises = channels.split(',').map(function(chan) {
+        const promises = channels.split(',').map((chan) => {
           return crowi.slack.postComment(createdComment, user, chan, path);
           return crowi.slack.postComment(createdComment, user, chan, path);
         });
         });
 
 
         Promise.all(promises)
         Promise.all(promises)
-          .catch(err => {
+          .catch((err) => {
             logger.error('Error occured in sending slack notification: ', err);
             logger.error('Error occured in sending slack notification: ', err);
           });
           });
       }
       }

+ 11 - 7
src/server/routes/hackmd.js

@@ -1,3 +1,5 @@
+/* eslint-disable no-use-before-define */
+
 const logger = require('@alias/logger')('growi:routes:hackmd');
 const logger = require('@alias/logger')('growi:routes:hackmd');
 const path = require('path');
 const path = require('path');
 const fs = require('graceful-fs');
 const fs = require('graceful-fs');
@@ -15,12 +17,12 @@ module.exports = function(crowi, app) {
   const agentScriptPath = path.join(crowi.publicDir, manifest['js/hackmd-agent.js']);
   const agentScriptPath = path.join(crowi.publicDir, manifest['js/hackmd-agent.js']);
   const stylesScriptPath = path.join(crowi.publicDir, manifest['js/hackmd-styles.js']);
   const stylesScriptPath = path.join(crowi.publicDir, manifest['js/hackmd-styles.js']);
   // generate swig template
   // generate swig template
-  let agentScriptContentTpl = undefined;
-  let stylesScriptContentTpl = undefined;
+  let agentScriptContentTpl;
+  let stylesScriptContentTpl;
 
 
   // init 'saveOnHackmd' event
   // init 'saveOnHackmd' event
-  pageEvent.on('saveOnHackmd', function(page) {
-    crowi.getIo().sockets.emit('page:editingWithHackmd', {page});
+  pageEvent.on('saveOnHackmd', (page) => {
+    crowi.getIo().sockets.emit('page:editingWithHackmd', { page });
   });
   });
 
 
   /**
   /**
@@ -67,7 +69,9 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     const styleFilePath = path.join(crowi.publicDir, manifest['styles/style-hackmd.css']);
     const styleFilePath = path.join(crowi.publicDir, manifest['styles/style-hackmd.css']);
-    const styles = fs.readFileSync(styleFilePath).toString().replace(/\s+/g, ' ');
+    const styles = fs
+      .readFileSync(styleFilePath).toString()
+      .replace(/\s+/g, ' ');
 
 
     // generate definitions to replace
     // generate definitions to replace
     const definitions = {
     const definitions = {
@@ -150,8 +154,8 @@ module.exports = function(crowi, app) {
     logger.debug('HackMD responds', response);
     logger.debug('HackMD responds', response);
 
 
     // extract page id on HackMD
     // extract page id on HackMD
-    const pagePathOnHackmd = response.request.path;     // e.g. '/NC7bSRraT1CQO1TO7wjCPw'
-    const pageIdOnHackmd = pagePathOnHackmd.substr(1);  // strip the head '/'
+    const pagePathOnHackmd = response.request.path; // e.g. '/NC7bSRraT1CQO1TO7wjCPw'
+    const pageIdOnHackmd = pagePathOnHackmd.substr(1); // strip the head '/'
 
 
     return Page.registerHackmdPage(page, pageIdOnHackmd);
     return Page.registerHackmdPage(page, pageIdOnHackmd);
   }
   }

+ 46 - 48
src/server/routes/index.js

@@ -1,40 +1,38 @@
-const multer = require('multer')
-const autoReap  = require('multer-autoreap');
-autoReap.options.reapOnError = true;  // continue reaping the file even if an error occurs
+const multer = require('multer');
+const autoReap = require('multer-autoreap');
+
+autoReap.options.reapOnError = true; // continue reaping the file even if an error occurs
 
 
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
-  const middleware = require('../util/middlewares')
-    , uploads   = multer({dest: crowi.tmpDir + 'uploads'})
-    , form      = require('../form')
-    , page      = require('./page')(crowi, app)
-    , login     = require('./login')(crowi, app)
-    , loginPassport = require('./login-passport')(crowi, app)
-    , logout    = require('./logout')(crowi, app)
-    , me        = require('./me')(crowi, app)
-    , admin     = require('./admin')(crowi, app)
-    , installer = require('./installer')(crowi, app)
-    , user      = require('./user')(crowi, app)
-    , attachment= require('./attachment')(crowi, app)
-    , comment   = require('./comment')(crowi, app)
-    , bookmark  = require('./bookmark')(crowi, app)
-    , revision  = require('./revision')(crowi, app)
-    , search    = require('./search')(crowi, app)
-    , hackmd    = require('./hackmd')(crowi, app)
-    , loginRequired = middleware.loginRequired
-    , accessTokenParser = middleware.accessTokenParser(crowi, app)
-    , csrf      = middleware.csrfVerify(crowi, app)
-
-    , config    = crowi.getConfig()
-    , Config    = crowi.model('Config')
-    ;
-
-  /* eslint-disable comma-spacing */
+  const middleware = require('../util/middlewares');
+  const uploads = multer({ dest: `${crowi.tmpDir}uploads` });
+  const form = require('../form');
+  const page = require('./page')(crowi, app);
+  const login = require('./login')(crowi, app);
+  const loginPassport = require('./login-passport')(crowi, app);
+  const logout = require('./logout')(crowi, app);
+  const me = require('./me')(crowi, app);
+  const admin = require('./admin')(crowi, app);
+  const installer = require('./installer')(crowi, app);
+  const user = require('./user')(crowi, app);
+  const attachment = require('./attachment')(crowi, app);
+  const comment = require('./comment')(crowi, app);
+  const bookmark = require('./bookmark')(crowi, app);
+  const revision = require('./revision')(crowi, app);
+  const search = require('./search')(crowi, app);
+  const hackmd = require('./hackmd')(crowi, app);
+  const loginRequired = middleware.loginRequired;
+  const accessTokenParser = middleware.accessTokenParser(crowi, app);
+  const csrf = middleware.csrfVerify(crowi, app);
+  const config = crowi.getConfig();
+  const Config = crowi.model('Config');
+
+  /* eslint-disable max-len, comma-spacing, no-multi-spaces */
 
 
   app.get('/'                        , middleware.applicationInstalled(), loginRequired(crowi, app, false) , page.showTopPage);
   app.get('/'                        , middleware.applicationInstalled(), loginRequired(crowi, app, false) , page.showTopPage);
 
 
   app.get('/installer'               , middleware.applicationNotInstalled() , installer.index);
   app.get('/installer'               , middleware.applicationNotInstalled() , installer.index);
   app.post('/installer'              , middleware.applicationNotInstalled() , form.register , csrf, installer.install);
   app.post('/installer'              , middleware.applicationNotInstalled() , form.register , csrf, installer.install);
-  //app.post('/installer/user'         , middleware.applicationNotInstalled() , installer.createFirstUser);
 
 
   app.get('/login/error/:reason'     , login.error);
   app.get('/login/error/:reason'     , login.error);
   app.get('/login'                   , middleware.applicationInstalled()    , login.login);
   app.get('/login'                   , middleware.applicationInstalled()    , login.login);
@@ -88,7 +86,7 @@ module.exports = function(crowi, app) {
 
 
   // markdown admin
   // markdown admin
   app.get('/admin/markdown'                   , loginRequired(crowi, app) , middleware.adminRequired() , admin.markdown.index);
   app.get('/admin/markdown'                   , loginRequired(crowi, app) , middleware.adminRequired() , admin.markdown.index);
-  app.post('/admin/markdown/lineBreaksSetting', loginRequired(crowi, app) , middleware.adminRequired() , csrf, form.admin.markdown, admin.markdown.lineBreaksSetting); //change form name
+  app.post('/admin/markdown/lineBreaksSetting', loginRequired(crowi, app) , middleware.adminRequired() , csrf, form.admin.markdown, admin.markdown.lineBreaksSetting); // change form name
   app.post('/admin/markdown/xss-setting'      , loginRequired(crowi, app) , middleware.adminRequired() , csrf, form.admin.markdownXss, admin.markdown.xssSetting);
   app.post('/admin/markdown/xss-setting'      , loginRequired(crowi, app) , middleware.adminRequired() , csrf, form.admin.markdownXss, admin.markdown.xssSetting);
   app.post('/admin/markdown/presentationSetting', loginRequired(crowi, app) , middleware.adminRequired() , csrf, form.admin.markdownPresentation, admin.markdown.presentationSetting);
   app.post('/admin/markdown/presentationSetting', loginRequired(crowi, app) , middleware.adminRequired() , csrf, form.admin.markdownPresentation, admin.markdown.presentationSetting);
 
 
@@ -172,20 +170,20 @@ module.exports = function(crowi, app) {
   app.post('/me/imagetype'            , form.me.imagetype         , loginRequired(crowi, app) , me.imagetype);
   app.post('/me/imagetype'            , form.me.imagetype         , loginRequired(crowi, app) , me.imagetype);
   app.post('/me/apiToken'             , form.me.apiToken          , loginRequired(crowi, app) , me.apiToken);
   app.post('/me/apiToken'             , form.me.apiToken          , loginRequired(crowi, app) , me.apiToken);
   app.post('/me/auth/google'          , loginRequired(crowi, app) , me.authGoogle);
   app.post('/me/auth/google'          , loginRequired(crowi, app) , me.authGoogle);
-  app.get( '/me/auth/google/callback' , loginRequired(crowi, app) , me.authGoogleCallback);
+  app.get('/me/auth/google/callback' , loginRequired(crowi, app) , me.authGoogleCallback);
 
 
-  app.get( '/:id([0-9a-z]{24})'       , loginRequired(crowi, app, false) , page.redirector);
-  app.get( '/_r/:id([0-9a-z]{24})'    , loginRequired(crowi, app, false) , page.redirector); // alias
-  app.get( '/attachment/:pageId/:fileName'  , loginRequired(crowi, app, false), attachment.api.obsoletedGetForMongoDB); // DEPRECATED: remains for backward compatibility for v3.3.x or below
-  app.get( '/attachment/:id([0-9a-z]{24})'  , loginRequired(crowi, app, false), attachment.api.get);
-  app.get( '/download/:id([0-9a-z]{24})'    , loginRequired(crowi, app, false), attachment.api.download);
+  app.get('/:id([0-9a-z]{24})'       , loginRequired(crowi, app, false) , page.redirector);
+  app.get('/_r/:id([0-9a-z]{24})'    , loginRequired(crowi, app, false) , page.redirector); // alias
+  app.get('/attachment/:pageId/:fileName'  , loginRequired(crowi, app, false), attachment.api.obsoletedGetForMongoDB); // DEPRECATED: remains for backward compatibility for v3.3.x or below
+  app.get('/attachment/:id([0-9a-z]{24})'  , loginRequired(crowi, app, false), attachment.api.get);
+  app.get('/download/:id([0-9a-z]{24})'    , loginRequired(crowi, app, false), attachment.api.download);
 
 
-  app.get( '/_search'                 , loginRequired(crowi, app, false) , search.searchPage);
-  app.get( '/_api/search'             , accessTokenParser , loginRequired(crowi, app, false) , search.api.search);
+  app.get('/_search'                 , loginRequired(crowi, app, false) , search.searchPage);
+  app.get('/_api/search'             , accessTokenParser , loginRequired(crowi, app, false) , search.api.search);
 
 
-  app.get( '/_api/check_username'           , user.api.checkUsername);
-  app.get( '/_api/me/user-group-relations'  , accessTokenParser , loginRequired(crowi, app) , me.api.userGroupRelations);
-  app.get( '/_api/user/bookmarks'           , loginRequired(crowi, app, false) , user.api.bookmarks);
+  app.get('/_api/check_username'           , user.api.checkUsername);
+  app.get('/_api/me/user-group-relations'  , accessTokenParser , loginRequired(crowi, app) , me.api.userGroupRelations);
+  app.get('/_api/user/bookmarks'           , loginRequired(crowi, app, false) , user.api.bookmarks);
 
 
   // HTTP RPC Styled API (に徐々に移行していいこうと思う)
   // HTTP RPC Styled API (に徐々に移行していいこうと思う)
   app.get('/_api/users.list'          , accessTokenParser , loginRequired(crowi, app, false) , user.api.list);
   app.get('/_api/users.list'          , accessTokenParser , loginRequired(crowi, app, false) , user.api.list);
@@ -205,20 +203,20 @@ module.exports = function(crowi, app) {
   app.get('/_api/comments.get'        , accessTokenParser , loginRequired(crowi, app, false) , comment.api.get);
   app.get('/_api/comments.get'        , accessTokenParser , loginRequired(crowi, app, false) , comment.api.get);
   app.post('/_api/comments.add'       , form.comment, accessTokenParser , loginRequired(crowi, app) , csrf, comment.api.add);
   app.post('/_api/comments.add'       , form.comment, accessTokenParser , loginRequired(crowi, app) , csrf, comment.api.add);
   app.post('/_api/comments.remove'    , accessTokenParser , loginRequired(crowi, app) , csrf, comment.api.remove);
   app.post('/_api/comments.remove'    , accessTokenParser , loginRequired(crowi, app) , csrf, comment.api.remove);
-  app.get( '/_api/bookmarks.get'      , accessTokenParser , loginRequired(crowi, app, false) , bookmark.api.get);
+  app.get('/_api/bookmarks.get'      , accessTokenParser , loginRequired(crowi, app, false) , bookmark.api.get);
   app.post('/_api/bookmarks.add'      , accessTokenParser , loginRequired(crowi, app) , csrf, bookmark.api.add);
   app.post('/_api/bookmarks.add'      , accessTokenParser , loginRequired(crowi, app) , csrf, bookmark.api.add);
   app.post('/_api/bookmarks.remove'   , accessTokenParser , loginRequired(crowi, app) , csrf, bookmark.api.remove);
   app.post('/_api/bookmarks.remove'   , accessTokenParser , loginRequired(crowi, app) , csrf, bookmark.api.remove);
   app.post('/_api/likes.add'          , accessTokenParser , loginRequired(crowi, app) , csrf, page.api.like);
   app.post('/_api/likes.add'          , accessTokenParser , loginRequired(crowi, app) , csrf, page.api.like);
   app.post('/_api/likes.remove'       , accessTokenParser , loginRequired(crowi, app) , csrf, page.api.unlike);
   app.post('/_api/likes.remove'       , accessTokenParser , loginRequired(crowi, app) , csrf, page.api.unlike);
-  app.get( '/_api/attachments.list'   , accessTokenParser , loginRequired(crowi, app, false) , attachment.api.list);
+  app.get('/_api/attachments.list'   , accessTokenParser , loginRequired(crowi, app, false) , attachment.api.list);
   app.post('/_api/attachments.add'                  , uploads.single('file'), autoReap, accessTokenParser, loginRequired(crowi, app) ,csrf, attachment.api.add);
   app.post('/_api/attachments.add'                  , uploads.single('file'), autoReap, accessTokenParser, loginRequired(crowi, app) ,csrf, attachment.api.add);
   app.post('/_api/attachments.uploadProfileImage'   , uploads.single('file'), autoReap, accessTokenParser, loginRequired(crowi, app) ,csrf, attachment.api.uploadProfileImage);
   app.post('/_api/attachments.uploadProfileImage'   , uploads.single('file'), autoReap, accessTokenParser, loginRequired(crowi, app) ,csrf, attachment.api.uploadProfileImage);
   app.post('/_api/attachments.remove' , accessTokenParser , loginRequired(crowi, app) , csrf, attachment.api.remove);
   app.post('/_api/attachments.remove' , accessTokenParser , loginRequired(crowi, app) , csrf, attachment.api.remove);
-  app.get( '/_api/attachments.limit'  , accessTokenParser , loginRequired(crowi, app) , csrf, attachment.api.limit);
+  app.get('/_api/attachments.limit'  , accessTokenParser , loginRequired(crowi, app) , csrf, attachment.api.limit);
 
 
-  app.get( '/_api/revisions.get'      , accessTokenParser , loginRequired(crowi, app, false) , revision.api.get);
-  app.get( '/_api/revisions.ids'      , accessTokenParser , loginRequired(crowi, app, false) , revision.api.ids);
-  app.get( '/_api/revisions.list'     , accessTokenParser , loginRequired(crowi, app, false) , revision.api.list);
+  app.get('/_api/revisions.get'      , accessTokenParser , loginRequired(crowi, app, false) , revision.api.get);
+  app.get('/_api/revisions.ids'      , accessTokenParser , loginRequired(crowi, app, false) , revision.api.ids);
+  app.get('/_api/revisions.list'     , accessTokenParser , loginRequired(crowi, app, false) , revision.api.list);
 
 
   app.get('/trash$'                  , loginRequired(crowi, app, false) , page.trashPageShowWrapper);
   app.get('/trash$'                  , loginRequired(crowi, app, false) , page.trashPageShowWrapper);
   app.get('/trash/$'                 , loginRequired(crowi, app, false) , page.trashPageListShowWrapper);
   app.get('/trash/$'                 , loginRequired(crowi, app, false) , page.trashPageListShowWrapper);

+ 6 - 9
src/server/routes/installer.js

@@ -1,6 +1,4 @@
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
-  'use strict';
-
   const logger = require('@alias/logger')('growi:routes:installer');
   const logger = require('@alias/logger')('growi:routes:installer');
   const path = require('path');
   const path = require('path');
   const fs = require('graceful-fs');
   const fs = require('graceful-fs');
@@ -73,28 +71,27 @@ module.exports = function(crowi, app) {
       await adminUser.asyncMakeAdmin();
       await adminUser.asyncMakeAdmin();
     }
     }
     catch (err) {
     catch (err) {
-      req.form.errors.push('管理ユーザーの作成に失敗しました。' + err.message);
+      req.form.errors.push(`管理ユーザーの作成に失敗しました。${err.message}`);
       return res.render('installer');
       return res.render('installer');
     }
     }
 
 
-    Config.applicationInstall(function(err, configs) {
+    Config.applicationInstall((err, configs) => {
       if (err) {
       if (err) {
         logger.error(err);
         logger.error(err);
         return;
         return;
       }
       }
 
 
       // save the globalLang config, and update the config cache
       // save the globalLang config, and update the config cache
-      Config.updateNamespaceByArray('crowi', {'app:globalLang': language}, function(err, config) {
+      Config.updateNamespaceByArray('crowi', { 'app:globalLang': language }, (err, config) => {
         Config.updateConfigCache('crowi', config);
         Config.updateConfigCache('crowi', config);
       });
       });
 
 
       // login with passport
       // login with passport
       req.logIn(adminUser, (err) => {
       req.logIn(adminUser, (err) => {
         if (err) { return next() }
         if (err) { return next() }
-        else {
-          req.flash('successMessage', 'GROWI のインストールが完了しました!はじめに、このページで各種設定を確認してください。');
-          return res.redirect('/admin/app');
-        }
+
+        req.flash('successMessage', 'GROWI のインストールが完了しました!はじめに、このページで各種設定を確認してください。');
+        return res.redirect('/admin/app');
       });
       });
     });
     });
 
 

+ 46 - 49
src/server/routes/login-passport.js

@@ -1,13 +1,11 @@
-module.exports = function(crowi, app) {
-  'use strict';
+/* eslint-disable no-use-before-define */
 
 
-  const debug = require('debug')('growi:routes:login-passport')
-    , logger = require('@alias/logger')('growi:routes:login-passport')
-    , passport = require('passport')
-    , config = crowi.getConfig()
-    , ExternalAccount = crowi.model('ExternalAccount')
-    , passportService = crowi.passportService
-    ;
+module.exports = function(crowi, app) {
+  const debug = require('debug')('growi:routes:login-passport');
+  const logger = require('@alias/logger')('growi:routes:login-passport');
+  const passport = require('passport');
+  const ExternalAccount = crowi.model('ExternalAccount');
+  const passportService = crowi.passportService;
 
 
   /**
   /**
    * success handler
    * success handler
@@ -28,9 +26,8 @@ module.exports = function(crowi, app) {
       req.session.jumpTo = null;
       req.session.jumpTo = null;
       return res.redirect(jumpTo);
       return res.redirect(jumpTo);
     }
     }
-    else {
-      return res.redirect('/');
-    }
+
+    return res.redirect('/');
   };
   };
 
 
   /**
   /**
@@ -53,7 +50,7 @@ module.exports = function(crowi, app) {
   function isValidLdapUserByGroupFilter(user) {
   function isValidLdapUserByGroupFilter(user) {
     let bool = true;
     let bool = true;
     if (user._groups != null) {
     if (user._groups != null) {
-      if (user._groups.length == 0) {
+      if (user._groups.length === 0) {
         bool = false;
         bool = false;
       }
       }
     }
     }
@@ -106,10 +103,10 @@ module.exports = function(crowi, app) {
     const nameToBeRegistered = ldapAccountInfo[attrMapName];
     const nameToBeRegistered = ldapAccountInfo[attrMapName];
     const mailToBeRegistered = ldapAccountInfo[attrMapMail];
     const mailToBeRegistered = ldapAccountInfo[attrMapMail];
     const userInfo = {
     const userInfo = {
-      'id': ldapAccountId,
-      'username': usernameToBeRegistered,
-      'name': nameToBeRegistered,
-      'email': mailToBeRegistered,
+      id: ldapAccountId,
+      username: usernameToBeRegistered,
+      name: nameToBeRegistered,
+      email: mailToBeRegistered,
     };
     };
 
 
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
@@ -120,7 +117,7 @@ module.exports = function(crowi, app) {
     const user = await externalAccount.getPopulatedUser();
     const user = await externalAccount.getPopulatedUser();
 
 
     // login
     // login
-    await req.logIn(user, err => {
+    await req.logIn(user, (err) => {
       if (err) { return next(err) }
       if (err) { return next(err) }
       return loginSuccess(req, res, user);
       return loginSuccess(req, res, user);
     });
     });
@@ -142,16 +139,16 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     passport.authenticate('ldapauth', (err, user, info) => {
     passport.authenticate('ldapauth', (err, user, info) => {
-      if (res.headersSent) {  // dirty hack -- 2017.09.25
-        return;               // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
+      if (res.headersSent) { // dirty hack -- 2017.09.25
+        return; //              cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
       }
       }
 
 
-      if (err) {  // DB Error
+      if (err) { // DB Error
         logger.error('LDAP Server Error: ', err);
         logger.error('LDAP Server Error: ', err);
         return res.json({
         return res.json({
           status: 'warning',
           status: 'warning',
           message: 'LDAP Server Error occured.',
           message: 'LDAP Server Error occured.',
-          err
+          err,
         });
         });
       }
       }
       if (info && info.message) {
       if (info && info.message) {
@@ -199,7 +196,7 @@ module.exports = function(crowi, app) {
       debug('user', user);
       debug('user', user);
       debug('info', info);
       debug('info', info);
 
 
-      if (err) {  // DB Error
+      if (err) { // DB Error
         logger.error('Database Server Error: ', err);
         logger.error('Database Server Error: ', err);
         req.flash('warningMessage', 'Database Server Error occured.');
         req.flash('warningMessage', 'Database Server Error occured.');
         return next(); // pass and the flash message is displayed when all of authentications are failed.
         return next(); // pass and the flash message is displayed when all of authentications are failed.
@@ -207,9 +204,8 @@ module.exports = function(crowi, app) {
       if (!user) { return next() }
       if (!user) { return next() }
       req.logIn(user, (err) => {
       req.logIn(user, (err) => {
         if (err) { return next() }
         if (err) { return next() }
-        else {
-          return loginSuccess(req, res, user);
-        }
+
+        return loginSuccess(req, res, user);
       });
       });
     })(req, res, next);
     })(req, res, next);
   };
   };
@@ -239,9 +235,9 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     const userInfo = {
     const userInfo = {
-      'id': response.id,
-      'username': response.displayName,
-      'name': `${response.name.givenName} ${response.name.familyName}`
+      id: response.id,
+      username: response.displayName,
+      name: `${response.name.givenName} ${response.name.familyName}`,
     };
     };
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
     if (!externalAccount) {
     if (!externalAccount) {
@@ -251,7 +247,7 @@ module.exports = function(crowi, app) {
     const user = await externalAccount.getPopulatedUser();
     const user = await externalAccount.getPopulatedUser();
 
 
     // login
     // login
-    req.logIn(user, err => {
+    req.logIn(user, (err) => {
       if (err) { return next(err) }
       if (err) { return next(err) }
       return loginSuccess(req, res, user);
       return loginSuccess(req, res, user);
     });
     });
@@ -280,9 +276,9 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     const userInfo = {
     const userInfo = {
-      'id': response.id,
-      'username': response.username,
-      'name': response.displayName
+      id: response.id,
+      username: response.username,
+      name: response.displayName,
     };
     };
 
 
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
@@ -293,7 +289,7 @@ module.exports = function(crowi, app) {
     const user = await externalAccount.getPopulatedUser();
     const user = await externalAccount.getPopulatedUser();
 
 
     // login
     // login
-    req.logIn(user, err => {
+    req.logIn(user, (err) => {
       if (err) { return next(err) }
       if (err) { return next(err) }
       return loginSuccess(req, res, user);
       return loginSuccess(req, res, user);
     });
     });
@@ -322,9 +318,9 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     const userInfo = {
     const userInfo = {
-      'id': response.id,
-      'username': response.username,
-      'name': response.displayName
+      id: response.id,
+      username: response.username,
+      name: response.displayName,
     };
     };
 
 
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
@@ -335,7 +331,7 @@ module.exports = function(crowi, app) {
     const user = await externalAccount.getPopulatedUser();
     const user = await externalAccount.getPopulatedUser();
 
 
     // login
     // login
-    req.logIn(user, err => {
+    req.logIn(user, (err) => {
       if (err) { return next(err) }
       if (err) { return next(err) }
       return loginSuccess(req, res, user);
       return loginSuccess(req, res, user);
     });
     });
@@ -369,16 +365,16 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     const userInfo = {
     const userInfo = {
-      'id': response[attrMapId],
-      'username': response[attrMapUsername],
-      'email': response[attrMapMail]
+      id: response[attrMapId],
+      username: response[attrMapUsername],
+      email: response[attrMapMail],
     };
     };
 
 
     // determine name
     // determine name
     const firstName = response[attrMapFirstName];
     const firstName = response[attrMapFirstName];
     const lastName = response[attrMapLastName];
     const lastName = response[attrMapLastName];
     if (firstName != null || lastName != null) {
     if (firstName != null || lastName != null) {
-      userInfo['name'] = `${response[attrMapFirstName]} ${response[attrMapLastName]}`.trim();
+      userInfo.name = `${response[attrMapFirstName]} ${response[attrMapLastName]}`.trim();
     }
     }
 
 
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
     const externalAccount = await getOrCreateUser(req, res, userInfo, providerId);
@@ -389,7 +385,7 @@ module.exports = function(crowi, app) {
     const user = await externalAccount.getPopulatedUser();
     const user = await externalAccount.getPopulatedUser();
 
 
     // login
     // login
-    req.logIn(user, err => {
+    req.logIn(user, (err) => {
       if (err != null) {
       if (err != null) {
         logger.error(err);
         logger.error(err);
         return loginFailure(req, res);
         return loginFailure(req, res);
@@ -401,8 +397,8 @@ module.exports = function(crowi, app) {
   const promisifiedPassportAuthentication = (strategyName, req, res) => {
   const promisifiedPassportAuthentication = (strategyName, req, res) => {
     return new Promise((resolve, reject) => {
     return new Promise((resolve, reject) => {
       passport.authenticate(strategyName, (err, response, info) => {
       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
+        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 ---`);
         logger.debug(`--- authenticate with ${strategyName} strategy ---`);
@@ -444,21 +440,22 @@ module.exports = function(crowi, app) {
       return externalAccount;
       return externalAccount;
     }
     }
     catch (err) {
     catch (err) {
+      /* eslint-disable no-else-return */
       if (err.name === 'DuplicatedUsernameException') {
       if (err.name === 'DuplicatedUsernameException') {
         if (isSameEmailTreatedAsIdenticalUser || isSameUsernameTreatedAsIdenticalUser) {
         if (isSameEmailTreatedAsIdenticalUser || isSameUsernameTreatedAsIdenticalUser) {
           // associate to existing user
           // associate to existing user
           debug(`ExternalAccount '${userInfo.username}' will be created and bound to the exisiting User account`);
           debug(`ExternalAccount '${userInfo.username}' will be created and bound to the exisiting User account`);
           return ExternalAccount.associate(providerId, userInfo.id, err.user);
           return ExternalAccount.associate(providerId, userInfo.id, err.user);
         }
         }
-        else {
-          req.flash('provider-DuplicatedUsernameException', providerId);
-          return;
-        }
+
+        req.flash('provider-DuplicatedUsernameException', providerId);
+        return;
       }
       }
       else if (err.name === 'UserUpperLimitException') {
       else if (err.name === 'UserUpperLimitException') {
         req.flash('warningMessage', 'Can not register more than the maximum number of users.');
         req.flash('warningMessage', 'Can not register more than the maximum number of users.');
         return;
         return;
       }
       }
+      /* eslint-enable no-else-return */
     }
     }
   };
   };
 
 

+ 96 - 98
src/server/routes/login.js

@@ -1,24 +1,22 @@
-module.exports = function(crowi, app) {
-  'use strict';
+// disable all of linting
+// because this file is a deprecated legacy of Crowi
+
+/* eslint-disable */
 
 
-  const debug = require('debug')('growi:routes:login')
-    , logger = require('@alias/logger')('growi:routes:login')
-    , path = require('path')
-    , async    = require('async')
-    , config = crowi.getConfig()
-    , mailer = crowi.getMailer()
-    , User = crowi.model('User')
-    , Config = crowi.model('Config')
-    , actions = {};
+module.exports = function(crowi, app) {
+  const debug = require('debug')('growi:routes:login');
+  const logger = require('@alias/logger')('growi:routes:login');
+  const path = require('path');
+  const async = require('async');
+  const config = crowi.getConfig();
+  const mailer = crowi.getMailer();
+  const User = crowi.model('User');
+  const Config = crowi.model('Config');
 
 
+  const actions = {};
 
 
   const clearGoogleSession = function(req) {
   const clearGoogleSession = function(req) {
-    req.session.googleAuthCode
-      = req.session.googleId
-      = req.session.googleEmail
-      = req.session.googleName
-      = req.session.googleImage
-      = null;
+    req.session.googleAuthCode = req.session.googleId = req.session.googleEmail = req.session.googleName = req.session.googleImage = null;
   };
   };
   const loginSuccess = function(req, res, userData) {
   const loginSuccess = function(req, res, userData) {
     req.user = req.session.user = userData;
     req.user = req.session.user = userData;
@@ -41,9 +39,8 @@ module.exports = function(crowi, app) {
       req.session.jumpTo = null;
       req.session.jumpTo = null;
       return res.redirect(jumpTo);
       return res.redirect(jumpTo);
     }
     }
-    else {
-      return res.redirect('/');
-    }
+
+    return res.redirect('/');
   };
   };
 
 
   const loginFailure = function(req, res) {
   const loginFailure = function(req, res) {
@@ -52,7 +49,7 @@ module.exports = function(crowi, app) {
   };
   };
 
 
   actions.googleCallback = function(req, res) {
   actions.googleCallback = function(req, res) {
-    var nextAction = req.session.googleCallbackAction || '/login';
+    const nextAction = req.session.googleCallbackAction || '/login';
     debug('googleCallback.nextAction', nextAction);
     debug('googleCallback.nextAction', nextAction);
     req.session.googleAuthCode = req.query.code || '';
     req.session.googleAuthCode = req.query.code || '';
     debug('google auth code', req.query.code);
     debug('google auth code', req.query.code);
@@ -62,10 +59,10 @@ module.exports = function(crowi, app) {
   };
   };
 
 
   actions.error = function(req, res) {
   actions.error = function(req, res) {
-    var reason = req.params.reason
-      , reasonMessage = ''
-      ;
+    const reason = req.params.reason;
+
 
 
+    let reasonMessage = '';
     if (reason === 'suspended') {
     if (reason === 'suspended') {
       reasonMessage = 'This account is suspended.';
       reasonMessage = 'This account is suspended.';
     }
     }
@@ -74,17 +71,17 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     return res.render('login/error', {
     return res.render('login/error', {
-      reason: reason,
-      reasonMessage: reasonMessage
+      reason,
+      reasonMessage,
     });
     });
   };
   };
 
 
   actions.login = function(req, res) {
   actions.login = function(req, res) {
-    var loginForm = req.body.loginForm;
+    const loginForm = req.body.loginForm;
 
 
     if (req.method == 'POST' && req.form.isValid) {
     if (req.method == 'POST' && req.form.isValid) {
-      var username = loginForm.username;
-      var password = loginForm.password;
+      const username = loginForm.username;
+      const password = loginForm.password;
 
 
       // find user
       // find user
       User.findUserByUsernameOrEmail(username, password, (err, user) => {
       User.findUserByUsernameOrEmail(username, password, (err, user) => {
@@ -106,11 +103,11 @@ module.exports = function(crowi, app) {
   };
   };
 
 
   actions.loginGoogle = function(req, res) {
   actions.loginGoogle = function(req, res) {
-    var googleAuth = require('../util/googleAuth')(crowi);
-    var code = req.session.googleAuthCode || null;
+    const googleAuth = require('../util/googleAuth')(crowi);
+    const code = req.session.googleAuthCode || null;
 
 
     if (!code) {
     if (!code) {
-      googleAuth.createAuthUrl(req, function(err, redirectUrl) {
+      googleAuth.createAuthUrl(req, (err, redirectUrl) => {
         if (err) {
         if (err) {
           // TODO
           // TODO
         }
         }
@@ -120,14 +117,14 @@ module.exports = function(crowi, app) {
       });
       });
     }
     }
     else {
     else {
-      googleAuth.handleCallback(req, function(err, tokenInfo) {
+      googleAuth.handleCallback(req, (err, tokenInfo) => {
         debug('handleCallback', err, tokenInfo);
         debug('handleCallback', err, tokenInfo);
         if (err) {
         if (err) {
           return loginFailure(req, res);
           return loginFailure(req, res);
         }
         }
 
 
-        var googleId = tokenInfo.user_id;
-        User.findUserByGoogleId(googleId, function(err, userData) {
+        const googleId = tokenInfo.user_id;
+        User.findUserByGoogleId(googleId, (err, userData) => {
           debug('findUserByGoogleId', err, userData);
           debug('findUserByGoogleId', err, userData);
           if (!userData) {
           if (!userData) {
             clearGoogleSession(req);
             clearGoogleSession(req);
@@ -140,7 +137,7 @@ module.exports = function(crowi, app) {
   };
   };
 
 
   actions.register = function(req, res) {
   actions.register = function(req, res) {
-    var googleAuth = require('../util/googleAuth')(crowi);
+    const googleAuth = require('../util/googleAuth')(crowi);
 
 
     // ログイン済みならさようなら
     // ログイン済みならさようなら
     if (req.user) {
     if (req.user) {
@@ -153,18 +150,18 @@ module.exports = function(crowi, app) {
     }
     }
 
 
     if (req.method == 'POST' && req.form.isValid) {
     if (req.method == 'POST' && req.form.isValid) {
-      var registerForm = req.form.registerForm || {};
+      const registerForm = req.form.registerForm || {};
 
 
-      var name = registerForm.name;
-      var username = registerForm.username;
-      var email = registerForm.email;
-      var password = registerForm.password;
+      const name = registerForm.name;
+      const username = registerForm.username;
+      const email = registerForm.email;
+      const password = registerForm.password;
       var googleId = registerForm.googleId || null;
       var googleId = registerForm.googleId || null;
       var googleImage = registerForm.googleImage || null;
       var googleImage = registerForm.googleImage || null;
 
 
       // email と username の unique チェックする
       // email と username の unique チェックする
-      User.isRegisterable(email, username, function(isRegisterable, errOn) {
-        var isError = false;
+      User.isRegisterable(email, username, (isRegisterable, errOn) => {
+        let isError = false;
         if (!User.isEmailValid(email)) {
         if (!User.isEmailValid(email)) {
           isError = true;
           isError = true;
           req.flash('registerWarningMessage', 'This email address could not be used. (Make sure the allowed email address)');
           req.flash('registerWarningMessage', 'This email address could not be used. (Make sure the allowed email address)');
@@ -178,14 +175,13 @@ module.exports = function(crowi, app) {
             isError = true;
             isError = true;
             req.flash('registerWarningMessage', 'This email address is already registered.');
             req.flash('registerWarningMessage', 'This email address is already registered.');
           }
           }
-
         }
         }
         if (isError) {
         if (isError) {
           debug('isError user register error', errOn);
           debug('isError user register error', errOn);
           return res.redirect('/register');
           return res.redirect('/register');
         }
         }
 
 
-        User.createUserByEmailAndPassword(name, username, email, password, undefined, function(err, userData) {
+        User.createUserByEmailAndPassword(name, username, email, password, undefined, (err, userData) => {
           if (err) {
           if (err) {
             if (err.name === 'UserUpperLimitException') {
             if (err.name === 'UserUpperLimitException') {
               req.flash('registerWarningMessage', 'Can not register more than the maximum number of users.');
               req.flash('registerWarningMessage', 'Can not register more than the maximum number of users.');
@@ -195,74 +191,72 @@ module.exports = function(crowi, app) {
             }
             }
             return res.redirect('/register');
             return res.redirect('/register');
           }
           }
-          else {
 
 
-            // 作成後、承認が必要なモードなら、管理者に通知する
-            const appTitle = Config.appTitle(config);
-            if (config.crowi['security:registrationMode'] === Config.SECURITY_REGISTRATION_MODE_RESTRICTED) {
-              // TODO send mail
-              User.findAdmins(function(err, admins) {
-                async.each(
-                  admins,
-                  function(adminUser, next) {
-                    mailer.send({
-                      to: adminUser.email,
-                      subject: '[' + appTitle + ':admin] A New User Created and Waiting for Activation',
-                      template: path.join(crowi.localeDir, 'en-US/admin/userWaitingActivation.txt'),
-                      vars: {
-                        createdUser: userData,
-                        adminUser: adminUser,
-                        url: crowi.configManager.getSiteUrl(),
-                        appTitle: appTitle,
-                      }
+
+          // 作成後、承認が必要なモードなら、管理者に通知する
+          const appTitle = Config.appTitle(config);
+          if (config.crowi['security:registrationMode'] === Config.SECURITY_REGISTRATION_MODE_RESTRICTED) {
+            // TODO send mail
+            User.findAdmins((err, admins) => {
+              async.each(
+                admins,
+                (adminUser, next) => {
+                  mailer.send({
+                    to: adminUser.email,
+                    subject: `[${appTitle}:admin] A New User Created and Waiting for Activation`,
+                    template: path.join(crowi.localeDir, 'en-US/admin/userWaitingActivation.txt'),
+                    vars: {
+                      createdUser: userData,
+                      adminUser,
+                      url: crowi.configManager.getSiteUrl(),
+                      appTitle,
                     },
                     },
-                    function(err, s) {
-                      debug('completed to send email: ', err, s);
-                      next();
-                    }
-                    );
                   },
                   },
-                  function(err) {
-                    debug('Sending invitation email completed.', err);
-                  }
-                );
-              });
-            }
-
-            if (googleId) {
-              userData.updateGoogleId(googleId, function(err, userData) {
-                if (err) { // TODO
-                }
-                return loginSuccess(req, res, userData);
-              });
-            }
-            else {
-              // add a flash message to inform the user that processing was successful -- 2017.09.23 Yuki Takei
-              // cz. loginSuccess method doesn't work on it's own when using passport
-              //      because `req.login()` prepared by passport is not called.
-              req.flash('successMessage', `The user '${userData.username}' is successfully created.`);
+                  (err, s) => {
+                    debug('completed to send email: ', err, s);
+                    next();
+                  });
+                },
+                (err) => {
+                  debug('Sending invitation email completed.', err);
+                },
+              );
+            });
+          }
 
 
+          if (googleId) {
+            userData.updateGoogleId(googleId, (err, userData) => {
+              if (err) { // TODO
+              }
               return loginSuccess(req, res, userData);
               return loginSuccess(req, res, userData);
-            }
+            });
+          }
+          else {
+            // add a flash message to inform the user that processing was successful -- 2017.09.23 Yuki Takei
+            // cz. loginSuccess method doesn't work on it's own when using passport
+            //      because `req.login()` prepared by passport is not called.
+            req.flash('successMessage', `The user '${userData.username}' is successfully created.`);
+
+            return loginSuccess(req, res, userData);
           }
           }
         });
         });
       });
       });
     }
     }
     else { // method GET of form is not valid
     else { // method GET of form is not valid
       debug('session is', req.session);
       debug('session is', req.session);
-      var isRegistering = true;
+      const isRegistering = true;
       // google callback を受ける可能性もある
       // google callback を受ける可能性もある
-      var code = req.session.googleAuthCode || null;
+      const code = req.session.googleAuthCode || null;
       var googleId = req.session.googleId || null;
       var googleId = req.session.googleId || null;
-      var googleEmail = req.session.googleEmail || null;
-      var googleName = req.session.googleName || null;
+      let googleEmail = req.session.googleEmail || null;
+      let googleName = req.session.googleName || null;
       var googleImage = req.session.googleImage || null;
       var googleImage = req.session.googleImage || null;
 
 
       debug('register. if code', code);
       debug('register. if code', code);
       // callback 経由で reigster にアクセスしてきた時最初だけこの if に入る
       // callback 経由で reigster にアクセスしてきた時最初だけこの if に入る
       // code から email などを取得したらそれを session にいれて code は消去
       // code から email などを取得したらそれを session にいれて code は消去
       if (code) {
       if (code) {
-        googleAuth.handleCallback(req, function(err, tokenInfo) {
+        googleAuth.handleCallback(req, (err, tokenInfo) => {
           debug('tokenInfo on register GET', tokenInfo);
           debug('tokenInfo on register GET', tokenInfo);
           req.session.googleAuthCode = null;
           req.session.googleAuthCode = null;
 
 
@@ -280,18 +274,22 @@ module.exports = function(crowi, app) {
             req.flash('registerWarningMessage', 'このメールアドレスのGoogleアカウントはコネクトできません。');
             req.flash('registerWarningMessage', 'このメールアドレスのGoogleアカウントはコネクトできません。');
             return res.redirect('/login?register=1');
             return res.redirect('/login?register=1');
           }
           }
-          return res.render('login', { isRegistering, googleId, googleEmail, googleName, googleImage, });
+          return res.render('login', {
+            isRegistering, googleId, googleEmail, googleName, googleImage,
+          });
         });
         });
       }
       }
       else {
       else {
-        return res.render('login', { isRegistering, googleId, googleEmail, googleName, googleImage, });
+        return res.render('login', {
+          isRegistering, googleId, googleEmail, googleName, googleImage,
+        });
       }
       }
     }
     }
   };
   };
 
 
   actions.registerGoogle = function(req, res) {
   actions.registerGoogle = function(req, res) {
-    var googleAuth = require('../util/googleAuth')(crowi);
-    googleAuth.createAuthUrl(req, function(err, redirectUrl) {
+    const googleAuth = require('../util/googleAuth')(crowi);
+    googleAuth.createAuthUrl(req, (err, redirectUrl) => {
       if (err) {
       if (err) {
         // TODO
         // TODO
       }
       }

+ 2 - 3
src/server/routes/logout.js

@@ -1,9 +1,8 @@
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
   return {
   return {
-    logout: function(req, res) {
-
+    logout(req, res) {
       req.session.destroy();
       req.session.destroy();
       return res.redirect('/');
       return res.redirect('/');
-    }
+    },
   };
   };
 };
 };

+ 92 - 99
src/server/routes/me.js

@@ -1,19 +1,17 @@
 module.exports = function(crowi, app) {
 module.exports = function(crowi, app) {
-  'use strict';
-
-  var debug = require('debug')('growi:routes:me')
-    , fs = require('fs')
-    , models = crowi.models
-    , config = crowi.getConfig()
-    , User = models.User
-    , UserGroupRelation = models.UserGroupRelation
-    , ExternalAccount = models.ExternalAccount
-    , ApiResponse = require('../util/apiResponse')
-    //, pluginService = require('../service/plugin')
-    , actions = {}
-    , api = {}
-    ;
+  const debug = require('debug')('growi:routes:me');
+  const logger = require('@alias/logger')('growi:routes:me');
+  const models = crowi.models;
+  const User = models.User;
+  const UserGroupRelation = models.UserGroupRelation;
+  const ExternalAccount = models.ExternalAccount;
+  const ApiResponse = require('../util/apiResponse');
 
 
+  // , pluginService = require('../service/plugin')
+
+  const actions = {};
+
+  const api = {};
   actions.api = api;
   actions.api = api;
 
 
   /**
   /**
@@ -23,20 +21,20 @@ module.exports = function(crowi, app) {
    */
    */
   api.userGroupRelations = function(req, res) {
   api.userGroupRelations = function(req, res) {
     UserGroupRelation.findAllRelationForUser(req.user)
     UserGroupRelation.findAllRelationForUser(req.user)
-      .then(userGroupRelations => {
-        return res.json(ApiResponse.success({userGroupRelations}));
+      .then((userGroupRelations) => {
+        return res.json(ApiResponse.success({ userGroupRelations }));
       });
       });
   };
   };
 
 
   actions.index = function(req, res) {
   actions.index = function(req, res) {
-    var userForm = req.body.userForm;
-    var userData = req.user;
+    const userForm = req.body.userForm;
+    const userData = req.user;
 
 
-    if (req.method == 'POST' && req.form.isValid) {
-      var name = userForm.name;
-      var email = userForm.email;
-      var lang = userForm.lang;
-      var isEmailPublished = userForm.isEmailPublished;
+    if (req.method === 'POST' && req.form.isValid) {
+      const name = userForm.name;
+      const email = userForm.email;
+      const lang = userForm.lang;
+      const isEmailPublished = userForm.isEmailPublished;
 
 
       /*
       /*
        * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
        * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
@@ -48,10 +46,12 @@ module.exports = function(crowi, app) {
       */
       */
 
 
       User.findOneAndUpdate(
       User.findOneAndUpdate(
-        { email: userData.email },                  // query
-        { name, email, lang, isEmailPublished },                      // updating data
-        { runValidators: true, context: 'query' },  // for validation
-        //   see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
+        /* eslint-disable object-curly-newline */
+        { email: userData.email }, //                   query
+        { name, email, lang, isEmailPublished }, //     updating data
+        { runValidators: true, context: 'query' }, //   for validation
+        // see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
+        /* eslint-enable object-curly-newline */
         (err) => {
         (err) => {
           if (err) {
           if (err) {
             Object.keys(err.errors).forEach((e) => {
             Object.keys(err.errors).forEach((e) => {
@@ -63,8 +63,8 @@ module.exports = function(crowi, app) {
           req.i18n.changeLanguage(lang);
           req.i18n.changeLanguage(lang);
           req.flash('successMessage', req.t('Updated'));
           req.flash('successMessage', req.t('Updated'));
           return res.redirect('/me');
           return res.redirect('/me');
-        });
-
+        },
+      );
     }
     }
     else { // method GET
     else { // method GET
       /*
       /*
@@ -86,23 +86,25 @@ module.exports = function(crowi, app) {
       // do nothing
       // do nothing
       return;
       return;
     }
     }
-    else if (!req.form.isValid) {
+    if (!req.form.isValid) {
       req.flash('errorMessage', req.form.errors.join('\n'));
       req.flash('errorMessage', req.form.errors.join('\n'));
       return;
       return;
     }
     }
 
 
-    var imagetypeForm = req.body.imagetypeForm;
-    var userData = req.user;
+    const imagetypeForm = req.body.imagetypeForm;
+    const userData = req.user;
 
 
-    var isGravatarEnabled = imagetypeForm.isGravatarEnabled;
+    const isGravatarEnabled = imagetypeForm.isGravatarEnabled;
 
 
-    userData.updateIsGravatarEnabled(isGravatarEnabled, function(err, userData) {
+    userData.updateIsGravatarEnabled(isGravatarEnabled, (err, userData) => {
       if (err) {
       if (err) {
-        for (var e in err.errors) {
+        /* eslint-disable no-restricted-syntax, no-prototype-builtins */
+        for (const e in err.errors) {
           if (err.errors.hasOwnProperty(e)) {
           if (err.errors.hasOwnProperty(e)) {
             req.form.errors.push(err.errors[e].message);
             req.form.errors.push(err.errors[e].message);
           }
           }
         }
         }
+        /* eslint-enable no-restricted-syntax, no-prototype-builtins */
         return res.render('me/index', {});
         return res.render('me/index', {});
       }
       }
 
 
@@ -115,20 +117,19 @@ module.exports = function(crowi, app) {
   actions.externalAccounts.list = function(req, res) {
   actions.externalAccounts.list = function(req, res) {
     const userData = req.user;
     const userData = req.user;
 
 
-    let renderVars = {};
-    ExternalAccount.find({user: userData})
+    const renderVars = {};
+    ExternalAccount.find({ user: userData })
       .then((externalAccounts) => {
       .then((externalAccounts) => {
         renderVars.externalAccounts = externalAccounts;
         renderVars.externalAccounts = externalAccounts;
         return;
         return;
       })
       })
       .then(() => {
       .then(() => {
-        if (req.method == 'POST' && req.form.isValid) {
+        if (req.method === 'POST' && req.form.isValid) {
           // TODO impl
           // TODO impl
           return res.render('me/external-accounts', renderVars);
           return res.render('me/external-accounts', renderVars);
         }
         }
-        else { // method GET
-          return res.render('me/external-accounts', renderVars);
-        }
+        // method GET
+        return res.render('me/external-accounts', renderVars);
       });
       });
   };
   };
 
 
@@ -150,7 +151,7 @@ module.exports = function(crowi, app) {
         resolve(true);
         resolve(true);
       }
       }
       else {
       else {
-        ExternalAccount.count({user: userData})
+        ExternalAccount.count({ user: userData })
           .then((count) => {
           .then((count) => {
             resolve(count > 1);
             resolve(count > 1);
           });
           });
@@ -158,7 +159,7 @@ module.exports = function(crowi, app) {
     })
     })
     .then((isDisassociatable) => {
     .then((isDisassociatable) => {
       if (!isDisassociatable) {
       if (!isDisassociatable) {
-        let e = new Error();
+        const e = new Error();
         e.name = 'couldntDisassociateError';
         e.name = 'couldntDisassociateError';
         throw e;
         throw e;
       }
       }
@@ -166,27 +167,24 @@ module.exports = function(crowi, app) {
       const providerType = req.body.providerType;
       const providerType = req.body.providerType;
       const accountId = req.body.accountId;
       const accountId = req.body.accountId;
 
 
-      return ExternalAccount.findOneAndRemove({providerType, accountId, user: userData});
+      return ExternalAccount.findOneAndRemove({ providerType, accountId, user: userData });
     })
     })
     .then((account) => {
     .then((account) => {
       if (account == null) {
       if (account == null) {
         return redirectWithFlash('errorMessage', 'ExternalAccount not found.');
         return redirectWithFlash('errorMessage', 'ExternalAccount not found.');
       }
       }
-      else {
-        return redirectWithFlash('successMessage', 'Successfully disassociated.');
-      }
+
+      return redirectWithFlash('successMessage', 'Successfully disassociated.');
     })
     })
     .catch((err) => {
     .catch((err) => {
       if (err) {
       if (err) {
-        if (err.name == 'couldntDisassociateError') {
+        if (err.name === 'couldntDisassociateError') {
           return redirectWithFlash('couldntDisassociateError', true);
           return redirectWithFlash('couldntDisassociateError', true);
         }
         }
-        else {
-          return redirectWithFlash('errorMessage', err.message);
-        }
+
+        return redirectWithFlash('errorMessage', err.message);
       }
       }
     });
     });
-
   };
   };
 
 
   actions.externalAccounts.associateLdap = function(req, res) {
   actions.externalAccounts.associateLdap = function(req, res) {
@@ -203,15 +201,13 @@ module.exports = function(crowi, app) {
       return redirectWithFlash('warning', 'LdapStrategy has not been set up');
       return redirectWithFlash('warning', 'LdapStrategy has not been set up');
     }
     }
 
 
-    const loginForm = req.body.loginForm;
-
     passport.authenticate('ldapauth', (err, user, info) => {
     passport.authenticate('ldapauth', (err, user, info) => {
-      if (res.headersSent) {  // dirty hack -- 2017.09.25
-        return;               // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
+      if (res.headersSent) { // dirty hack -- 2017.09.25
+        return; //              cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
       }
       }
 
 
-      if (err) {  // DB Error
-        console.log('LDAP Server Error: ', err);
+      if (err) { // DB Error
+        logger.error('LDAP Server Error: ', err);
         return redirectWithFlash('warningMessage', 'LDAP Server Error occured.');
         return redirectWithFlash('warningMessage', 'LDAP Server Error occured.');
       }
       }
       if (info && info.message) {
       if (info && info.message) {
@@ -229,16 +225,13 @@ module.exports = function(crowi, app) {
           .catch((err) => {
           .catch((err) => {
             return redirectWithFlash('errorMessage', err.message);
             return redirectWithFlash('errorMessage', err.message);
           });
           });
-
       }
       }
     })(req, res, () => {});
     })(req, res, () => {});
-
-
   };
   };
 
 
   actions.password = function(req, res) {
   actions.password = function(req, res) {
-    var passwordForm = req.body.mePassword;
-    var userData = req.user;
+    const passwordForm = req.body.mePassword;
+    const userData = req.user;
 
 
     /*
     /*
       * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
       * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
@@ -250,10 +243,10 @@ module.exports = function(crowi, app) {
     }
     }
     */
     */
 
 
-    if (req.method == 'POST' && req.form.isValid) {
-      var newPassword = passwordForm.newPassword;
-      var newPasswordConfirm = passwordForm.newPasswordConfirm;
-      var oldPassword = passwordForm.oldPassword;
+    if (req.method === 'POST' && req.form.isValid) {
+      const newPassword = passwordForm.newPassword;
+      const newPasswordConfirm = passwordForm.newPasswordConfirm;
+      const oldPassword = passwordForm.oldPassword;
 
 
       if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
       if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
         req.form.errors.push('Wrong current password');
         req.form.errors.push('Wrong current password');
@@ -262,19 +255,21 @@ module.exports = function(crowi, app) {
       }
       }
 
 
       // check password confirm
       // check password confirm
-      if (newPassword != newPasswordConfirm) {
+      if (newPassword !== newPasswordConfirm) {
         req.form.errors.push('Failed to verify passwords');
         req.form.errors.push('Failed to verify passwords');
       }
       }
       else {
       else {
-        userData.updatePassword(newPassword, function(err, userData) {
+        userData.updatePassword(newPassword, (err, userData) => {
           if (err) {
           if (err) {
-            for (var e in err.errors) {
+            /* eslint-disable no-restricted-syntax, no-prototype-builtins */
+            for (const e in err.errors) {
               if (err.errors.hasOwnProperty(e)) {
               if (err.errors.hasOwnProperty(e)) {
                 req.form.errors.push(err.errors[e].message);
                 req.form.errors.push(err.errors[e].message);
               }
               }
             }
             }
             return res.render('me/password', {});
             return res.render('me/password', {});
           }
           }
+          /* eslint-enable no-restricted-syntax, no-prototype-builtins */
 
 
           req.flash('successMessage', 'Password updated');
           req.flash('successMessage', 'Password updated');
           return res.redirect('/me/password');
           return res.redirect('/me/password');
@@ -288,17 +283,16 @@ module.exports = function(crowi, app) {
   };
   };
 
 
   actions.apiToken = function(req, res) {
   actions.apiToken = function(req, res) {
-    var apiTokenForm = req.body.apiTokenForm;
-    var userData = req.user;
+    const userData = req.user;
 
 
-    if (req.method == 'POST' && req.form.isValid) {
+    if (req.method === 'POST' && req.form.isValid) {
       userData.updateApiToken()
       userData.updateApiToken()
-      .then(function(userData) {
+      .then((userData) => {
         req.flash('successMessage', 'API Token updated');
         req.flash('successMessage', 'API Token updated');
         return res.redirect('/me/apiToken');
         return res.redirect('/me/apiToken');
       })
       })
-      .catch(function(err) {
-        //req.flash('successMessage',);
+      .catch((err) => {
+        // req.flash('successMessage',);
         req.form.errors.push('Failed to update API Token');
         req.form.errors.push('Failed to update API Token');
         return res.render('me/api_token', {
         return res.render('me/api_token', {
         });
         });
@@ -316,21 +310,21 @@ module.exports = function(crowi, app) {
   };
   };
 
 
   actions.authGoogle = function(req, res) {
   actions.authGoogle = function(req, res) {
-    var googleAuth = require('../util/googleAuth')(crowi);
+    const googleAuth = require('../util/googleAuth')(crowi);
 
 
-    var userData = req.user;
+    const userData = req.user;
 
 
-    var toDisconnect = req.body.disconnectGoogle ? true : false;
-    var toConnect = req.body.connectGoogle ? true : false;
+    const toDisconnect = !!req.body.disconnectGoogle;
+    const toConnect = !!req.body.connectGoogle;
     if (toDisconnect) {
     if (toDisconnect) {
-      userData.deleteGoogleId(function(err, userData) {
+      userData.deleteGoogleId((err, userData) => {
         req.flash('successMessage', 'Disconnected from Google account');
         req.flash('successMessage', 'Disconnected from Google account');
 
 
         return res.redirect('/me');
         return res.redirect('/me');
       });
       });
     }
     }
     else if (toConnect) {
     else if (toConnect) {
-      googleAuth.createAuthUrl(req, function(err, redirectUrl) {
+      googleAuth.createAuthUrl(req, (err, redirectUrl) => {
         if (err) {
         if (err) {
           // TODO
           // TODO
         }
         }
@@ -345,40 +339,39 @@ module.exports = function(crowi, app) {
   };
   };
 
 
   actions.authGoogleCallback = function(req, res) {
   actions.authGoogleCallback = function(req, res) {
-    var googleAuth = require('../util/googleAuth')(crowi);
-    var userData = req.user;
+    const googleAuth = require('../util/googleAuth')(crowi);
+    const userData = req.user;
 
 
-    googleAuth.handleCallback(req, function(err, tokenInfo) {
+    googleAuth.handleCallback(req, (err, tokenInfo) => {
       if (err) {
       if (err) {
         req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
         req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
         return res.redirect('/me'); // TODO Handling
         return res.redirect('/me'); // TODO Handling
       }
       }
 
 
-      var googleId = tokenInfo.user_id;
-      var googleEmail = tokenInfo.email;
+      const googleId = tokenInfo.user_id;
+      const googleEmail = tokenInfo.email;
       if (!User.isEmailValid(googleEmail)) {
       if (!User.isEmailValid(googleEmail)) {
         req.flash('warningMessage.auth.google', 'You can\'t connect with this  Google\'s account');
         req.flash('warningMessage.auth.google', 'You can\'t connect with this  Google\'s account');
         return res.redirect('/me');
         return res.redirect('/me');
       }
       }
 
 
-      User.findUserByGoogleId(googleId, function(err, googleUser) {
+      User.findUserByGoogleId(googleId, (err, googleUser) => {
         if (!err && googleUser) {
         if (!err && googleUser) {
           req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
           req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
           return res.redirect('/me');
           return res.redirect('/me');
         }
         }
-        else {
-          userData.updateGoogleId(googleId, function(err, userData) {
-            if (err) {
-              debug('Failed to updateGoogleId', err);
-              req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
-              return res.redirect('/me');
-            }
 
 
-            // TODO if err
-            req.flash('successMessage', 'Connected with Google');
+        userData.updateGoogleId(googleId, (err, userData) => {
+          if (err) {
+            debug('Failed to updateGoogleId', err);
+            req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
             return res.redirect('/me');
             return res.redirect('/me');
-          });
-        }
+          }
+
+          // TODO if err
+          req.flash('successMessage', 'Connected with Google');
+          return res.redirect('/me');
+        });
       });
       });
     });
     });
   };
   };