admin.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('growi:routes:admin')
  4. , logger = require('@alias/logger')('growi:routes:admin')
  5. , fs = require('fs')
  6. , models = crowi.models
  7. , Page = models.Page
  8. , PageGroupRelation = models.PageGroupRelation
  9. , User = models.User
  10. , ExternalAccount = models.ExternalAccount
  11. , UserGroup = models.UserGroup
  12. , UserGroupRelation = models.UserGroupRelation
  13. , Config = models.Config
  14. , GlobalNotificationSetting = models.GlobalNotificationSetting
  15. , GlobalNotificationMailSetting = models.GlobalNotificationMailSetting
  16. , GlobalNotificationSlackSetting = models.GlobalNotificationSlackSetting
  17. , PluginUtils = require('../plugins/plugin-utils')
  18. , pluginUtils = new PluginUtils()
  19. , ApiResponse = require('../util/apiResponse')
  20. , recommendedXssWhiteList = require('../util/recommendedXssWhiteList')
  21. , MAX_PAGE_LIST = 50
  22. , actions = {};
  23. function createPager(total, limit, page, pagesCount, maxPageList) {
  24. const pager = {
  25. page: page,
  26. pagesCount: pagesCount,
  27. pages: [],
  28. total: total,
  29. previous: null,
  30. previousDots: false,
  31. next: null,
  32. nextDots: false,
  33. };
  34. if (page > 1) {
  35. pager.previous = page - 1;
  36. }
  37. if (page < pagesCount) {
  38. pager.next = page + 1;
  39. }
  40. let pagerMin = Math.max(1, Math.ceil(page - maxPageList/2));
  41. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList/2));
  42. if (pagerMin === 1) {
  43. if (MAX_PAGE_LIST < pagesCount) {
  44. pagerMax = MAX_PAGE_LIST;
  45. }
  46. else {
  47. pagerMax = pagesCount;
  48. }
  49. }
  50. if (pagerMax === pagesCount) {
  51. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  52. pagerMin = 1;
  53. }
  54. else {
  55. pagerMin = pagerMax - MAX_PAGE_LIST;
  56. }
  57. }
  58. pager.previousDots = null;
  59. if (pagerMin > 1) {
  60. pager.previousDots = true;
  61. }
  62. pager.nextDots = null;
  63. if (pagerMax < pagesCount) {
  64. pager.nextDots = true;
  65. }
  66. for (let i = pagerMin; i <= pagerMax; i++) {
  67. pager.pages.push(i);
  68. }
  69. return pager;
  70. }
  71. actions.index = function(req, res) {
  72. return res.render('admin/index', {
  73. plugins: pluginUtils.listPlugins(crowi.rootDir),
  74. });
  75. };
  76. // app.get('/admin/app' , admin.app.index);
  77. actions.app = {};
  78. actions.app.index = function(req, res) {
  79. var settingForm;
  80. settingForm = Config.setupCofigFormData('crowi', req.config);
  81. return res.render('admin/app', {
  82. settingForm: settingForm,
  83. });
  84. };
  85. actions.app.settingUpdate = function(req, res) {
  86. };
  87. // app.get('/admin/security' , admin.security.index);
  88. actions.security = {};
  89. actions.security.index = function(req, res) {
  90. const settingForm = Config.setupCofigFormData('crowi', req.config);
  91. return res.render('admin/security', { settingForm });
  92. };
  93. // app.get('/admin/markdown' , admin.markdown.index);
  94. actions.markdown = {};
  95. actions.markdown.index = function(req, res) {
  96. const config = crowi.getConfig();
  97. const markdownSetting = Config.setupCofigFormData('markdown', config);
  98. return res.render('admin/markdown', {
  99. markdownSetting: markdownSetting,
  100. recommendedXssWhiteList: recommendedXssWhiteList,
  101. });
  102. };
  103. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  104. actions.markdown.lineBreaksSetting = function(req, res) {
  105. var markdownSetting = req.form.markdownSetting;
  106. req.session.markdownSetting = markdownSetting;
  107. if (req.form.isValid) {
  108. Config.updateNamespaceByArray('markdown', markdownSetting, function(err, config) {
  109. Config.updateConfigCache('markdown', config);
  110. req.session.markdownSetting = null;
  111. req.flash('successMessage', ['Successfully updated!']);
  112. return res.redirect('/admin/markdown');
  113. });
  114. }
  115. else {
  116. req.flash('errorMessage', req.form.errors);
  117. return res.redirect('/admin/markdown');
  118. }
  119. };
  120. // app.post('/admin/markdown/xss-setting' , admin.markdown.xssSetting);
  121. actions.markdown.xssSetting = function(req, res) {
  122. let xssSetting = req.form.markdownSetting;
  123. xssSetting['markdown:xss:tagWhiteList'] = stringToArray(xssSetting['markdown:xss:tagWhiteList']);
  124. xssSetting['markdown:xss:attrWhiteList'] = stringToArray(xssSetting['markdown:xss:attrWhiteList']);
  125. req.session.markdownSetting = xssSetting;
  126. if (req.form.isValid) {
  127. Config.updateNamespaceByArray('markdown', xssSetting, function(err, config) {
  128. Config.updateConfigCache('markdown', config);
  129. req.session.xssSetting = null;
  130. req.flash('successMessage', ['Successfully updated!']);
  131. return res.redirect('/admin/markdown');
  132. });
  133. }
  134. else {
  135. req.flash('errorMessage', req.form.errors);
  136. return res.redirect('/admin/markdown');
  137. }
  138. };
  139. const stringToArray = (string) => {
  140. const array = string.split(',');
  141. return array.map(item => item.trim());
  142. };
  143. // app.get('/admin/customize' , admin.customize.index);
  144. actions.customize = {};
  145. actions.customize.index = function(req, res) {
  146. var settingForm;
  147. settingForm = Config.setupCofigFormData('crowi', req.config);
  148. const highlightJsCssSelectorOptions = {
  149. 'github': { name: '[Light] GitHub', border: false },
  150. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  151. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  152. 'xcode': { name: '[Light] Xcode', border: true },
  153. 'vs': { name: '[Light] Vs', border: true },
  154. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  155. 'hybrid': { name: '[Dark] Hybrid', border: false },
  156. 'monokai': { name: '[Dark] Monokai', border: false },
  157. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  158. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  159. };
  160. return res.render('admin/customize', {
  161. settingForm: settingForm,
  162. highlightJsCssSelectorOptions: highlightJsCssSelectorOptions
  163. });
  164. };
  165. // app.get('/admin/notification' , admin.notification.index);
  166. actions.notification = {};
  167. actions.notification.index = async(req, res) => {
  168. const config = crowi.getConfig();
  169. const UpdatePost = crowi.model('UpdatePost');
  170. let slackSetting = Config.setupCofigFormData('notification', config);
  171. const hasSlackIwhUrl = Config.hasSlackIwhUrl(config);
  172. const hasSlackToken = Config.hasSlackToken(config);
  173. if (!Config.hasSlackIwhUrl(req.config)) {
  174. slackSetting['slack:incomingWebhookUrl'] = '';
  175. }
  176. if (req.session.slackSetting) {
  177. slackSetting = req.session.slackSetting;
  178. req.session.slackSetting = null;
  179. }
  180. const globalNotifications = await GlobalNotificationSetting.findAll();
  181. const userNotifications = await UpdatePost.findAll();
  182. return res.render('admin/notification', {
  183. userNotifications,
  184. slackSetting,
  185. hasSlackIwhUrl,
  186. hasSlackToken,
  187. globalNotifications,
  188. });
  189. };
  190. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  191. actions.notification.slackSetting = function(req, res) {
  192. var slackSetting = req.form.slackSetting;
  193. req.session.slackSetting = slackSetting;
  194. if (req.form.isValid) {
  195. Config.updateNamespaceByArray('notification', slackSetting, function(err, config) {
  196. Config.updateConfigCache('notification', config);
  197. req.flash('successMessage', ['Successfully Updated!']);
  198. req.session.slackSetting = null;
  199. // Re-setup
  200. crowi.setupSlack().then(function() {
  201. return res.redirect('/admin/notification');
  202. });
  203. });
  204. }
  205. else {
  206. req.flash('errorMessage', req.form.errors);
  207. return res.redirect('/admin/notification');
  208. }
  209. };
  210. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  211. actions.notification.slackAuth = function(req, res) {
  212. const code = req.query.code;
  213. const config = crowi.getConfig();
  214. if (!code || !Config.hasSlackConfig(req.config)) {
  215. return res.redirect('/admin/notification');
  216. }
  217. const slack = crowi.slack;
  218. slack.getOauthAccessToken(code)
  219. .then(data => {
  220. debug('oauth response', data);
  221. Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
  222. if (err) {
  223. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  224. }
  225. else {
  226. Config.updateConfigCache('notification', config);
  227. req.flash('successMessage', ['Successfully Connected!']);
  228. }
  229. return res.redirect('/admin/notification');
  230. });
  231. }).catch(err => {
  232. debug('oauth response ERROR', err);
  233. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  234. return res.redirect('/admin/notification');
  235. });
  236. };
  237. actions.search = {};
  238. actions.search.index = function(req, res) {
  239. return res.render('admin/search', {
  240. });
  241. };
  242. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  243. actions.notification.slackIwhSetting = function(req, res) {
  244. var slackIwhSetting = req.form.slackIwhSetting;
  245. if (req.form.isValid) {
  246. Config.updateNamespaceByArray('notification', slackIwhSetting, function(err, config) {
  247. Config.updateConfigCache('notification', config);
  248. req.flash('successMessage', ['Successfully Updated!']);
  249. // Re-setup
  250. crowi.setupSlack().then(function() {
  251. return res.redirect('/admin/notification#slack-incoming-webhooks');
  252. });
  253. });
  254. }
  255. else {
  256. req.flash('errorMessage', req.form.errors);
  257. return res.redirect('/admin/notification#slack-incoming-webhooks');
  258. }
  259. };
  260. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  261. actions.notification.disconnectFromSlack = function(req, res) {
  262. const config = crowi.getConfig();
  263. const slack = crowi.slack;
  264. Config.updateNamespaceByArray('notification', {'slack:token': ''}, function(err, config) {
  265. Config.updateConfigCache('notification', config);
  266. req.flash('successMessage', ['Successfully Disconnected!']);
  267. return res.redirect('/admin/notification');
  268. });
  269. };
  270. actions.globalNotification = {};
  271. actions.globalNotification.detail = async(req, res) => {
  272. const notificationSettingId = req.params.id;
  273. let renderVars = {};
  274. if (notificationSettingId) {
  275. try {
  276. renderVars.setting = await GlobalNotificationSetting.findOne({_id: notificationSettingId});
  277. }
  278. catch (err) {
  279. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  280. }
  281. }
  282. return res.render('admin/global-notification-detail', renderVars);
  283. };
  284. actions.globalNotification.create = (req, res) => {
  285. const form = req.form.notificationGlobal;
  286. let setting;
  287. switch (form.notifyToType) {
  288. case 'mail':
  289. setting = new GlobalNotificationMailSetting(crowi);
  290. setting.toEmail = form.toEmail;
  291. break;
  292. // case 'slack':
  293. // setting = new GlobalNotificationSlackSetting(crowi);
  294. // setting.slackChannels = form.slackChannels;
  295. // break;
  296. default:
  297. logger.error('GlobalNotificationSetting Type Error: undefined type');
  298. req.flash('errorMessage', 'Error occurred in creating a new global notification setting: undefined notification type');
  299. return res.redirect('/admin/notification#global-notification');
  300. }
  301. setting.triggerPath = form.triggerPath;
  302. setting.triggerEvents = getNotificationEvents(form);
  303. setting.save();
  304. return res.redirect('/admin/notification#global-notification');
  305. };
  306. actions.globalNotification.update = async(req, res) => {
  307. const form = req.form.notificationGlobal;
  308. const setting = await GlobalNotificationSetting.findOne({_id: form.id});
  309. switch (form.notifyToType) {
  310. case 'mail':
  311. setting.toEmail = form.toEmail;
  312. break;
  313. // case 'slack':
  314. // setting.slackChannels = form.slackChannels;
  315. // break;
  316. default:
  317. logger.error('GlobalNotificationSetting Type Error: undefined type');
  318. req.flash('errorMessage', 'Error occurred in updating the global notification setting: undefined notification type');
  319. return res.redirect('/admin/notification#global-notification');
  320. }
  321. setting.triggerPath = form.triggerPath;
  322. setting.triggerEvents = getNotificationEvents(form);
  323. setting.save();
  324. return res.redirect('/admin/notification#global-notification');
  325. };
  326. const getNotificationEvents = (form) => {
  327. let triggerEvents = [];
  328. const triggerEventKeys = Object.keys(form).filter(key => key.match(/^triggerEvent/));
  329. triggerEventKeys.forEach(key => {
  330. if (form[key]) {
  331. triggerEvents.push(form[key]);
  332. }
  333. });
  334. return triggerEvents;
  335. };
  336. actions.search.buildIndex = function(req, res) {
  337. var search = crowi.getSearcher();
  338. if (!search) {
  339. return res.redirect('/admin');
  340. }
  341. return new Promise(function(resolve, reject) {
  342. search.deleteIndex()
  343. .then(function(data) {
  344. debug('Index deleted.');
  345. resolve();
  346. }).catch(function(err) {
  347. debug('Delete index Error, but if it is initialize, its ok.', err);
  348. resolve();
  349. });
  350. })
  351. .then(function() {
  352. return search.buildIndex();
  353. })
  354. .then(function(data) {
  355. if (!data.errors) {
  356. debug('Index created.');
  357. }
  358. return search.addAllPages();
  359. })
  360. .then(function(data) {
  361. if (!data.errors) {
  362. debug('Data is successfully indexed.');
  363. req.flash('successMessage', 'Data is successfully indexed.');
  364. }
  365. else {
  366. debug('Data index error.', data.errors);
  367. req.flash('errorMessage', `Data index error: ${data.errors}`);
  368. }
  369. return res.redirect('/admin/search');
  370. })
  371. .catch(function(err) {
  372. debug('Error', err);
  373. req.flash('errorMessage', `Error: ${err}`);
  374. return res.redirect('/admin/search');
  375. });
  376. };
  377. actions.user = {};
  378. actions.user.index = function(req, res) {
  379. var page = parseInt(req.query.page) || 1;
  380. User.findUsersWithPagination({page: page}, function(err, result) {
  381. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  382. return res.render('admin/users', {
  383. users: result.docs,
  384. pager: pager
  385. });
  386. });
  387. };
  388. actions.user.invite = function(req, res) {
  389. var form = req.form.inviteForm;
  390. var toSendEmail = form.sendEmail || false;
  391. if (req.form.isValid) {
  392. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, function(err, userList) {
  393. if (err) {
  394. req.flash('errorMessage', req.form.errors.join('\n'));
  395. }
  396. else {
  397. req.flash('createdUser', userList);
  398. }
  399. return res.redirect('/admin/users');
  400. });
  401. }
  402. else {
  403. req.flash('errorMessage', req.form.errors.join('\n'));
  404. return res.redirect('/admin/users');
  405. }
  406. };
  407. actions.user.makeAdmin = function(req, res) {
  408. var id = req.params.id;
  409. User.findById(id, function(err, userData) {
  410. userData.makeAdmin(function(err, userData) {
  411. if (err === null) {
  412. req.flash('successMessage', userData.name + 'さんのアカウントを管理者に設定しました。');
  413. }
  414. else {
  415. req.flash('errorMessage', '更新に失敗しました。');
  416. debug(err, userData);
  417. }
  418. return res.redirect('/admin/users');
  419. });
  420. });
  421. };
  422. actions.user.removeFromAdmin = function(req, res) {
  423. var id = req.params.id;
  424. User.findById(id, function(err, userData) {
  425. userData.removeFromAdmin(function(err, userData) {
  426. if (err === null) {
  427. req.flash('successMessage', userData.name + 'さんのアカウントを管理者から外しました。');
  428. }
  429. else {
  430. req.flash('errorMessage', '更新に失敗しました。');
  431. debug(err, userData);
  432. }
  433. return res.redirect('/admin/users');
  434. });
  435. });
  436. };
  437. actions.user.activate = function(req, res) {
  438. var id = req.params.id;
  439. User.findById(id, function(err, userData) {
  440. userData.statusActivate(function(err, userData) {
  441. if (err === null) {
  442. req.flash('successMessage', userData.name + 'さんのアカウントを有効化しました');
  443. }
  444. else {
  445. req.flash('errorMessage', '更新に失敗しました。');
  446. debug(err, userData);
  447. }
  448. return res.redirect('/admin/users');
  449. });
  450. });
  451. };
  452. actions.user.suspend = function(req, res) {
  453. var id = req.params.id;
  454. User.findById(id, function(err, userData) {
  455. userData.statusSuspend(function(err, userData) {
  456. if (err === null) {
  457. req.flash('successMessage', userData.name + 'さんのアカウントを利用停止にしました');
  458. }
  459. else {
  460. req.flash('errorMessage', '更新に失敗しました。');
  461. debug(err, userData);
  462. }
  463. return res.redirect('/admin/users');
  464. });
  465. });
  466. };
  467. actions.user.remove = function(req, res) {
  468. const id = req.params.id;
  469. let username = '';
  470. return new Promise((resolve, reject) => {
  471. User.findById(id, (err, userData) => {
  472. username = userData.username;
  473. return resolve(userData);
  474. });
  475. })
  476. .then((userData) => {
  477. return new Promise((resolve, reject) => {
  478. userData.statusDelete((err, userData) => {
  479. if (err) {
  480. reject(err);
  481. }
  482. resolve(userData);
  483. });
  484. });
  485. })
  486. .then((userData) => {
  487. // remove all External Accounts
  488. return ExternalAccount.remove({user: userData}).then(() => userData);
  489. })
  490. .then((userData) => {
  491. return Page.removePageByPath(`/user/${username}`).then(() => userData);
  492. })
  493. .then((userData) => {
  494. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  495. return res.redirect('/admin/users');
  496. })
  497. .catch((err) => {
  498. req.flash('errorMessage', '削除に失敗しました。');
  499. return res.redirect('/admin/users');
  500. });
  501. };
  502. // これやったときの relation の挙動未確認
  503. actions.user.removeCompletely = function(req, res) {
  504. // ユーザーの物理削除
  505. var id = req.params.id;
  506. User.removeCompletelyById(id, function(err, removed) {
  507. if (err) {
  508. debug('Error while removing user.', err, id);
  509. req.flash('errorMessage', '完全な削除に失敗しました。');
  510. }
  511. else {
  512. req.flash('successMessage', '削除しました');
  513. }
  514. return res.redirect('/admin/users');
  515. });
  516. };
  517. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  518. actions.user.resetPassword = function(req, res) {
  519. const id = req.body.user_id;
  520. const User = crowi.model('User');
  521. User.resetPasswordByRandomString(id)
  522. .then(function(data) {
  523. data.user = User.filterToPublicFields(data.user);
  524. return res.json(ApiResponse.success(data));
  525. }).catch(function(err) {
  526. debug('Error on reseting password', err);
  527. return res.json(ApiResponse.error('Error'));
  528. });
  529. };
  530. actions.externalAccount = {};
  531. actions.externalAccount.index = function(req, res) {
  532. const page = parseInt(req.query.page) || 1;
  533. ExternalAccount.findAllWithPagination({page})
  534. .then((result) => {
  535. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  536. return res.render('admin/external-accounts', {
  537. accounts: result.docs,
  538. pager: pager
  539. });
  540. });
  541. };
  542. actions.externalAccount.remove = function(req, res) {
  543. const accountId = req.params.id;
  544. ExternalAccount.findOneAndRemove({accountId})
  545. .then((result) => {
  546. if (result == null) {
  547. req.flash('errorMessage', '削除に失敗しました。');
  548. return res.redirect('/admin/users/external-accounts');
  549. }
  550. else {
  551. req.flash('successMessage', `外部アカウント '${accountId}' を削除しました`);
  552. return res.redirect('/admin/users/external-accounts');
  553. }
  554. });
  555. };
  556. actions.userGroup = {};
  557. actions.userGroup.index = function(req, res) {
  558. var page = parseInt(req.query.page) || 1;
  559. var renderVar = {
  560. userGroups: [],
  561. userGroupRelations: new Map(),
  562. pager: null,
  563. };
  564. UserGroup.findUserGroupsWithPagination({ page: page })
  565. .then((result) => {
  566. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  567. var userGroups = result.docs;
  568. renderVar.userGroups = userGroups;
  569. renderVar.pager = pager;
  570. return userGroups.map((userGroup) => {
  571. return new Promise((resolve, reject) => {
  572. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  573. .then((relations) => {
  574. return resolve([userGroup, relations]);
  575. });
  576. });
  577. });
  578. })
  579. .then((allRelationsPromise) => {
  580. return Promise.all(allRelationsPromise);
  581. })
  582. .then((relations) => {
  583. renderVar.userGroupRelations = new Map(relations);
  584. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  585. return res.render('admin/user-groups', renderVar);
  586. })
  587. .catch( function(err) {
  588. debug('Error on find all relations', err);
  589. return res.json(ApiResponse.error('Error'));
  590. });
  591. };
  592. // グループ詳細
  593. actions.userGroup.detail = function(req, res) {
  594. const userGroupId = req.params.id;
  595. const renderVar = {
  596. userGroup: null,
  597. userGroupRelations: [],
  598. pageGroupRelations: [],
  599. notRelatedusers: []
  600. };
  601. let targetUserGroup = null;
  602. UserGroup.findOne({ _id: userGroupId})
  603. .then(function(userGroup) {
  604. targetUserGroup = userGroup;
  605. if (targetUserGroup == null) {
  606. req.flash('errorMessage', 'グループがありません');
  607. throw new Error('no userGroup is exists. ', name);
  608. }
  609. else {
  610. renderVar.userGroup = targetUserGroup;
  611. return Promise.all([
  612. // get all user and group relations
  613. UserGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  614. // get all page and group relations
  615. PageGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  616. // get all not related users for group
  617. UserGroupRelation.findUserByNotRelatedGroup(targetUserGroup),
  618. ]);
  619. }
  620. })
  621. .then((resolves) => {
  622. renderVar.userGroupRelations = resolves[0];
  623. renderVar.pageGroupRelations = resolves[1];
  624. renderVar.notRelatedusers = resolves[2];
  625. debug('notRelatedusers', renderVar.notRelatedusers);
  626. return res.render('admin/user-group-detail', renderVar);
  627. })
  628. .catch((err) => {
  629. req.flash('errorMessage', 'ユーザグループの検索に失敗しました');
  630. debug('Error on get userGroupDetail', err);
  631. return res.redirect('/admin/user-groups');
  632. });
  633. };
  634. //グループの生成
  635. actions.userGroup.create = function(req, res) {
  636. const form = req.form.createGroupForm;
  637. if (req.form.isValid) {
  638. const userGroupName = crowi.xss.process(form.userGroupName);
  639. UserGroup.createGroupByName(userGroupName)
  640. .then((newUserGroup) => {
  641. req.flash('successMessage', newUserGroup.name);
  642. req.flash('createdUserGroup', newUserGroup);
  643. return res.redirect('/admin/user-groups');
  644. })
  645. .catch((err) => {
  646. debug('create userGroup error:', err);
  647. req.flash('errorMessage', '同じグループ名が既に存在します。');
  648. });
  649. }
  650. else {
  651. req.flash('errorMessage', req.form.errors.join('\n'));
  652. return res.redirect('/admin/user-groups');
  653. }
  654. };
  655. //
  656. actions.userGroup.update = function(req, res) {
  657. const userGroupId = req.params.userGroupId;
  658. const name = crowi.xss.process(req.body.name);
  659. UserGroup.findById(userGroupId)
  660. .then((userGroupData) => {
  661. if (userGroupData == null) {
  662. req.flash('errorMessage', 'グループの検索に失敗しました。');
  663. return new Promise();
  664. }
  665. else {
  666. // 名前存在チェック
  667. return UserGroup.isRegisterableName(name)
  668. .then((isRegisterableName) => {
  669. // 既に存在するグループ名に更新しようとした場合はエラー
  670. if (!isRegisterableName) {
  671. req.flash('errorMessage', 'グループ名が既に存在します。');
  672. }
  673. else {
  674. return userGroupData.updateName(name)
  675. .then(() => {
  676. req.flash('successMessage', 'グループ名を更新しました。');
  677. })
  678. .catch((err) => {
  679. req.flash('errorMessage', 'グループ名の更新に失敗しました。');
  680. });
  681. }
  682. });
  683. }
  684. })
  685. .then(() => {
  686. return res.redirect('/admin/user-group-detail/' + userGroupId);
  687. });
  688. };
  689. actions.userGroup.uploadGroupPicture = function(req, res) {
  690. var fileUploader = require('../util/fileUploader')(crowi, app);
  691. //var storagePlugin = new pluginService('storage');
  692. //var storage = require('../service/storage').StorageService(config);
  693. var userGroupId = req.params.userGroupId;
  694. var tmpFile = req.file || null;
  695. if (!tmpFile) {
  696. return res.json({
  697. 'status': false,
  698. 'message': 'File type error.'
  699. });
  700. }
  701. UserGroup.findById(userGroupId, function(err, userGroupData) {
  702. if (!userGroupData) {
  703. return res.json({
  704. 'status': false,
  705. 'message': 'UserGroup error.'
  706. });
  707. }
  708. var tmpPath = tmpFile.path;
  709. var filePath = UserGroup.createUserGroupPictureFilePath(userGroupData, tmpFile.filename + tmpFile.originalname);
  710. var acceptableFileType = /image\/.+/;
  711. if (!tmpFile.mimetype.match(acceptableFileType)) {
  712. return res.json({
  713. 'status': false,
  714. 'message': 'File type error. Only image files is allowed to set as user picture.',
  715. });
  716. }
  717. var tmpFileStream = fs.createReadStream(tmpPath, { flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  718. fileUploader.uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
  719. .then(function(data) {
  720. var imageUrl = fileUploader.generateUrl(filePath);
  721. userGroupData.updateImage(imageUrl)
  722. .then(() => {
  723. fs.unlink(tmpPath, function(err) {
  724. if (err) {
  725. debug('Error while deleting tmp file.', err);
  726. }
  727. return res.json({
  728. 'status': true,
  729. 'url': imageUrl,
  730. 'message': '',
  731. });
  732. });
  733. });
  734. }).catch(function(err) {
  735. debug('Uploading error', err);
  736. return res.json({
  737. 'status': false,
  738. 'message': 'Error while uploading to ',
  739. });
  740. });
  741. });
  742. };
  743. actions.userGroup.deletePicture = function(req, res) {
  744. const userGroupId = req.params.userGroupId;
  745. let userGroupName = null;
  746. UserGroup.findById(userGroupId)
  747. .then((userGroupData) => {
  748. if (userGroupData == null) {
  749. return Promise.reject();
  750. }
  751. else {
  752. userGroupName = userGroupData.name;
  753. return userGroupData.deleteImage();
  754. }
  755. })
  756. .then((updated) => {
  757. req.flash('successMessage', 'Deleted group picture');
  758. return res.redirect('/admin/user-group-detail/' + userGroupId);
  759. })
  760. .catch((err) => {
  761. debug('An error occured.', err);
  762. req.flash('errorMessage', 'Error while deleting group picture');
  763. if (userGroupName == null) {
  764. return res.redirect('/admin/user-groups/');
  765. }
  766. else {
  767. return res.redirect('/admin/user-group-detail/' + userGroupId);
  768. }
  769. });
  770. };
  771. // app.post('/_api/admin/user-group/delete' , admin.userGroup.removeCompletely);
  772. actions.userGroup.removeCompletely = function(req, res) {
  773. const id = req.body.user_group_id;
  774. const fileUploader = require('../util/fileUploader')(crowi, app);
  775. UserGroup.removeCompletelyById(id)
  776. //// TODO remove attachments
  777. // couldn't remove because filePath includes '/uploads/uploads'
  778. // Error: ENOENT: no such file or directory, unlink 'C:\dev\growi\public\uploads\uploads\userGroup\5b1df18ab69611651cc71495.png
  779. //
  780. // .then(removed => {
  781. // if (removed.image != null) {
  782. // fileUploader.deleteFile(null, removed.image);
  783. // }
  784. // })
  785. .then(() => {
  786. req.flash('successMessage', '削除しました');
  787. return res.redirect('/admin/user-groups');
  788. })
  789. .catch((err) => {
  790. debug('Error while removing userGroup.', err, id);
  791. req.flash('errorMessage', '完全な削除に失敗しました。');
  792. return res.redirect('/admin/user-groups');
  793. });
  794. };
  795. actions.userGroupRelation = {};
  796. actions.userGroupRelation.index = function(req, res) {
  797. };
  798. actions.userGroupRelation.create = function(req, res) {
  799. const User = crowi.model('User');
  800. const UserGroup = crowi.model('UserGroup');
  801. const UserGroupRelation = crowi.model('UserGroupRelation');
  802. // req params
  803. const userName = req.body.user_name;
  804. const userGroupId = req.body.user_group_id;
  805. let user = null;
  806. let userGroup = null;
  807. Promise.all([
  808. // ユーザグループをIDで検索
  809. UserGroup.findById(userGroupId),
  810. // ユーザを名前で検索
  811. User.findUserByUsername(userName),
  812. ])
  813. .then((resolves) => {
  814. userGroup = resolves[0];
  815. user = resolves[1];
  816. // Relation を作成
  817. UserGroupRelation.createRelation(userGroup, user);
  818. })
  819. .then((result) => {
  820. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  821. }).catch((err) => {
  822. debug('Error on create user-group relation', err);
  823. req.flash('errorMessage', 'Error on create user-group relation');
  824. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  825. });
  826. };
  827. actions.userGroupRelation.remove = function(req, res) {
  828. const UserGroupRelation = crowi.model('UserGroupRelation');
  829. const userGroupId = req.params.id;
  830. const relationId = req.params.relationId;
  831. UserGroupRelation.removeById(relationId)
  832. .then(() =>{
  833. return res.redirect('/admin/user-group-detail/' + userGroupId);
  834. })
  835. .catch((err) => {
  836. debug('Error on remove user-group-relation', err);
  837. req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
  838. });
  839. };
  840. actions.api = {};
  841. actions.api.appSetting = function(req, res) {
  842. var form = req.form.settingForm;
  843. if (req.form.isValid) {
  844. debug('form content', form);
  845. // mail setting ならここで validation
  846. if (form['mail:from']) {
  847. validateMailSetting(req, form, function(err, data) {
  848. debug('Error validate mail setting: ', err, data);
  849. if (err) {
  850. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  851. return res.json({status: false, message: req.form.errors.join('\n')});
  852. }
  853. return saveSetting(req, res, form);
  854. });
  855. }
  856. else {
  857. return saveSetting(req, res, form);
  858. }
  859. }
  860. else {
  861. return res.json({status: false, message: req.form.errors.join('\n')});
  862. }
  863. };
  864. actions.api.securitySetting = function(req, res) {
  865. const form = req.form.settingForm;
  866. if (req.form.isValid) {
  867. debug('form content', form);
  868. return saveSetting(req, res, form);
  869. }
  870. else {
  871. return res.json({status: false, message: req.form.errors.join('\n')});
  872. }
  873. };
  874. actions.api.securityPassportLdapSetting = function(req, res) {
  875. var form = req.form.settingForm;
  876. if (!req.form.isValid) {
  877. return res.json({status: false, message: req.form.errors.join('\n')});
  878. }
  879. debug('form content', form);
  880. return saveSettingAsync(form)
  881. .then(() => {
  882. const config = crowi.getConfig();
  883. // reset strategy
  884. crowi.passportService.resetLdapStrategy();
  885. // setup strategy
  886. if (Config.isEnabledPassportLdap(config)) {
  887. crowi.passportService.setupLdapStrategy(true);
  888. }
  889. return;
  890. })
  891. .then(() => {
  892. res.json({status: true});
  893. });
  894. };
  895. actions.api.securityPassportGoogleSetting = async(req, res) => {
  896. const form = req.form.settingForm;
  897. if (!req.form.isValid) {
  898. return res.json({status: false, message: req.form.errors.join('\n')});
  899. }
  900. debug('form content', form);
  901. await saveSettingAsync(form);
  902. const config = await crowi.getConfig();
  903. // reset strategy
  904. await crowi.passportService.resetGoogleStrategy();
  905. // setup strategy
  906. if (Config.isEnabledPassportGoogle(config)) {
  907. try {
  908. await crowi.passportService.setupGoogleStrategy(true);
  909. }
  910. catch (err) {
  911. // reset
  912. await crowi.passportService.resetGoogleStrategy();
  913. return res.json({status: false, message: err.message});
  914. }
  915. }
  916. return res.json({status: true});
  917. };
  918. actions.api.securityPassportGitHubSetting = async(req, res) => {
  919. const form = req.form.settingForm;
  920. if (!req.form.isValid) {
  921. return res.json({status: false, message: req.form.errors.join('\n')});
  922. }
  923. debug('form content', form);
  924. await saveSettingAsync(form);
  925. const config = await crowi.getConfig();
  926. // reset strategy
  927. await crowi.passportService.resetGitHubStrategy();
  928. // setup strategy
  929. if (Config.isEnabledPassportGitHub(config)) {
  930. try {
  931. await crowi.passportService.setupGitHubStrategy(true);
  932. }
  933. catch (err) {
  934. // reset
  935. await crowi.passportService.resetGitHubStrategy();
  936. return res.json({status: false, message: err.message});
  937. }
  938. }
  939. return res.json({status: true});
  940. };
  941. actions.api.customizeSetting = function(req, res) {
  942. const form = req.form.settingForm;
  943. if (req.form.isValid) {
  944. debug('form content', form);
  945. return saveSetting(req, res, form);
  946. }
  947. else {
  948. return res.json({status: false, message: req.form.errors.join('\n')});
  949. }
  950. };
  951. actions.api.customizeSetting = function(req, res) {
  952. const form = req.form.settingForm;
  953. if (req.form.isValid) {
  954. debug('form content', form);
  955. return saveSetting(req, res, form);
  956. }
  957. else {
  958. return res.json({status: false, message: req.form.errors.join('\n')});
  959. }
  960. };
  961. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  962. actions.api.notificationAdd = function(req, res) {
  963. var UpdatePost = crowi.model('UpdatePost');
  964. var pathPattern = req.body.pathPattern;
  965. var channel = req.body.channel;
  966. debug('notification.add', pathPattern, channel);
  967. UpdatePost.create(pathPattern, channel, req.user)
  968. .then(function(doc) {
  969. debug('Successfully save updatePost', doc);
  970. // fixme: うーん
  971. doc.creator = doc.creator._id.toString();
  972. return res.json(ApiResponse.success({updatePost: doc}));
  973. }).catch(function(err) {
  974. debug('Failed to save updatePost', err);
  975. return res.json(ApiResponse.error());
  976. });
  977. };
  978. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  979. actions.api.notificationRemove = function(req, res) {
  980. var UpdatePost = crowi.model('UpdatePost');
  981. var id = req.body.id;
  982. UpdatePost.remove(id)
  983. .then(function() {
  984. debug('Successfully remove updatePost');
  985. return res.json(ApiResponse.success({}));
  986. }).catch(function(err) {
  987. debug('Failed to remove updatePost', err);
  988. return res.json(ApiResponse.error());
  989. });
  990. };
  991. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  992. actions.api.usersSearch = function(req, res) {
  993. const User = crowi.model('User');
  994. const email =req.query.email;
  995. User.findUsersByPartOfEmail(email, {})
  996. .then(users => {
  997. const result = {
  998. data: users
  999. };
  1000. return res.json(ApiResponse.success(result));
  1001. }).catch(err => {
  1002. return res.json(ApiResponse.error());
  1003. });
  1004. };
  1005. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  1006. const id = req.query.id;
  1007. const isEnabled = (req.query.isEnabled == 'true');
  1008. try {
  1009. if (isEnabled) {
  1010. await GlobalNotificationSetting.disable(id);
  1011. }
  1012. else {
  1013. await GlobalNotificationSetting.enable(id);
  1014. }
  1015. return res.json(ApiResponse.success());
  1016. }
  1017. catch (err) {
  1018. return res.json(ApiResponse.error());
  1019. }
  1020. };
  1021. actions.api.removeGlobalNotification = async(req, res) => {
  1022. const id = req.params.id;
  1023. try {
  1024. await GlobalNotificationSetting.findOneAndRemove({_id: id});
  1025. return res.json(ApiResponse.success());
  1026. }
  1027. catch (err) {
  1028. return res.json(ApiResponse.error());
  1029. }
  1030. };
  1031. /**
  1032. * save settings, update config cache, and response json
  1033. *
  1034. * @param {any} req
  1035. * @param {any} res
  1036. * @param {any} form
  1037. */
  1038. function saveSetting(req, res, form) {
  1039. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  1040. Config.updateConfigCache('crowi', config);
  1041. return res.json({status: true});
  1042. });
  1043. }
  1044. /**
  1045. * save settings, update config cache ONLY. (this method don't response json)
  1046. *
  1047. * @param {any} form
  1048. * @returns
  1049. */
  1050. function saveSettingAsync(form) {
  1051. return new Promise((resolve, reject) => {
  1052. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  1053. if (err) {
  1054. return reject(err);
  1055. }
  1056. Config.updateConfigCache('crowi', config);
  1057. return resolve();
  1058. });
  1059. });
  1060. }
  1061. function validateMailSetting(req, form, callback) {
  1062. var mailer = crowi.mailer;
  1063. var option = {
  1064. host: form['mail:smtpHost'],
  1065. port: form['mail:smtpPort'],
  1066. };
  1067. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1068. option.auth = {
  1069. user: form['mail:smtpUser'],
  1070. pass: form['mail:smtpPassword'],
  1071. };
  1072. }
  1073. if (option.port === 465) {
  1074. option.secure = true;
  1075. }
  1076. var smtpClient = mailer.createSMTPClient(option);
  1077. debug('mailer setup for validate SMTP setting', smtpClient);
  1078. smtpClient.sendMail({
  1079. from: form['mail:from'],
  1080. to: req.user.email,
  1081. subject: 'Wiki管理設定のアップデートによるメール通知',
  1082. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  1083. }, callback);
  1084. }
  1085. return actions;
  1086. };