admin.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. };
  62. // app.get('/admin/app' , admin.app.index);
  63. actions.app = {};
  64. actions.app.index = function(req, res) {
  65. var settingForm;
  66. settingForm = Config.setupCofigFormData('crowi', req.config);
  67. return res.render('admin/app', {
  68. settingForm: settingForm,
  69. plugins: pluginUtils.listPlugins(crowi.rootDir),
  70. });
  71. };
  72. actions.app.settingUpdate = function(req, res) {
  73. };
  74. // app.get('/admin/markdonw' , admin.markdonw.index);
  75. actions.markdown = {};
  76. actions.markdown.index = function(req, res) {
  77. var config = crowi.getConfig();
  78. var markdownSetting = Config.setupCofigFormData('markdown', config);
  79. return res.render('admin/markdown', {
  80. markdownSetting: markdownSetting,
  81. });
  82. };
  83. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  84. actions.markdown.lineBreaksSetting = function(req, res) {
  85. var markdownSetting = req.form.markdownSetting;
  86. req.session.markdownSetting = markdownSetting;
  87. if (req.form.isValid) {
  88. Config.updateNamespaceByArray('markdown', markdownSetting, function(err, config) {
  89. Config.updateConfigCache('markdown', config);
  90. req.session.markdownSetting = null;
  91. req.flash('successMessage', ['Successfully updated!']);
  92. return res.redirect('/admin/markdown');
  93. });
  94. } else {
  95. req.flash('errorMessage', req.form.errors);
  96. return res.redirect('/admin/markdown');
  97. }
  98. };
  99. // app.get('/admin/notification' , admin.notification.index);
  100. actions.notification = {};
  101. actions.notification.index = function(req, res) {
  102. var config = crowi.getConfig();
  103. var UpdatePost = crowi.model('UpdatePost');
  104. var slackSetting = Config.setupCofigFormData('notification', config);
  105. var hasSlackConfig = Config.hasSlackConfig(config);
  106. var hasSlackToken = Config.hasSlackToken(config);
  107. var slack = crowi.slack;
  108. var slackAuthUrl = '';
  109. if (!Config.hasSlackConfig(req.config)) {
  110. slackSetting['slack:clientId'] = '';
  111. slackSetting['slack:clientSecret'] = '';
  112. } else {
  113. slackAuthUrl = slack.getAuthorizeURL();
  114. }
  115. if (req.session.slackSetting) {
  116. slackSetting = req.session.slackSetting;
  117. req.session.slackSetting = null;
  118. }
  119. UpdatePost.findAll()
  120. .then(function(settings) {
  121. return res.render('admin/notification', {
  122. settings,
  123. slackSetting,
  124. hasSlackConfig,
  125. hasSlackToken,
  126. slackAuthUrl
  127. });
  128. });
  129. };
  130. // app.post('/admin/notification/slackSetting' , admin.notification.slackSetting);
  131. actions.notification.slackSetting = function(req, res) {
  132. var slackSetting = req.form.slackSetting;
  133. req.session.slackSetting = slackSetting;
  134. if (req.form.isValid) {
  135. Config.updateNamespaceByArray('notification', slackSetting, function(err, config) {
  136. Config.updateConfigCache('notification', config);
  137. req.session.slackSetting = null;
  138. crowi.setupSlack().then(function() {
  139. return res.redirect('/admin/notification');
  140. });
  141. });
  142. } else {
  143. req.flash('errorMessage', req.form.errors);
  144. return res.redirect('/admin/notification');
  145. }
  146. };
  147. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  148. actions.notification.slackAuth = function(req, res) {
  149. var code = req.query.code;
  150. var config = crowi.getConfig();
  151. if (!code || !Config.hasSlackConfig(req.config)) {
  152. return res.redirect('/admin/notification');
  153. }
  154. var slack = crowi.slack;
  155. var bot = slack.createBot();
  156. bot.api.oauth.access({code}, function(err, data) {
  157. debug('oauth response', err, data);
  158. if (!data.ok || !data.access_token) {
  159. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  160. return res.redirect('/admin/notification');
  161. } else {
  162. Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
  163. if (err) {
  164. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  165. } else {
  166. Config.updateConfigCache('notification', config);
  167. req.flash('successMessage', ['Successfully Connected!']);
  168. }
  169. slack.createBot();
  170. return res.redirect('/admin/notification');
  171. });
  172. }
  173. });
  174. };
  175. actions.search = {};
  176. actions.search.index = function(req, res) {
  177. var search = crowi.getSearcher();
  178. if (!search) {
  179. return res.redirect('/admin');
  180. }
  181. return res.render('admin/search', {
  182. });
  183. };
  184. actions.search.buildIndex = function(req, res) {
  185. var search = crowi.getSearcher();
  186. if (!search) {
  187. return res.redirect('/admin');
  188. }
  189. Promise.resolve().then(function() {
  190. return new Promise(function(resolve, reject) {
  191. search.deleteIndex()
  192. .then(function(data) {
  193. debug('Index deleted.');
  194. resolve();
  195. }).catch(function(err) {
  196. debug('Delete index Error, but if it is initialize, its ok.', err);
  197. resolve();
  198. });
  199. });
  200. }).then(function() {
  201. search.buildIndex()
  202. .then(function(data) {
  203. if (!data.errors) {
  204. debug('Index created.');
  205. }
  206. return search.addAllPages();
  207. })
  208. .then(function(data) {
  209. if (!data.errors) {
  210. debug('Data is successfully indexed.');
  211. } else {
  212. debug('Data index error.', data.errors);
  213. }
  214. })
  215. .catch(function(err) {
  216. debug('Error', err);
  217. });
  218. req.flash('successMessage', 'Now re-building index ... this takes a while.');
  219. return res.redirect('/admin/search');
  220. });
  221. };
  222. actions.user = {};
  223. actions.user.index = function(req, res) {
  224. var page = parseInt(req.query.page) || 1;
  225. User.findUsersWithPagination({page: page}, function(err, result) {
  226. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  227. return res.render('admin/users', {
  228. users: result.docs,
  229. pager: pager
  230. });
  231. });
  232. };
  233. actions.user.invite = function(req, res) {
  234. var form = req.form.inviteForm;
  235. var toSendEmail = form.sendEmail || false;
  236. if (req.form.isValid) {
  237. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, function(err, userList) {
  238. if (err) {
  239. req.flash('errorMessage', req.form.errors.join('\n'));
  240. } else {
  241. req.flash('createdUser', userList);
  242. }
  243. return res.redirect('/admin/users');
  244. });
  245. } else {
  246. req.flash('errorMessage', req.form.errors.join('\n'));
  247. return res.redirect('/admin/users');
  248. }
  249. };
  250. actions.user.makeAdmin = function(req, res) {
  251. var id = req.params.id;
  252. User.findById(id, function(err, userData) {
  253. userData.makeAdmin(function(err, userData) {
  254. if (err === null) {
  255. req.flash('successMessage', userData.name + 'さんのアカウントを管理者に設定しました。');
  256. } else {
  257. req.flash('errorMessage', '更新に失敗しました。');
  258. debug(err, userData);
  259. }
  260. return res.redirect('/admin/users');
  261. });
  262. });
  263. };
  264. actions.user.removeFromAdmin = function(req, res) {
  265. var id = req.params.id;
  266. User.findById(id, function(err, userData) {
  267. userData.removeFromAdmin(function(err, userData) {
  268. if (err === null) {
  269. req.flash('successMessage', userData.name + 'さんのアカウントを管理者から外しました。');
  270. } else {
  271. req.flash('errorMessage', '更新に失敗しました。');
  272. debug(err, userData);
  273. }
  274. return res.redirect('/admin/users');
  275. });
  276. });
  277. };
  278. actions.user.activate = function(req, res) {
  279. var id = req.params.id;
  280. User.findById(id, function(err, userData) {
  281. userData.statusActivate(function(err, userData) {
  282. if (err === null) {
  283. req.flash('successMessage', userData.name + 'さんのアカウントを承認しました');
  284. } else {
  285. req.flash('errorMessage', '更新に失敗しました。');
  286. debug(err, userData);
  287. }
  288. return res.redirect('/admin/users');
  289. });
  290. });
  291. };
  292. actions.user.suspend = function(req, res) {
  293. var id = req.params.id;
  294. User.findById(id, function(err, userData) {
  295. userData.statusSuspend(function(err, userData) {
  296. if (err === null) {
  297. req.flash('successMessage', userData.name + 'さんのアカウントを利用停止にしました');
  298. } else {
  299. req.flash('errorMessage', '更新に失敗しました。');
  300. debug(err, userData);
  301. }
  302. return res.redirect('/admin/users');
  303. });
  304. });
  305. };
  306. actions.user.remove = function(req, res) {
  307. // 未実装
  308. return res.redirect('/admin/users');
  309. };
  310. // これやったときの relation の挙動未確認
  311. actions.user.removeCompletely = function(req, res) {
  312. // ユーザーの物理削除
  313. var id = req.params.id;
  314. User.removeCompletelyById(id, function(err, removed) {
  315. if (err) {
  316. debug('Error while removing user.', err, id);
  317. req.flash('errorMessage', '完全な削除に失敗しました。');
  318. } else {
  319. req.flash('successMessage', '削除しました');
  320. }
  321. return res.redirect('/admin/users');
  322. });
  323. };
  324. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  325. actions.user.resetPassword = function(req, res) {
  326. const id = req.body.user_id;
  327. const User = crowi.model('User');
  328. User.resetPasswordByRandomString(id)
  329. .then(function(data) {
  330. data.user = User.filterToPublicFields(data.user);
  331. return res.json(ApiResponse.success(data));
  332. }).catch(function(err) {
  333. debug('Error on reseting password', err);
  334. return res.json(ApiResponse.error('Error'));
  335. });
  336. }
  337. actions.api = {};
  338. actions.api.appSetting = function(req, res) {
  339. var form = req.form.settingForm;
  340. if (req.form.isValid) {
  341. debug('form content', form);
  342. // mail setting ならここで validation
  343. if (form['mail:from']) {
  344. validateMailSetting(req, form, function(err, data) {
  345. debug('Error validate mail setting: ', err, data);
  346. if (err) {
  347. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  348. return res.json({status: false, message: req.form.errors.join('\n')});
  349. }
  350. return saveSetting(req, res, form);
  351. });
  352. } else {
  353. return saveSetting(req, res, form);
  354. }
  355. } else {
  356. return res.json({status: false, message: req.form.errors.join('\n')});
  357. }
  358. };
  359. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  360. actions.api.notificationAdd = function(req, res) {
  361. var UpdatePost = crowi.model('UpdatePost');
  362. var pathPattern = req.body.pathPattern;
  363. var channel = req.body.channel;
  364. debug('notification.add', pathPattern, channel);
  365. UpdatePost.create(pathPattern, channel, req.user)
  366. .then(function(doc) {
  367. debug('Successfully save updatePost', doc);
  368. // fixme: うーん
  369. doc.creator = doc.creator._id.toString();
  370. return res.json(ApiResponse.success({updatePost: doc}));
  371. }).catch(function(err) {
  372. debug('Failed to save updatePost', err);
  373. return res.json(ApiResponse.error());
  374. });
  375. };
  376. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  377. actions.api.notificationRemove = function(req, res) {
  378. var UpdatePost = crowi.model('UpdatePost');
  379. var id = req.body.id;
  380. UpdatePost.remove(id)
  381. .then(function() {
  382. debug('Successfully remove updatePost');
  383. return res.json(ApiResponse.success({}));
  384. }).catch(function(err) {
  385. debug('Failed to remove updatePost', err);
  386. return res.json(ApiResponse.error());
  387. });
  388. };
  389. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  390. actions.api.usersSearch = function(req, res) {
  391. const User = crowi.model('User');
  392. const email =req.query.email;
  393. User.findUsersByPartOfEmail(email, {})
  394. .then(users => {
  395. const result = {
  396. data: users
  397. };
  398. return res.json(ApiResponse.success(result));
  399. }).catch(err => {
  400. return res.json(ApiResponse.error());
  401. });
  402. };
  403. function saveSetting(req, res, form)
  404. {
  405. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  406. Config.updateConfigCache('crowi', config);
  407. return res.json({status: true});
  408. });
  409. }
  410. function validateMailSetting(req, form, callback)
  411. {
  412. var mailer = crowi.mailer;
  413. var option = {
  414. host: form['mail:smtpHost'],
  415. port: form['mail:smtpPort'],
  416. };
  417. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  418. option.auth = {
  419. user: form['mail:smtpUser'],
  420. pass: form['mail:smtpPassword'],
  421. };
  422. }
  423. if (option.port === 465) {
  424. option.secure = true;
  425. }
  426. var smtpClient = mailer.createSMTPClient(option);
  427. debug('mailer setup for validate SMTP setting', smtpClient);
  428. smtpClient.sendMail({
  429. to: req.user.email,
  430. subject: 'Wiki管理設定のアップデートによるメール通知',
  431. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  432. }, callback);
  433. }
  434. return actions;
  435. };