admin.js 14 KB

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