admin.js 15 KB

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