admin.js 16 KB

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