admin.js 38 KB

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