admin.js 37 KB

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