admin.js 42 KB

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