admin.js 18 KB

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