admin.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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/markdonw' , admin.markdonw.index);
  76. actions.markdown = {};
  77. actions.markdown.index = function(req, res) {
  78. var config = crowi.getConfig();
  79. var markdownSetting = Config.setupCofigFormData('markdown', config);
  80. return res.render('admin/markdown', {
  81. markdownSetting: markdownSetting,
  82. });
  83. };
  84. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  85. actions.markdown.lineBreaksSetting = function(req, res) {
  86. var markdownSetting = req.form.markdownSetting;
  87. req.session.markdownSetting = markdownSetting;
  88. if (req.form.isValid) {
  89. Config.updateNamespaceByArray('markdown', markdownSetting, function(err, config) {
  90. Config.updateConfigCache('markdown', config);
  91. req.session.markdownSetting = null;
  92. req.flash('successMessage', ['Successfully updated!']);
  93. return res.redirect('/admin/markdown');
  94. });
  95. } else {
  96. req.flash('errorMessage', req.form.errors);
  97. return res.redirect('/admin/markdown');
  98. }
  99. };
  100. // app.get('/admin/customize' , admin.customize.index);
  101. actions.customize = {};
  102. actions.customize.index = function(req, res) {
  103. var settingForm;
  104. settingForm = Config.setupCofigFormData('crowi', req.config);
  105. return res.render('admin/customize', {
  106. settingForm: settingForm,
  107. });
  108. };
  109. // app.get('/admin/notification' , admin.notification.index);
  110. actions.notification = {};
  111. actions.notification.index = function(req, res) {
  112. var config = crowi.getConfig();
  113. var UpdatePost = crowi.model('UpdatePost');
  114. var slackSetting = Config.setupCofigFormData('notification', config);
  115. var hasSlackAppConfig = Config.hasSlackAppConfig(config);
  116. var hasSlackIwhUrl = Config.hasSlackIwhUrl(config);
  117. var hasSlackToken = Config.hasSlackToken(config);
  118. var slack = crowi.slack;
  119. var slackAuthUrl = '';
  120. if (!Config.hasSlackAppConfig(req.config)) {
  121. slackSetting['slack:clientId'] = '';
  122. slackSetting['slack:clientSecret'] = '';
  123. }
  124. else {
  125. slackAuthUrl = slack.getAuthorizeURL();
  126. }
  127. if (!Config.hasSlackIwhUrl(req.config)) {
  128. slackSetting['slack:incomingWebhookUrl'] = '';
  129. }
  130. if (req.session.slackSetting) {
  131. slackSetting = req.session.slackSetting;
  132. req.session.slackSetting = null;
  133. }
  134. UpdatePost.findAll()
  135. .then(function(settings) {
  136. return res.render('admin/notification', {
  137. settings,
  138. slackSetting,
  139. hasSlackAppConfig,
  140. hasSlackIwhUrl,
  141. hasSlackToken,
  142. slackAuthUrl
  143. });
  144. });
  145. };
  146. // app.post('/admin/notification/slackSetting' , admin.notification.slackSetting);
  147. actions.notification.slackSetting = function(req, res) {
  148. var slackSetting = req.form.slackSetting;
  149. req.session.slackSetting = slackSetting;
  150. if (req.form.isValid) {
  151. Config.updateNamespaceByArray('notification', slackSetting, function(err, config) {
  152. Config.updateConfigCache('notification', config);
  153. req.flash('successMessage', ['Successfully Updated!']);
  154. req.session.slackSetting = null;
  155. // Re-setup
  156. crowi.setupSlack().then(function() {
  157. return res.redirect('/admin/notification');
  158. });
  159. });
  160. } else {
  161. req.flash('errorMessage', req.form.errors);
  162. return res.redirect('/admin/notification');
  163. }
  164. };
  165. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  166. actions.notification.slackAuth = function(req, res) {
  167. var code = req.query.code;
  168. var config = crowi.getConfig();
  169. if (!code || !Config.hasSlackAppConfig(req.config)) {
  170. return res.redirect('/admin/notification');
  171. }
  172. var slack = crowi.slack;
  173. var bot = slack.initAppBot(true);
  174. var args = {
  175. code,
  176. client_id: config.notification['slack:clientId'],
  177. client_secret: config.notification['slack:clientSecret'],
  178. }
  179. bot.api.oauth.access(args, function(err, data) {
  180. debug('oauth response', err, data);
  181. if (!data.ok || !data.access_token) {
  182. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  183. return res.redirect('/admin/notification');
  184. } else {
  185. Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
  186. if (err) {
  187. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  188. } else {
  189. Config.updateConfigCache('notification', config);
  190. req.flash('successMessage', ['Successfully Connected!']);
  191. }
  192. slack.initAppBot();
  193. return res.redirect('/admin/notification');
  194. });
  195. }
  196. });
  197. };
  198. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  199. actions.notification.disconnectFromSlack = function(req, res) {
  200. const config = crowi.getConfig();
  201. const slack = crowi.slack;
  202. Config.updateNamespaceByArray('notification', {'slack:token': ''}, function(err, config) {
  203. Config.updateConfigCache('notification', config);
  204. req.flash('successMessage', ['Successfully Disconnected!']);
  205. slack.initAppBot();
  206. return res.redirect('/admin/notification');
  207. });
  208. };
  209. actions.search = {};
  210. actions.search.index = function(req, res) {
  211. var search = crowi.getSearcher();
  212. if (!search) {
  213. return res.redirect('/admin');
  214. }
  215. return res.render('admin/search', {
  216. });
  217. };
  218. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  219. actions.notification.slackIwhSetting = function(req, res) {
  220. var slackIwhSetting = req.form.slackIwhSetting;
  221. if (req.form.isValid) {
  222. Config.updateNamespaceByArray('notification', slackIwhSetting, function(err, config) {
  223. Config.updateConfigCache('notification', config);
  224. req.flash('successMessage', ['Successfully Updated!']);
  225. // Re-setup
  226. crowi.setupSlack().then(function() {
  227. return res.redirect('/admin/notification#slack-incoming-webhooks');
  228. });
  229. });
  230. } else {
  231. req.flash('errorMessage', req.form.errors);
  232. return res.redirect('/admin/notification#slack-incoming-webhooks');
  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. return Page.removePageByPath(`/user/${username}`)
  380. .then(() => userData);
  381. })
  382. .then((userData) => {
  383. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  384. return res.redirect('/admin/users');
  385. })
  386. .catch((err) => {
  387. req.flash('errorMessage', '削除に失敗しました。');
  388. return res.redirect('/admin/users');
  389. });
  390. };
  391. // これやったときの relation の挙動未確認
  392. actions.user.removeCompletely = function(req, res) {
  393. // ユーザーの物理削除
  394. var id = req.params.id;
  395. User.removeCompletelyById(id, function(err, removed) {
  396. if (err) {
  397. debug('Error while removing user.', err, id);
  398. req.flash('errorMessage', '完全な削除に失敗しました。');
  399. } else {
  400. req.flash('successMessage', '削除しました');
  401. }
  402. return res.redirect('/admin/users');
  403. });
  404. };
  405. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  406. actions.user.resetPassword = function(req, res) {
  407. const id = req.body.user_id;
  408. const User = crowi.model('User');
  409. User.resetPasswordByRandomString(id)
  410. .then(function(data) {
  411. data.user = User.filterToPublicFields(data.user);
  412. return res.json(ApiResponse.success(data));
  413. }).catch(function(err) {
  414. debug('Error on reseting password', err);
  415. return res.json(ApiResponse.error('Error'));
  416. });
  417. }
  418. actions.api = {};
  419. actions.api.appSetting = function(req, res) {
  420. var form = req.form.settingForm;
  421. if (req.form.isValid) {
  422. debug('form content', form);
  423. // mail setting ならここで validation
  424. if (form['mail:from']) {
  425. validateMailSetting(req, form, function(err, data) {
  426. debug('Error validate mail setting: ', err, data);
  427. if (err) {
  428. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  429. return res.json({status: false, message: req.form.errors.join('\n')});
  430. }
  431. return saveSetting(req, res, form);
  432. });
  433. } else {
  434. return saveSetting(req, res, form);
  435. }
  436. } else {
  437. return res.json({status: false, message: req.form.errors.join('\n')});
  438. }
  439. };
  440. actions.api.customizeSetting = function(req, res) {
  441. var form = req.form.settingForm;
  442. if (req.form.isValid) {
  443. debug('form content', form);
  444. return saveSetting(req, res, form);
  445. } else {
  446. return res.json({status: false, message: req.form.errors.join('\n')});
  447. }
  448. }
  449. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  450. actions.api.notificationAdd = function(req, res) {
  451. var UpdatePost = crowi.model('UpdatePost');
  452. var pathPattern = req.body.pathPattern;
  453. var channel = req.body.channel;
  454. debug('notification.add', pathPattern, channel);
  455. UpdatePost.create(pathPattern, channel, req.user)
  456. .then(function(doc) {
  457. debug('Successfully save updatePost', doc);
  458. // fixme: うーん
  459. doc.creator = doc.creator._id.toString();
  460. return res.json(ApiResponse.success({updatePost: doc}));
  461. }).catch(function(err) {
  462. debug('Failed to save updatePost', err);
  463. return res.json(ApiResponse.error());
  464. });
  465. };
  466. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  467. actions.api.notificationRemove = function(req, res) {
  468. var UpdatePost = crowi.model('UpdatePost');
  469. var id = req.body.id;
  470. UpdatePost.remove(id)
  471. .then(function() {
  472. debug('Successfully remove updatePost');
  473. return res.json(ApiResponse.success({}));
  474. }).catch(function(err) {
  475. debug('Failed to remove updatePost', err);
  476. return res.json(ApiResponse.error());
  477. });
  478. };
  479. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  480. actions.api.usersSearch = function(req, res) {
  481. const User = crowi.model('User');
  482. const email =req.query.email;
  483. User.findUsersByPartOfEmail(email, {})
  484. .then(users => {
  485. const result = {
  486. data: users
  487. };
  488. return res.json(ApiResponse.success(result));
  489. }).catch(err => {
  490. return res.json(ApiResponse.error());
  491. });
  492. };
  493. function saveSetting(req, res, form)
  494. {
  495. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  496. Config.updateConfigCache('crowi', config);
  497. return res.json({status: true});
  498. });
  499. }
  500. function validateMailSetting(req, form, callback)
  501. {
  502. var mailer = crowi.mailer;
  503. var option = {
  504. host: form['mail:smtpHost'],
  505. port: form['mail:smtpPort'],
  506. };
  507. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  508. option.auth = {
  509. user: form['mail:smtpUser'],
  510. pass: form['mail:smtpPassword'],
  511. };
  512. }
  513. if (option.port === 465) {
  514. option.secure = true;
  515. }
  516. var smtpClient = mailer.createSMTPClient(option);
  517. debug('mailer setup for validate SMTP setting', smtpClient);
  518. smtpClient.sendMail({
  519. to: req.user.email,
  520. subject: 'Wiki管理設定のアップデートによるメール通知',
  521. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  522. }, callback);
  523. }
  524. return actions;
  525. };