admin.js 39 KB

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