admin.js 38 KB

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