admin.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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. break;
  297. }
  298. let triggerEvents = [];
  299. const triggerEventKeys = Object.keys(form).filter(key => key.match(/^triggerEvent/));
  300. triggerEventKeys.forEach(key => {
  301. if (form[key]) {
  302. triggerEvents.push(form[key]);
  303. }
  304. });
  305. if (setting) {
  306. setting.triggerPath = form.triggerPath;
  307. setting.triggerEvents = triggerEvents;
  308. setting.save();
  309. }
  310. return res.redirect('/admin/notification#global-notification');
  311. };
  312. actions.globalNotification.update = (req, res) => {
  313. const notificationSettingId = req.params.id;
  314. const renderVars = {
  315. };
  316. return res.render('admin/global-notification-detail', renderVars);
  317. };
  318. // actions.globalNotification.remove = (req, res) => {
  319. // const notificationSettingId = req.params.id;
  320. // const renderVars = {
  321. // };
  322. // return res.render('admin/global-notification-detail', renderVars);
  323. // };
  324. actions.search.buildIndex = function(req, res) {
  325. var search = crowi.getSearcher();
  326. if (!search) {
  327. return res.redirect('/admin');
  328. }
  329. return new Promise(function(resolve, reject) {
  330. search.deleteIndex()
  331. .then(function(data) {
  332. debug('Index deleted.');
  333. resolve();
  334. }).catch(function(err) {
  335. debug('Delete index Error, but if it is initialize, its ok.', err);
  336. resolve();
  337. });
  338. })
  339. .then(function() {
  340. return search.buildIndex();
  341. })
  342. .then(function(data) {
  343. if (!data.errors) {
  344. debug('Index created.');
  345. }
  346. return search.addAllPages();
  347. })
  348. .then(function(data) {
  349. if (!data.errors) {
  350. debug('Data is successfully indexed.');
  351. req.flash('successMessage', 'Data is successfully indexed.');
  352. }
  353. else {
  354. debug('Data index error.', data.errors);
  355. req.flash('errorMessage', `Data index error: ${data.errors}`);
  356. }
  357. return res.redirect('/admin/search');
  358. })
  359. .catch(function(err) {
  360. debug('Error', err);
  361. req.flash('errorMessage', `Error: ${err}`);
  362. return res.redirect('/admin/search');
  363. });
  364. };
  365. actions.user = {};
  366. actions.user.index = function(req, res) {
  367. var page = parseInt(req.query.page) || 1;
  368. User.findUsersWithPagination({page: page}, function(err, result) {
  369. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  370. return res.render('admin/users', {
  371. users: result.docs,
  372. pager: pager
  373. });
  374. });
  375. };
  376. actions.user.invite = function(req, res) {
  377. var form = req.form.inviteForm;
  378. var toSendEmail = form.sendEmail || false;
  379. if (req.form.isValid) {
  380. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, function(err, userList) {
  381. if (err) {
  382. req.flash('errorMessage', req.form.errors.join('\n'));
  383. }
  384. else {
  385. req.flash('createdUser', userList);
  386. }
  387. return res.redirect('/admin/users');
  388. });
  389. }
  390. else {
  391. req.flash('errorMessage', req.form.errors.join('\n'));
  392. return res.redirect('/admin/users');
  393. }
  394. };
  395. actions.user.makeAdmin = function(req, res) {
  396. var id = req.params.id;
  397. User.findById(id, function(err, userData) {
  398. userData.makeAdmin(function(err, userData) {
  399. if (err === null) {
  400. req.flash('successMessage', userData.name + 'さんのアカウントを管理者に設定しました。');
  401. }
  402. else {
  403. req.flash('errorMessage', '更新に失敗しました。');
  404. debug(err, userData);
  405. }
  406. return res.redirect('/admin/users');
  407. });
  408. });
  409. };
  410. actions.user.removeFromAdmin = function(req, res) {
  411. var id = req.params.id;
  412. User.findById(id, function(err, userData) {
  413. userData.removeFromAdmin(function(err, userData) {
  414. if (err === null) {
  415. req.flash('successMessage', userData.name + 'さんのアカウントを管理者から外しました。');
  416. }
  417. else {
  418. req.flash('errorMessage', '更新に失敗しました。');
  419. debug(err, userData);
  420. }
  421. return res.redirect('/admin/users');
  422. });
  423. });
  424. };
  425. actions.user.activate = function(req, res) {
  426. var id = req.params.id;
  427. User.findById(id, function(err, userData) {
  428. userData.statusActivate(function(err, userData) {
  429. if (err === null) {
  430. req.flash('successMessage', userData.name + 'さんのアカウントを有効化しました');
  431. }
  432. else {
  433. req.flash('errorMessage', '更新に失敗しました。');
  434. debug(err, userData);
  435. }
  436. return res.redirect('/admin/users');
  437. });
  438. });
  439. };
  440. actions.user.suspend = function(req, res) {
  441. var id = req.params.id;
  442. User.findById(id, function(err, userData) {
  443. userData.statusSuspend(function(err, userData) {
  444. if (err === null) {
  445. req.flash('successMessage', userData.name + 'さんのアカウントを利用停止にしました');
  446. }
  447. else {
  448. req.flash('errorMessage', '更新に失敗しました。');
  449. debug(err, userData);
  450. }
  451. return res.redirect('/admin/users');
  452. });
  453. });
  454. };
  455. actions.user.remove = function(req, res) {
  456. const id = req.params.id;
  457. let username = '';
  458. return new Promise((resolve, reject) => {
  459. User.findById(id, (err, userData) => {
  460. username = userData.username;
  461. return resolve(userData);
  462. });
  463. })
  464. .then((userData) => {
  465. return new Promise((resolve, reject) => {
  466. userData.statusDelete((err, userData) => {
  467. if (err) {
  468. reject(err);
  469. }
  470. resolve(userData);
  471. });
  472. });
  473. })
  474. .then((userData) => {
  475. // remove all External Accounts
  476. return ExternalAccount.remove({user: userData}).then(() => userData);
  477. })
  478. .then((userData) => {
  479. return Page.removePageByPath(`/user/${username}`).then(() => userData);
  480. })
  481. .then((userData) => {
  482. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  483. return res.redirect('/admin/users');
  484. })
  485. .catch((err) => {
  486. req.flash('errorMessage', '削除に失敗しました。');
  487. return res.redirect('/admin/users');
  488. });
  489. };
  490. // これやったときの relation の挙動未確認
  491. actions.user.removeCompletely = function(req, res) {
  492. // ユーザーの物理削除
  493. var id = req.params.id;
  494. User.removeCompletelyById(id, function(err, removed) {
  495. if (err) {
  496. debug('Error while removing user.', err, id);
  497. req.flash('errorMessage', '完全な削除に失敗しました。');
  498. }
  499. else {
  500. req.flash('successMessage', '削除しました');
  501. }
  502. return res.redirect('/admin/users');
  503. });
  504. };
  505. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  506. actions.user.resetPassword = function(req, res) {
  507. const id = req.body.user_id;
  508. const User = crowi.model('User');
  509. User.resetPasswordByRandomString(id)
  510. .then(function(data) {
  511. data.user = User.filterToPublicFields(data.user);
  512. return res.json(ApiResponse.success(data));
  513. }).catch(function(err) {
  514. debug('Error on reseting password', err);
  515. return res.json(ApiResponse.error('Error'));
  516. });
  517. };
  518. actions.externalAccount = {};
  519. actions.externalAccount.index = function(req, res) {
  520. const page = parseInt(req.query.page) || 1;
  521. ExternalAccount.findAllWithPagination({page})
  522. .then((result) => {
  523. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  524. return res.render('admin/external-accounts', {
  525. accounts: result.docs,
  526. pager: pager
  527. });
  528. });
  529. };
  530. actions.externalAccount.remove = function(req, res) {
  531. const accountId = req.params.id;
  532. ExternalAccount.findOneAndRemove({accountId})
  533. .then((result) => {
  534. if (result == null) {
  535. req.flash('errorMessage', '削除に失敗しました。');
  536. return res.redirect('/admin/users/external-accounts');
  537. }
  538. else {
  539. req.flash('successMessage', `外部アカウント '${accountId}' を削除しました`);
  540. return res.redirect('/admin/users/external-accounts');
  541. }
  542. });
  543. };
  544. actions.userGroup = {};
  545. actions.userGroup.index = function(req, res) {
  546. var page = parseInt(req.query.page) || 1;
  547. var renderVar = {
  548. userGroups: [],
  549. userGroupRelations: new Map(),
  550. pager: null,
  551. };
  552. UserGroup.findUserGroupsWithPagination({ page: page })
  553. .then((result) => {
  554. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  555. var userGroups = result.docs;
  556. renderVar.userGroups = userGroups;
  557. renderVar.pager = pager;
  558. return userGroups.map((userGroup) => {
  559. return new Promise((resolve, reject) => {
  560. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  561. .then((relations) => {
  562. return resolve([userGroup, relations]);
  563. });
  564. });
  565. });
  566. })
  567. .then((allRelationsPromise) => {
  568. return Promise.all(allRelationsPromise);
  569. })
  570. .then((relations) => {
  571. renderVar.userGroupRelations = new Map(relations);
  572. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  573. return res.render('admin/user-groups', renderVar);
  574. })
  575. .catch( function(err) {
  576. debug('Error on find all relations', err);
  577. return res.json(ApiResponse.error('Error'));
  578. });
  579. };
  580. // グループ詳細
  581. actions.userGroup.detail = function(req, res) {
  582. const userGroupId = req.params.id;
  583. const renderVar = {
  584. userGroup: null,
  585. userGroupRelations: [],
  586. pageGroupRelations: [],
  587. notRelatedusers: []
  588. };
  589. let targetUserGroup = null;
  590. UserGroup.findOne({ _id: userGroupId})
  591. .then(function(userGroup) {
  592. targetUserGroup = userGroup;
  593. if (targetUserGroup == null) {
  594. req.flash('errorMessage', 'グループがありません');
  595. throw new Error('no userGroup is exists. ', name);
  596. }
  597. else {
  598. renderVar.userGroup = targetUserGroup;
  599. return Promise.all([
  600. // get all user and group relations
  601. UserGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  602. // get all page and group relations
  603. PageGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  604. // get all not related users for group
  605. UserGroupRelation.findUserByNotRelatedGroup(targetUserGroup),
  606. ]);
  607. }
  608. })
  609. .then((resolves) => {
  610. renderVar.userGroupRelations = resolves[0];
  611. renderVar.pageGroupRelations = resolves[1];
  612. renderVar.notRelatedusers = resolves[2];
  613. debug('notRelatedusers', renderVar.notRelatedusers);
  614. return res.render('admin/user-group-detail', renderVar);
  615. })
  616. .catch((err) => {
  617. req.flash('errorMessage', 'ユーザグループの検索に失敗しました');
  618. debug('Error on get userGroupDetail', err);
  619. return res.redirect('/admin/user-groups');
  620. });
  621. };
  622. //グループの生成
  623. actions.userGroup.create = function(req, res) {
  624. const form = req.form.createGroupForm;
  625. if (req.form.isValid) {
  626. const userGroupName = crowi.xss.process(form.userGroupName);
  627. UserGroup.createGroupByName(userGroupName)
  628. .then((newUserGroup) => {
  629. req.flash('successMessage', newUserGroup.name);
  630. req.flash('createdUserGroup', newUserGroup);
  631. return res.redirect('/admin/user-groups');
  632. })
  633. .catch((err) => {
  634. debug('create userGroup error:', err);
  635. req.flash('errorMessage', '同じグループ名が既に存在します。');
  636. });
  637. }
  638. else {
  639. req.flash('errorMessage', req.form.errors.join('\n'));
  640. return res.redirect('/admin/user-groups');
  641. }
  642. };
  643. //
  644. actions.userGroup.update = function(req, res) {
  645. const userGroupId = req.params.userGroupId;
  646. const name = crowi.xss.process(req.body.name);
  647. UserGroup.findById(userGroupId)
  648. .then((userGroupData) => {
  649. if (userGroupData == null) {
  650. req.flash('errorMessage', 'グループの検索に失敗しました。');
  651. return new Promise();
  652. }
  653. else {
  654. // 名前存在チェック
  655. return UserGroup.isRegisterableName(name)
  656. .then((isRegisterableName) => {
  657. // 既に存在するグループ名に更新しようとした場合はエラー
  658. if (!isRegisterableName) {
  659. req.flash('errorMessage', 'グループ名が既に存在します。');
  660. }
  661. else {
  662. return userGroupData.updateName(name)
  663. .then(() => {
  664. req.flash('successMessage', 'グループ名を更新しました。');
  665. })
  666. .catch((err) => {
  667. req.flash('errorMessage', 'グループ名の更新に失敗しました。');
  668. });
  669. }
  670. });
  671. }
  672. })
  673. .then(() => {
  674. return res.redirect('/admin/user-group-detail/' + userGroupId);
  675. });
  676. };
  677. actions.userGroup.uploadGroupPicture = function(req, res) {
  678. var fileUploader = require('../util/fileUploader')(crowi, app);
  679. //var storagePlugin = new pluginService('storage');
  680. //var storage = require('../service/storage').StorageService(config);
  681. var userGroupId = req.params.userGroupId;
  682. var tmpFile = req.file || null;
  683. if (!tmpFile) {
  684. return res.json({
  685. 'status': false,
  686. 'message': 'File type error.'
  687. });
  688. }
  689. UserGroup.findById(userGroupId, function(err, userGroupData) {
  690. if (!userGroupData) {
  691. return res.json({
  692. 'status': false,
  693. 'message': 'UserGroup error.'
  694. });
  695. }
  696. var tmpPath = tmpFile.path;
  697. var filePath = UserGroup.createUserGroupPictureFilePath(userGroupData, tmpFile.filename + tmpFile.originalname);
  698. var acceptableFileType = /image\/.+/;
  699. if (!tmpFile.mimetype.match(acceptableFileType)) {
  700. return res.json({
  701. 'status': false,
  702. 'message': 'File type error. Only image files is allowed to set as user picture.',
  703. });
  704. }
  705. var tmpFileStream = fs.createReadStream(tmpPath, { flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  706. fileUploader.uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
  707. .then(function(data) {
  708. var imageUrl = fileUploader.generateUrl(filePath);
  709. userGroupData.updateImage(imageUrl)
  710. .then(() => {
  711. fs.unlink(tmpPath, function(err) {
  712. if (err) {
  713. debug('Error while deleting tmp file.', err);
  714. }
  715. return res.json({
  716. 'status': true,
  717. 'url': imageUrl,
  718. 'message': '',
  719. });
  720. });
  721. });
  722. }).catch(function(err) {
  723. debug('Uploading error', err);
  724. return res.json({
  725. 'status': false,
  726. 'message': 'Error while uploading to ',
  727. });
  728. });
  729. });
  730. };
  731. actions.userGroup.deletePicture = function(req, res) {
  732. const userGroupId = req.params.userGroupId;
  733. let userGroupName = null;
  734. UserGroup.findById(userGroupId)
  735. .then((userGroupData) => {
  736. if (userGroupData == null) {
  737. return Promise.reject();
  738. }
  739. else {
  740. userGroupName = userGroupData.name;
  741. return userGroupData.deleteImage();
  742. }
  743. })
  744. .then((updated) => {
  745. req.flash('successMessage', 'Deleted group picture');
  746. return res.redirect('/admin/user-group-detail/' + userGroupId);
  747. })
  748. .catch((err) => {
  749. debug('An error occured.', err);
  750. req.flash('errorMessage', 'Error while deleting group picture');
  751. if (userGroupName == null) {
  752. return res.redirect('/admin/user-groups/');
  753. }
  754. else {
  755. return res.redirect('/admin/user-group-detail/' + userGroupId);
  756. }
  757. });
  758. };
  759. // app.post('/_api/admin/user-group/delete' , admin.userGroup.removeCompletely);
  760. actions.userGroup.removeCompletely = function(req, res) {
  761. const id = req.body.user_group_id;
  762. const fileUploader = require('../util/fileUploader')(crowi, app);
  763. UserGroup.removeCompletelyById(id)
  764. //// TODO remove attachments
  765. // couldn't remove because filePath includes '/uploads/uploads'
  766. // Error: ENOENT: no such file or directory, unlink 'C:\dev\growi\public\uploads\uploads\userGroup\5b1df18ab69611651cc71495.png
  767. //
  768. // .then(removed => {
  769. // if (removed.image != null) {
  770. // fileUploader.deleteFile(null, removed.image);
  771. // }
  772. // })
  773. .then(() => {
  774. req.flash('successMessage', '削除しました');
  775. return res.redirect('/admin/user-groups');
  776. })
  777. .catch((err) => {
  778. debug('Error while removing userGroup.', err, id);
  779. req.flash('errorMessage', '完全な削除に失敗しました。');
  780. return res.redirect('/admin/user-groups');
  781. });
  782. };
  783. actions.userGroupRelation = {};
  784. actions.userGroupRelation.index = function(req, res) {
  785. };
  786. actions.userGroupRelation.create = function(req, res) {
  787. const User = crowi.model('User');
  788. const UserGroup = crowi.model('UserGroup');
  789. const UserGroupRelation = crowi.model('UserGroupRelation');
  790. // req params
  791. const userName = req.body.user_name;
  792. const userGroupId = req.body.user_group_id;
  793. let user = null;
  794. let userGroup = null;
  795. Promise.all([
  796. // ユーザグループをIDで検索
  797. UserGroup.findById(userGroupId),
  798. // ユーザを名前で検索
  799. User.findUserByUsername(userName),
  800. ])
  801. .then((resolves) => {
  802. userGroup = resolves[0];
  803. user = resolves[1];
  804. // Relation を作成
  805. UserGroupRelation.createRelation(userGroup, user);
  806. })
  807. .then((result) => {
  808. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  809. }).catch((err) => {
  810. debug('Error on create user-group relation', err);
  811. req.flash('errorMessage', 'Error on create user-group relation');
  812. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  813. });
  814. };
  815. actions.userGroupRelation.remove = function(req, res) {
  816. const UserGroupRelation = crowi.model('UserGroupRelation');
  817. const userGroupId = req.params.id;
  818. const relationId = req.params.relationId;
  819. UserGroupRelation.removeById(relationId)
  820. .then(() =>{
  821. return res.redirect('/admin/user-group-detail/' + userGroupId);
  822. })
  823. .catch((err) => {
  824. debug('Error on remove user-group-relation', err);
  825. req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
  826. });
  827. };
  828. actions.api = {};
  829. actions.api.appSetting = function(req, res) {
  830. var form = req.form.settingForm;
  831. if (req.form.isValid) {
  832. debug('form content', form);
  833. // mail setting ならここで validation
  834. if (form['mail:from']) {
  835. validateMailSetting(req, form, function(err, data) {
  836. debug('Error validate mail setting: ', err, data);
  837. if (err) {
  838. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  839. return res.json({status: false, message: req.form.errors.join('\n')});
  840. }
  841. return saveSetting(req, res, form);
  842. });
  843. }
  844. else {
  845. return saveSetting(req, res, form);
  846. }
  847. }
  848. else {
  849. return res.json({status: false, message: req.form.errors.join('\n')});
  850. }
  851. };
  852. actions.api.securitySetting = function(req, res) {
  853. const form = req.form.settingForm;
  854. if (req.form.isValid) {
  855. debug('form content', form);
  856. return saveSetting(req, res, form);
  857. }
  858. else {
  859. return res.json({status: false, message: req.form.errors.join('\n')});
  860. }
  861. };
  862. actions.api.securityPassportLdapSetting = function(req, res) {
  863. var form = req.form.settingForm;
  864. if (!req.form.isValid) {
  865. return res.json({status: false, message: req.form.errors.join('\n')});
  866. }
  867. debug('form content', form);
  868. return saveSettingAsync(form)
  869. .then(() => {
  870. const config = crowi.getConfig();
  871. // reset strategy
  872. crowi.passportService.resetLdapStrategy();
  873. // setup strategy
  874. if (Config.isEnabledPassportLdap(config)) {
  875. crowi.passportService.setupLdapStrategy(true);
  876. }
  877. return;
  878. })
  879. .then(() => {
  880. res.json({status: true});
  881. });
  882. };
  883. actions.api.securityPassportGoogleSetting = async(req, res) => {
  884. const form = req.form.settingForm;
  885. if (!req.form.isValid) {
  886. return res.json({status: false, message: req.form.errors.join('\n')});
  887. }
  888. debug('form content', form);
  889. await saveSettingAsync(form);
  890. const config = await crowi.getConfig();
  891. // reset strategy
  892. await crowi.passportService.resetGoogleStrategy();
  893. // setup strategy
  894. if (Config.isEnabledPassportGoogle(config)) {
  895. try {
  896. await crowi.passportService.setupGoogleStrategy(true);
  897. }
  898. catch (err) {
  899. // reset
  900. await crowi.passportService.resetGoogleStrategy();
  901. return res.json({status: false, message: err.message});
  902. }
  903. }
  904. return res.json({status: true});
  905. };
  906. actions.api.securityPassportGitHubSetting = async(req, res) => {
  907. const form = req.form.settingForm;
  908. if (!req.form.isValid) {
  909. return res.json({status: false, message: req.form.errors.join('\n')});
  910. }
  911. debug('form content', form);
  912. await saveSettingAsync(form);
  913. const config = await crowi.getConfig();
  914. // reset strategy
  915. await crowi.passportService.resetGitHubStrategy();
  916. // setup strategy
  917. if (Config.isEnabledPassportGitHub(config)) {
  918. try {
  919. await crowi.passportService.setupGitHubStrategy(true);
  920. }
  921. catch (err) {
  922. // reset
  923. await crowi.passportService.resetGitHubStrategy();
  924. return res.json({status: false, message: err.message});
  925. }
  926. }
  927. return res.json({status: true});
  928. };
  929. actions.api.customizeSetting = function(req, res) {
  930. const form = req.form.settingForm;
  931. if (req.form.isValid) {
  932. debug('form content', form);
  933. return saveSetting(req, res, form);
  934. }
  935. else {
  936. return res.json({status: false, message: req.form.errors.join('\n')});
  937. }
  938. };
  939. actions.api.customizeSetting = function(req, res) {
  940. const form = req.form.settingForm;
  941. if (req.form.isValid) {
  942. debug('form content', form);
  943. return saveSetting(req, res, form);
  944. }
  945. else {
  946. return res.json({status: false, message: req.form.errors.join('\n')});
  947. }
  948. };
  949. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  950. actions.api.notificationAdd = function(req, res) {
  951. var UpdatePost = crowi.model('UpdatePost');
  952. var pathPattern = req.body.pathPattern;
  953. var channel = req.body.channel;
  954. debug('notification.add', pathPattern, channel);
  955. UpdatePost.create(pathPattern, channel, req.user)
  956. .then(function(doc) {
  957. debug('Successfully save updatePost', doc);
  958. // fixme: うーん
  959. doc.creator = doc.creator._id.toString();
  960. return res.json(ApiResponse.success({updatePost: doc}));
  961. }).catch(function(err) {
  962. debug('Failed to save updatePost', err);
  963. return res.json(ApiResponse.error());
  964. });
  965. };
  966. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  967. actions.api.notificationRemove = function(req, res) {
  968. var UpdatePost = crowi.model('UpdatePost');
  969. var id = req.body.id;
  970. UpdatePost.remove(id)
  971. .then(function() {
  972. debug('Successfully remove updatePost');
  973. return res.json(ApiResponse.success({}));
  974. }).catch(function(err) {
  975. debug('Failed to remove updatePost', err);
  976. return res.json(ApiResponse.error());
  977. });
  978. };
  979. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  980. actions.api.usersSearch = function(req, res) {
  981. const User = crowi.model('User');
  982. const email =req.query.email;
  983. User.findUsersByPartOfEmail(email, {})
  984. .then(users => {
  985. const result = {
  986. data: users
  987. };
  988. return res.json(ApiResponse.success(result));
  989. }).catch(err => {
  990. return res.json(ApiResponse.error());
  991. });
  992. };
  993. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  994. const id =req.query.id;
  995. try {
  996. GlobalNotificationSetting.Parent.toggleIsEnabled(id);
  997. return res.json(ApiResponse.success());
  998. }
  999. catch (err) {
  1000. return res.json(ApiResponse.error());
  1001. }
  1002. };
  1003. /**
  1004. * save settings, update config cache, and response json
  1005. *
  1006. * @param {any} req
  1007. * @param {any} res
  1008. * @param {any} form
  1009. */
  1010. function saveSetting(req, res, form) {
  1011. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  1012. Config.updateConfigCache('crowi', config);
  1013. return res.json({status: true});
  1014. });
  1015. }
  1016. /**
  1017. * save settings, update config cache ONLY. (this method don't response json)
  1018. *
  1019. * @param {any} form
  1020. * @returns
  1021. */
  1022. function saveSettingAsync(form) {
  1023. return new Promise((resolve, reject) => {
  1024. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  1025. if (err) {
  1026. return reject(err);
  1027. }
  1028. Config.updateConfigCache('crowi', config);
  1029. return resolve();
  1030. });
  1031. });
  1032. }
  1033. function validateMailSetting(req, form, callback) {
  1034. var mailer = crowi.mailer;
  1035. var option = {
  1036. host: form['mail:smtpHost'],
  1037. port: form['mail:smtpPort'],
  1038. };
  1039. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1040. option.auth = {
  1041. user: form['mail:smtpUser'],
  1042. pass: form['mail:smtpPassword'],
  1043. };
  1044. }
  1045. if (option.port === 465) {
  1046. option.secure = true;
  1047. }
  1048. var smtpClient = mailer.createSMTPClient(option);
  1049. debug('mailer setup for validate SMTP setting', smtpClient);
  1050. smtpClient.sendMail({
  1051. from: form['mail:from'],
  1052. to: req.user.email,
  1053. subject: 'Wiki管理設定のアップデートによるメール通知',
  1054. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  1055. }, callback);
  1056. }
  1057. return actions;
  1058. };