admin.js 14 KB

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