admin.js 37 KB

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