admin.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('crowi:routes:admin')
  4. , models = crowi.models
  5. , Page = models.Page
  6. , User = models.User
  7. , ExternalAccount = models.ExternalAccount
  8. , Config = models.Config
  9. , PluginUtils = require('../plugins/plugin-utils')
  10. , pluginUtils = new PluginUtils()
  11. , ApiResponse = require('../util/apiResponse')
  12. , MAX_PAGE_LIST = 5
  13. , actions = {};
  14. function createPager(total, limit, page, pagesCount, maxPageList) {
  15. const pager = {
  16. page: page,
  17. pagesCount: pagesCount,
  18. pages: [],
  19. total: total,
  20. previous: null,
  21. previousDots: false,
  22. next: null,
  23. nextDots: false,
  24. };
  25. if (page > 1) {
  26. pager.previous = page - 1;
  27. }
  28. if (page < pagesCount) {
  29. pager.next = page + 1;
  30. }
  31. let pagerMin = Math.max(1, Math.ceil(page - maxPageList/2));
  32. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList/2));
  33. if (pagerMin === 1) {
  34. if (MAX_PAGE_LIST < pagesCount) {
  35. pagerMax = MAX_PAGE_LIST;
  36. } else {
  37. pagerMax = pagesCount;
  38. }
  39. }
  40. if (pagerMax === pagesCount) {
  41. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  42. pagerMin = 1;
  43. } else {
  44. pagerMin = pagerMax - MAX_PAGE_LIST;
  45. }
  46. }
  47. pager.previousDots = null;
  48. if (pagerMin > 1) {
  49. pager.previousDots = true;
  50. }
  51. pager.nextDots = null;
  52. if (pagerMax < pagesCount) {
  53. pager.nextDots = true;
  54. }
  55. for (let i = pagerMin; i <= pagerMax; i++) {
  56. pager.pages.push(i);
  57. }
  58. return pager;
  59. }
  60. actions.index = function(req, res) {
  61. return res.render('admin/index', {
  62. plugins: pluginUtils.listPlugins(crowi.rootDir),
  63. });
  64. };
  65. // app.get('/admin/app' , admin.app.index);
  66. actions.app = {};
  67. actions.app.index = function(req, res) {
  68. var settingForm;
  69. settingForm = Config.setupCofigFormData('crowi', req.config);
  70. return res.render('admin/app', {
  71. settingForm: settingForm,
  72. });
  73. };
  74. actions.app.settingUpdate = function(req, res) {
  75. };
  76. // app.get('/admin/security' , admin.security.index);
  77. actions.security = {};
  78. actions.security.index = function(req, res) {
  79. var settingForm;
  80. settingForm = Config.setupCofigFormData('crowi', req.config);
  81. return res.render('admin/security', { settingForm });
  82. };
  83. // app.get('/admin/markdown' , admin.markdown.index);
  84. actions.markdown = {};
  85. actions.markdown.index = function(req, res) {
  86. var config = crowi.getConfig();
  87. var markdownSetting = Config.setupCofigFormData('markdown', config);
  88. return res.render('admin/markdown', {
  89. markdownSetting: markdownSetting,
  90. });
  91. };
  92. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  93. actions.markdown.lineBreaksSetting = function(req, res) {
  94. var markdownSetting = req.form.markdownSetting;
  95. req.session.markdownSetting = markdownSetting;
  96. if (req.form.isValid) {
  97. Config.updateNamespaceByArray('markdown', markdownSetting, function(err, config) {
  98. Config.updateConfigCache('markdown', config);
  99. req.session.markdownSetting = null;
  100. req.flash('successMessage', ['Successfully updated!']);
  101. return res.redirect('/admin/markdown');
  102. });
  103. } else {
  104. req.flash('errorMessage', req.form.errors);
  105. return res.redirect('/admin/markdown');
  106. }
  107. };
  108. // app.get('/admin/customize' , admin.customize.index);
  109. actions.customize = {};
  110. actions.customize.index = function(req, res) {
  111. var settingForm;
  112. settingForm = Config.setupCofigFormData('crowi', req.config);
  113. return res.render('admin/customize', {
  114. settingForm: settingForm,
  115. });
  116. };
  117. // app.get('/admin/notification' , admin.notification.index);
  118. actions.notification = {};
  119. actions.notification.index = function(req, res) {
  120. var config = crowi.getConfig();
  121. var UpdatePost = crowi.model('UpdatePost');
  122. var slackSetting = Config.setupCofigFormData('notification', config);
  123. var hasSlackWebClientConfig = Config.hasSlackWebClientConfig(config);
  124. var hasSlackIwhUrl = Config.hasSlackIwhUrl(config);
  125. var hasSlackToken = Config.hasSlackToken(config);
  126. var slack = crowi.slack;
  127. var slackAuthUrl = '';
  128. if (!Config.hasSlackWebClientConfig(req.config)) {
  129. slackSetting['slack:clientId'] = '';
  130. slackSetting['slack:clientSecret'] = '';
  131. }
  132. else {
  133. slackAuthUrl = slack.getAuthorizeURL();
  134. }
  135. if (!Config.hasSlackIwhUrl(req.config)) {
  136. slackSetting['slack:incomingWebhookUrl'] = '';
  137. }
  138. if (req.session.slackSetting) {
  139. slackSetting = req.session.slackSetting;
  140. req.session.slackSetting = null;
  141. }
  142. UpdatePost.findAll()
  143. .then(function(settings) {
  144. return res.render('admin/notification', {
  145. settings,
  146. slackSetting,
  147. hasSlackWebClientConfig,
  148. hasSlackIwhUrl,
  149. hasSlackToken,
  150. slackAuthUrl
  151. });
  152. });
  153. };
  154. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  155. actions.notification.slackSetting = function(req, res) {
  156. var slackSetting = req.form.slackSetting;
  157. req.session.slackSetting = slackSetting;
  158. if (req.form.isValid) {
  159. Config.updateNamespaceByArray('notification', slackSetting, function(err, config) {
  160. Config.updateConfigCache('notification', config);
  161. req.flash('successMessage', ['Successfully Updated!']);
  162. req.session.slackSetting = null;
  163. // Re-setup
  164. crowi.setupSlack().then(function() {
  165. return res.redirect('/admin/notification');
  166. });
  167. });
  168. } else {
  169. req.flash('errorMessage', req.form.errors);
  170. return res.redirect('/admin/notification');
  171. }
  172. };
  173. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  174. actions.notification.slackAuth = function(req, res) {
  175. const code = req.query.code;
  176. const config = crowi.getConfig();
  177. if (!code || !Config.hasSlackConfig(req.config)) {
  178. return res.redirect('/admin/notification');
  179. }
  180. const slack = crowi.slack;
  181. slack.getOauthAccessToken(code)
  182. .then(data => {
  183. debug('oauth response', data);
  184. Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
  185. if (err) {
  186. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  187. } else {
  188. Config.updateConfigCache('notification', config);
  189. req.flash('successMessage', ['Successfully Connected!']);
  190. }
  191. return res.redirect('/admin/notification');
  192. });
  193. }).catch(err => {
  194. debug('oauth response ERROR', err);
  195. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  196. return res.redirect('/admin/notification');
  197. });
  198. };
  199. actions.search = {};
  200. actions.search.index = function(req, res) {
  201. var search = crowi.getSearcher();
  202. if (!search) {
  203. return res.redirect('/admin');
  204. }
  205. return res.render('admin/search', {
  206. });
  207. };
  208. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  209. actions.notification.slackIwhSetting = function(req, res) {
  210. var slackIwhSetting = req.form.slackIwhSetting;
  211. if (req.form.isValid) {
  212. Config.updateNamespaceByArray('notification', slackIwhSetting, function(err, config) {
  213. Config.updateConfigCache('notification', config);
  214. req.flash('successMessage', ['Successfully Updated!']);
  215. // Re-setup
  216. crowi.setupSlack().then(function() {
  217. return res.redirect('/admin/notification#slack-incoming-webhooks');
  218. });
  219. });
  220. } else {
  221. req.flash('errorMessage', req.form.errors);
  222. return res.redirect('/admin/notification#slack-incoming-webhooks');
  223. }
  224. };
  225. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  226. actions.notification.disconnectFromSlack = function(req, res) {
  227. const config = crowi.getConfig();
  228. const slack = crowi.slack;
  229. Config.updateNamespaceByArray('notification', {'slack:token': ''}, function(err, config) {
  230. Config.updateConfigCache('notification', config);
  231. req.flash('successMessage', ['Successfully Disconnected!']);
  232. return res.redirect('/admin/notification');
  233. });
  234. };
  235. actions.search.buildIndex = function(req, res) {
  236. var search = crowi.getSearcher();
  237. if (!search) {
  238. return res.redirect('/admin');
  239. }
  240. return new Promise(function(resolve, reject) {
  241. search.deleteIndex()
  242. .then(function(data) {
  243. debug('Index deleted.');
  244. resolve();
  245. }).catch(function(err) {
  246. debug('Delete index Error, but if it is initialize, its ok.', err);
  247. resolve();
  248. });
  249. })
  250. .then(function() {
  251. return search.buildIndex()
  252. })
  253. .then(function(data) {
  254. if (!data.errors) {
  255. debug('Index created.');
  256. }
  257. return search.addAllPages();
  258. })
  259. .then(function(data) {
  260. if (!data.errors) {
  261. debug('Data is successfully indexed.');
  262. req.flash('successMessage', 'Data is successfully indexed.');
  263. } else {
  264. debug('Data index error.', data.errors);
  265. req.flash('errorMessage', `Data index error: ${data.errors}`);
  266. }
  267. return res.redirect('/admin/search');
  268. })
  269. .catch(function(err) {
  270. debug('Error', err);
  271. req.flash('errorMessage', `Error: ${err}`);
  272. return res.redirect('/admin/search');
  273. });
  274. };
  275. actions.user = {};
  276. actions.user.index = function(req, res) {
  277. var page = parseInt(req.query.page) || 1;
  278. User.findUsersWithPagination({page: page}, function(err, result) {
  279. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  280. return res.render('admin/users', {
  281. users: result.docs,
  282. pager: pager
  283. });
  284. });
  285. };
  286. actions.user.invite = function(req, res) {
  287. var form = req.form.inviteForm;
  288. var toSendEmail = form.sendEmail || false;
  289. if (req.form.isValid) {
  290. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, function(err, userList) {
  291. if (err) {
  292. req.flash('errorMessage', req.form.errors.join('\n'));
  293. } else {
  294. req.flash('createdUser', userList);
  295. }
  296. return res.redirect('/admin/users');
  297. });
  298. } else {
  299. req.flash('errorMessage', req.form.errors.join('\n'));
  300. return res.redirect('/admin/users');
  301. }
  302. };
  303. actions.user.makeAdmin = function(req, res) {
  304. var id = req.params.id;
  305. User.findById(id, function(err, userData) {
  306. userData.makeAdmin(function(err, userData) {
  307. if (err === null) {
  308. req.flash('successMessage', userData.name + 'さんのアカウントを管理者に設定しました。');
  309. } else {
  310. req.flash('errorMessage', '更新に失敗しました。');
  311. debug(err, userData);
  312. }
  313. return res.redirect('/admin/users');
  314. });
  315. });
  316. };
  317. actions.user.removeFromAdmin = function(req, res) {
  318. var id = req.params.id;
  319. User.findById(id, function(err, userData) {
  320. userData.removeFromAdmin(function(err, userData) {
  321. if (err === null) {
  322. req.flash('successMessage', userData.name + 'さんのアカウントを管理者から外しました。');
  323. } else {
  324. req.flash('errorMessage', '更新に失敗しました。');
  325. debug(err, userData);
  326. }
  327. return res.redirect('/admin/users');
  328. });
  329. });
  330. };
  331. actions.user.activate = function(req, res) {
  332. var id = req.params.id;
  333. User.findById(id, function(err, userData) {
  334. userData.statusActivate(function(err, userData) {
  335. if (err === null) {
  336. req.flash('successMessage', userData.name + 'さんのアカウントを有効化しました');
  337. } else {
  338. req.flash('errorMessage', '更新に失敗しました。');
  339. debug(err, userData);
  340. }
  341. return res.redirect('/admin/users');
  342. });
  343. });
  344. };
  345. actions.user.suspend = function(req, res) {
  346. var id = req.params.id;
  347. User.findById(id, function(err, userData) {
  348. userData.statusSuspend(function(err, userData) {
  349. if (err === null) {
  350. req.flash('successMessage', userData.name + 'さんのアカウントを利用停止にしました');
  351. } else {
  352. req.flash('errorMessage', '更新に失敗しました。');
  353. debug(err, userData);
  354. }
  355. return res.redirect('/admin/users');
  356. });
  357. });
  358. };
  359. actions.user.remove = function(req, res) {
  360. var id = req.params.id;
  361. let username = '';
  362. return new Promise((resolve, reject) => {
  363. User.findById(id, (err, userData) => {
  364. username = userData.username;
  365. return resolve(userData);
  366. });
  367. })
  368. .then((userData) => {
  369. return new Promise((resolve, reject) => {
  370. userData.statusDelete((err, userData) => {
  371. if (err) {
  372. reject(err);
  373. }
  374. resolve(userData);
  375. });
  376. });
  377. })
  378. .then((userData) => {
  379. // remove all External Accounts
  380. ExternalAccount.remove({user: userData})
  381. .then((err) => {
  382. if (err) {
  383. throw new Error(err.message);
  384. }
  385. return userData;
  386. })
  387. })
  388. .then((userData) => {
  389. return Page.removePageByPath(`/user/${username}`)
  390. .then(() => userData);
  391. })
  392. .then((userData) => {
  393. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  394. return res.redirect('/admin/users');
  395. })
  396. .catch((err) => {
  397. req.flash('errorMessage', '削除に失敗しました。');
  398. return res.redirect('/admin/users');
  399. });
  400. };
  401. // これやったときの relation の挙動未確認
  402. actions.user.removeCompletely = function(req, res) {
  403. // ユーザーの物理削除
  404. var id = req.params.id;
  405. User.removeCompletelyById(id, function(err, removed) {
  406. if (err) {
  407. debug('Error while removing user.', err, id);
  408. req.flash('errorMessage', '完全な削除に失敗しました。');
  409. } else {
  410. req.flash('successMessage', '削除しました');
  411. }
  412. return res.redirect('/admin/users');
  413. });
  414. };
  415. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  416. actions.user.resetPassword = function(req, res) {
  417. const id = req.body.user_id;
  418. const User = crowi.model('User');
  419. User.resetPasswordByRandomString(id)
  420. .then(function(data) {
  421. data.user = User.filterToPublicFields(data.user);
  422. return res.json(ApiResponse.success(data));
  423. }).catch(function(err) {
  424. debug('Error on reseting password', err);
  425. return res.json(ApiResponse.error('Error'));
  426. });
  427. }
  428. actions.externalAccount = {};
  429. actions.externalAccount.index = function(req, res) {
  430. const page = parseInt(req.query.page) || 1;
  431. ExternalAccount.findAllWithPagination({page})
  432. .then((result) => {
  433. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  434. return res.render('admin/external-accounts', {
  435. accounts: result.docs,
  436. pager: pager
  437. })
  438. });
  439. };
  440. actions.externalAccount.remove = function(req, res) {
  441. const accountId = req.params.id;
  442. ExternalAccount.findOneAndRemove({accountId})
  443. .then((result) => {
  444. if (result == null) {
  445. req.flash('errorMessage', '削除に失敗しました。');
  446. return res.redirect('/admin/users/external-accounts');
  447. }
  448. else {
  449. req.flash('successMessage', `外部アカウント '${accountId}' を削除しました`);
  450. return res.redirect('/admin/users/external-accounts');
  451. }
  452. });
  453. };
  454. actions.api = {};
  455. actions.api.appSetting = function(req, res) {
  456. var form = req.form.settingForm;
  457. if (req.form.isValid) {
  458. debug('form content', form);
  459. // mail setting ならここで validation
  460. if (form['mail:from']) {
  461. validateMailSetting(req, form, function(err, data) {
  462. debug('Error validate mail setting: ', err, data);
  463. if (err) {
  464. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  465. return res.json({status: false, message: req.form.errors.join('\n')});
  466. }
  467. return saveSetting(req, res, form);
  468. });
  469. } else {
  470. return saveSetting(req, res, form);
  471. }
  472. } else {
  473. return res.json({status: false, message: req.form.errors.join('\n')});
  474. }
  475. };
  476. actions.api.securitySetting = function(req, res) {
  477. var form = req.form.settingForm;
  478. if (req.form.isValid) {
  479. debug('form content', form);
  480. return saveSetting(req, res, form);
  481. } else {
  482. return res.json({status: false, message: req.form.errors.join('\n')});
  483. }
  484. };
  485. actions.api.securityPassportLdapSetting = function(req, res) {
  486. var form = req.form.settingForm;
  487. if (!req.form.isValid) {
  488. return res.json({status: false, message: req.form.errors.join('\n')});
  489. }
  490. debug('form content', form);
  491. return saveSettingAsync(form)
  492. .then(() => {
  493. const config = crowi.getConfig();
  494. // reset strategy
  495. crowi.passportService.resetLdapStrategy();
  496. // setup strategy
  497. if (Config.isEnabledPassportLdap(config)) {
  498. crowi.passportService.setupLdapStrategy(true);
  499. }
  500. return;
  501. })
  502. .then(() => {
  503. res.json({status: true});
  504. });
  505. };
  506. actions.api.customizeSetting = function(req, res) {
  507. var form = req.form.settingForm;
  508. if (req.form.isValid) {
  509. debug('form content', form);
  510. return saveSetting(req, res, form);
  511. } else {
  512. return res.json({status: false, message: req.form.errors.join('\n')});
  513. }
  514. }
  515. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  516. actions.api.notificationAdd = function(req, res) {
  517. var UpdatePost = crowi.model('UpdatePost');
  518. var pathPattern = req.body.pathPattern;
  519. var channel = req.body.channel;
  520. debug('notification.add', pathPattern, channel);
  521. UpdatePost.create(pathPattern, channel, req.user)
  522. .then(function(doc) {
  523. debug('Successfully save updatePost', doc);
  524. // fixme: うーん
  525. doc.creator = doc.creator._id.toString();
  526. return res.json(ApiResponse.success({updatePost: doc}));
  527. }).catch(function(err) {
  528. debug('Failed to save updatePost', err);
  529. return res.json(ApiResponse.error());
  530. });
  531. };
  532. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  533. actions.api.notificationRemove = function(req, res) {
  534. var UpdatePost = crowi.model('UpdatePost');
  535. var id = req.body.id;
  536. UpdatePost.remove(id)
  537. .then(function() {
  538. debug('Successfully remove updatePost');
  539. return res.json(ApiResponse.success({}));
  540. }).catch(function(err) {
  541. debug('Failed to remove updatePost', err);
  542. return res.json(ApiResponse.error());
  543. });
  544. };
  545. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  546. actions.api.usersSearch = function(req, res) {
  547. const User = crowi.model('User');
  548. const email =req.query.email;
  549. User.findUsersByPartOfEmail(email, {})
  550. .then(users => {
  551. const result = {
  552. data: users
  553. };
  554. return res.json(ApiResponse.success(result));
  555. }).catch(err => {
  556. return res.json(ApiResponse.error());
  557. });
  558. };
  559. /**
  560. * save settings, update config cache, and response json
  561. *
  562. * @param {any} req
  563. * @param {any} res
  564. * @param {any} form
  565. */
  566. function saveSetting(req, res, form)
  567. {
  568. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  569. Config.updateConfigCache('crowi', config);
  570. return res.json({status: true});
  571. });
  572. }
  573. /**
  574. * save settings, update config cache ONLY. (this method don't response json)
  575. *
  576. * @param {any} form
  577. * @returns
  578. */
  579. function saveSettingAsync(form) {
  580. return new Promise((resolve, reject) => {
  581. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  582. if (err) {
  583. return reject(err)
  584. };
  585. Config.updateConfigCache('crowi', config);
  586. return resolve();
  587. });
  588. });
  589. }
  590. function validateMailSetting(req, form, callback)
  591. {
  592. var mailer = crowi.mailer;
  593. var option = {
  594. host: form['mail:smtpHost'],
  595. port: form['mail:smtpPort'],
  596. };
  597. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  598. option.auth = {
  599. user: form['mail:smtpUser'],
  600. pass: form['mail:smtpPassword'],
  601. };
  602. }
  603. if (option.port === 465) {
  604. option.secure = true;
  605. }
  606. var smtpClient = mailer.createSMTPClient(option);
  607. debug('mailer setup for validate SMTP setting', smtpClient);
  608. smtpClient.sendMail({
  609. to: req.user.email,
  610. subject: 'Wiki管理設定のアップデートによるメール通知',
  611. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  612. }, callback);
  613. }
  614. return actions;
  615. };