admin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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(currentPage, pageCount, itemCount, maxPageList) {
  12. var pager = {};
  13. pager.currentPage = currentPage;
  14. pager.pageCount = pageCount;
  15. pager.itemCount = itemCount;
  16. pager.previous = null;
  17. if (currentPage > 1) {
  18. pager.previous = currentPage - 1;
  19. }
  20. pager.next = null;
  21. if (currentPage < pageCount) {
  22. pager.next = currentPage + 1;
  23. }
  24. pager.pages = [];
  25. var pagerMin = Math.max(1, Math.ceil(currentPage - maxPageList/2));
  26. var pagerMax = Math.min(pageCount, Math.floor(currentPage + maxPageList/2));
  27. if (pagerMin == 1) {
  28. if (MAX_PAGE_LIST < pageCount) {
  29. pagerMax = MAX_PAGE_LIST;
  30. } else {
  31. pagerMax = pageCount;
  32. }
  33. }
  34. if (pagerMax == pageCount) {
  35. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  36. pagerMin = 1;
  37. } else {
  38. pagerMin = pagerMax - MAX_PAGE_LIST;
  39. }
  40. }
  41. pager.previousDots = null;
  42. if (pagerMin > 1) {
  43. pager.previousDots = true;
  44. }
  45. pager.nextDots = null;
  46. if (pagerMax < pageCount) {
  47. pager.nextDots = true;
  48. }
  49. for (var i = pagerMin;
  50. i <= pagerMax;
  51. i++) {
  52. pager.pages.push(i);
  53. }
  54. return pager;
  55. }
  56. actions.index = function(req, res) {
  57. return res.render('admin/index');
  58. };
  59. actions.app = {};
  60. actions.app.index = function(req, res) {
  61. var settingForm;
  62. settingForm = Config.setupCofigFormData('crowi', req.config);
  63. return res.render('admin/app', {
  64. settingForm: settingForm,
  65. });
  66. };
  67. actions.app.settingUpdate = function(req, res) {
  68. };
  69. // app.get('/admin/notification' , admin.notification.index);
  70. actions.notification = {};
  71. actions.notification.index = function(req, res) {
  72. var config = crowi.getConfig();
  73. var UpdatePost = crowi.model('UpdatePost');
  74. var slackSetting = Config.setupCofigFormData('notification', config);
  75. var hasSlackConfig = Config.hasSlackConfig(config);
  76. var hasSlackToken = Config.hasSlackToken(config);
  77. var slack = crowi.slack;
  78. var slackAuthUrl = '';
  79. if (!Config.hasSlackConfig(req.config)) {
  80. slackSetting['slack:clientId'] = '';
  81. slackSetting['slack:clientSecret'] = '';
  82. } else {
  83. slackAuthUrl = slack.getAuthorizeURL();
  84. }
  85. if (req.session.slackSetting) {
  86. slackSetting = req.session.slackSetting;
  87. req.session.slackSetting = null;
  88. }
  89. UpdatePost.findAll()
  90. .then(function(settings) {
  91. return res.render('admin/notification', {
  92. settings,
  93. slackSetting,
  94. hasSlackConfig,
  95. hasSlackToken,
  96. slackAuthUrl
  97. });
  98. });
  99. };
  100. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  101. actions.notification.slackSetting = function(req, res) {
  102. var slackSetting = req.form.slackSetting;
  103. req.session.slackSetting = slackSetting;
  104. if (req.form.isValid) {
  105. Config.updateNamespaceByArray('notification', slackSetting, function(err, config) {
  106. Config.updateConfigCache('notification', config);
  107. req.session.slackSetting = null;
  108. crowi.setupSlack().then(function() {
  109. return res.redirect('/admin/notification');
  110. });
  111. });
  112. } else {
  113. req.flash('errorMessage', req.form.errors);
  114. return res.redirect('/admin/notification');
  115. }
  116. };
  117. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  118. actions.notification.slackAuth = function(req, res) {
  119. var code = req.query.code;
  120. var config = crowi.getConfig();
  121. if (!code || !Config.hasSlackConfig(req.config)) {
  122. return res.redirect('/admin/notification');
  123. }
  124. var slack = crowi.slack;
  125. var bot = slack.createBot();
  126. bot.api.oauth.access({code}, function(err, data) {
  127. debug('oauth response', err, data);
  128. if (!data.ok || !data.access_token) {
  129. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  130. return res.redirect('/admin/notification');
  131. } else {
  132. Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
  133. if (err) {
  134. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  135. } else {
  136. Config.updateConfigCache('notification', config);
  137. req.flash('successMessage', ['Successfully Connected!']);
  138. }
  139. slack.createBot();
  140. return res.redirect('/admin/notification');
  141. });
  142. }
  143. });
  144. };
  145. actions.user = {};
  146. actions.user.index = function(req, res) {
  147. var page = parseInt(req.query.page) || 1;
  148. User.findUsersWithPagination({page: page}, function(err, users, pageCount, itemCount) {
  149. var pager = createPager(page, pageCount, itemCount, MAX_PAGE_LIST);
  150. return res.render('admin/users', {
  151. users: users,
  152. pager: pager
  153. });
  154. });
  155. };
  156. actions.user.invite = function(req, res) {
  157. var form = req.form.inviteForm;
  158. var toSendEmail = form.sendEmail || false;
  159. if (req.form.isValid) {
  160. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, function(err, userList) {
  161. if (err) {
  162. req.flash('errorMessage', req.form.errors.join('\n'));
  163. } else {
  164. req.flash('createdUser', userList);
  165. }
  166. return res.redirect('/admin/users');
  167. });
  168. } else {
  169. req.flash('errorMessage', req.form.errors.join('\n'));
  170. return res.redirect('/admin/users');
  171. }
  172. };
  173. actions.user.makeAdmin = function(req, res) {
  174. var id = req.params.id;
  175. User.findById(id, function(err, userData) {
  176. userData.makeAdmin(function(err, userData) {
  177. if (err === null) {
  178. req.flash('successMessage', userData.name + 'さんのアカウントを管理者に設定しました。');
  179. } else {
  180. req.flash('errorMessage', '更新に失敗しました。');
  181. debug(err, userData);
  182. }
  183. return res.redirect('/admin/users');
  184. });
  185. });
  186. };
  187. actions.user.removeFromAdmin = function(req, res) {
  188. var id = req.params.id;
  189. User.findById(id, function(err, userData) {
  190. userData.removeFromAdmin(function(err, userData) {
  191. if (err === null) {
  192. req.flash('successMessage', userData.name + 'さんのアカウントを管理者から外しました。');
  193. } else {
  194. req.flash('errorMessage', '更新に失敗しました。');
  195. debug(err, userData);
  196. }
  197. return res.redirect('/admin/users');
  198. });
  199. });
  200. };
  201. actions.user.activate = function(req, res) {
  202. var id = req.params.id;
  203. User.findById(id, function(err, userData) {
  204. userData.statusActivate(function(err, userData) {
  205. if (err === null) {
  206. req.flash('successMessage', userData.name + 'さんのアカウントを承認しました');
  207. } else {
  208. req.flash('errorMessage', '更新に失敗しました。');
  209. debug(err, userData);
  210. }
  211. return res.redirect('/admin/users');
  212. });
  213. });
  214. };
  215. actions.user.suspend = function(req, res) {
  216. var id = req.params.id;
  217. User.findById(id, function(err, userData) {
  218. userData.statusSuspend(function(err, userData) {
  219. if (err === null) {
  220. req.flash('successMessage', userData.name + 'さんのアカウントを利用停止にしました');
  221. } else {
  222. req.flash('errorMessage', '更新に失敗しました。');
  223. debug(err, userData);
  224. }
  225. return res.redirect('/admin/users');
  226. });
  227. });
  228. };
  229. actions.user.remove = function(req, res) {
  230. // 未実装
  231. return res.redirect('/admin/users');
  232. };
  233. // これやったときの relation の挙動未確認
  234. actions.user.removeCompletely = function(req, res) {
  235. // ユーザーの物理削除
  236. var id = req.params.id;
  237. User.removeCompletelyById(id, function(err, removed) {
  238. if (err) {
  239. debug('Error while removing user.', err, id);
  240. req.flash('errorMessage', '完全な削除に失敗しました。');
  241. } else {
  242. req.flash('successMessage', '削除しました');
  243. }
  244. return res.redirect('/admin/users');
  245. });
  246. };
  247. actions.api = {};
  248. actions.api.appSetting = function(req, res) {
  249. var form = req.form.settingForm;
  250. if (req.form.isValid) {
  251. debug('form content', form);
  252. // mail setting ならここで validation
  253. if (form['mail:from']) {
  254. validateMailSetting(req, form, function(err, data) {
  255. debug('Error validate mail setting: ', err, data);
  256. if (err) {
  257. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  258. return res.json({status: false, message: req.form.errors.join('\n')});
  259. }
  260. return saveSetting(req, res, form);
  261. });
  262. } else {
  263. return saveSetting(req, res, form);
  264. }
  265. } else {
  266. return res.json({status: false, message: req.form.errors.join('\n')});
  267. }
  268. };
  269. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  270. actions.api.notificationAdd = function(req, res) {
  271. var UpdatePost = crowi.model('UpdatePost');
  272. var pathPattern = req.body.pathPattern;
  273. var channel = req.body.channel;
  274. debug('notification.add', pathPattern, channel);
  275. UpdatePost.create(pathPattern, channel, req.user)
  276. .then(function(doc) {
  277. debug('Successfully save updatePost', doc);
  278. // fixme: うーん
  279. doc.creator = doc.creator._id.toString();
  280. return res.json(ApiResponse.success({updatePost: doc}));
  281. }).catch(function(err) {
  282. debug('Failed to save updatePost', err);
  283. return res.json(ApiResponse.error());
  284. });
  285. };
  286. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  287. actions.api.notificationRemove = function(req, res) {
  288. var UpdatePost = crowi.model('UpdatePost');
  289. var id = req.body.id;
  290. UpdatePost.remove(id)
  291. .then(function() {
  292. debug('Successfully remove updatePost');
  293. return res.json(ApiResponse.success({}));
  294. }).catch(function(err) {
  295. debug('Failed to remove updatePost', err);
  296. return res.json(ApiResponse.error());
  297. });
  298. };
  299. function saveSetting(req, res, form)
  300. {
  301. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  302. Config.updateConfigCache('crowi', config);
  303. return res.json({status: true});
  304. });
  305. }
  306. function validateMailSetting(req, form, callback)
  307. {
  308. var mailer = crowi.mailer;
  309. var option = {
  310. host: form['mail:smtpHost'],
  311. port: form['mail:smtpPort'],
  312. };
  313. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  314. option.auth = {
  315. user: form['mail:smtpUser'],
  316. pass: form['mail:smtpPassword'],
  317. };
  318. }
  319. if (option.port === 465) {
  320. option.secure = true;
  321. }
  322. var smtpClient = mailer.createSMTPClient(option);
  323. debug('mailer setup for validate SMTP setting', smtpClient);
  324. smtpClient.sendMail({
  325. to: req.user.email,
  326. subject: 'Wiki管理設定のアップデートによるメール通知',
  327. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  328. }, callback);
  329. }
  330. return actions;
  331. };