admin.js 16 KB

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