admin.js 19 KB

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