admin.js 37 KB

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