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