admin.js 41 KB

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