admin.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. /* eslint-disable no-use-before-define */
  2. module.exports = function(crowi, app) {
  3. const debug = require('debug')('growi:routes:admin');
  4. const logger = require('@alias/logger')('growi:routes:admin');
  5. const models = crowi.models;
  6. const Page = models.Page;
  7. const User = models.User;
  8. const ExternalAccount = models.ExternalAccount;
  9. const UserGroup = models.UserGroup;
  10. const UserGroupRelation = models.UserGroupRelation;
  11. const GlobalNotificationSetting = models.GlobalNotificationSetting;
  12. const GlobalNotificationMailSetting = models.GlobalNotificationMailSetting;
  13. const GlobalNotificationSlackSetting = models.GlobalNotificationSlackSetting; // eslint-disable-line no-unused-vars
  14. const {
  15. configManager,
  16. aclService,
  17. slackNotificationService,
  18. customizeService,
  19. } = crowi;
  20. const recommendedWhitelist = require('@commons/service/xss/recommended-whitelist');
  21. const PluginUtils = require('../plugins/plugin-utils');
  22. const ApiResponse = require('../util/apiResponse');
  23. const importer = require('../util/importer')(crowi);
  24. const searchEvent = crowi.event('search');
  25. const pluginUtils = new PluginUtils();
  26. const MAX_PAGE_LIST = 50;
  27. const actions = {};
  28. function createPager(total, limit, page, pagesCount, maxPageList) {
  29. const pager = {
  30. page,
  31. pagesCount,
  32. pages: [],
  33. total,
  34. previous: null,
  35. previousDots: false,
  36. next: null,
  37. nextDots: false,
  38. };
  39. if (page > 1) {
  40. pager.previous = page - 1;
  41. }
  42. if (page < pagesCount) {
  43. pager.next = page + 1;
  44. }
  45. let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2));
  46. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2));
  47. if (pagerMin === 1) {
  48. if (MAX_PAGE_LIST < pagesCount) {
  49. pagerMax = MAX_PAGE_LIST;
  50. }
  51. else {
  52. pagerMax = pagesCount;
  53. }
  54. }
  55. if (pagerMax === pagesCount) {
  56. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  57. pagerMin = 1;
  58. }
  59. else {
  60. pagerMin = pagerMax - MAX_PAGE_LIST;
  61. }
  62. }
  63. pager.previousDots = null;
  64. if (pagerMin > 1) {
  65. pager.previousDots = true;
  66. }
  67. pager.nextDots = null;
  68. if (pagerMax < pagesCount) {
  69. pager.nextDots = true;
  70. }
  71. for (let i = pagerMin; i <= pagerMax; i++) {
  72. pager.pages.push(i);
  73. }
  74. return pager;
  75. }
  76. actions.index = function(req, res) {
  77. return res.render('admin/index', {
  78. plugins: pluginUtils.listPlugins(crowi.rootDir),
  79. });
  80. };
  81. // app.get('/admin/app' , admin.app.index);
  82. actions.app = {};
  83. actions.app.index = function(req, res) {
  84. return res.render('admin/app');
  85. };
  86. actions.app.settingUpdate = function(req, res) {
  87. };
  88. // app.get('/admin/security' , admin.security.index);
  89. actions.security = {};
  90. actions.security.index = function(req, res) {
  91. const isWikiModeForced = aclService.isWikiModeForced();
  92. const guestModeValue = aclService.getGuestModeValue();
  93. return res.render('admin/security', {
  94. isWikiModeForced,
  95. guestModeValue,
  96. });
  97. };
  98. // app.get('/admin/markdown' , admin.markdown.index);
  99. actions.markdown = {};
  100. actions.markdown.index = function(req, res) {
  101. const markdownSetting = configManager.getConfigByPrefix('markdown', 'markdown:');
  102. return res.render('admin/markdown', {
  103. markdownSetting,
  104. recommendedWhitelist,
  105. });
  106. };
  107. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  108. actions.markdown.lineBreaksSetting = async function(req, res) {
  109. const markdownSetting = req.form.markdownSetting;
  110. if (req.form.isValid) {
  111. await configManager.updateConfigsInTheSameNamespace('markdown', markdownSetting);
  112. req.flash('successMessage', ['Successfully updated!']);
  113. }
  114. else {
  115. req.flash('errorMessage', req.form.errors);
  116. }
  117. return res.redirect('/admin/markdown');
  118. };
  119. // app.post('/admin/markdown/presentationSetting' , admin.markdown.presentationSetting);
  120. actions.markdown.presentationSetting = async function(req, res) {
  121. const markdownSetting = req.form.markdownSetting;
  122. if (req.form.isValid) {
  123. await configManager.updateConfigsInTheSameNamespace('markdown', markdownSetting);
  124. req.flash('successMessage', ['Successfully updated!']);
  125. }
  126. else {
  127. req.flash('errorMessage', req.form.errors);
  128. }
  129. return res.redirect('/admin/markdown');
  130. };
  131. // app.post('/admin/markdown/xss-setting' , admin.markdown.xssSetting);
  132. actions.markdown.xssSetting = async function(req, res) {
  133. const xssSetting = req.form.markdownSetting;
  134. xssSetting['markdown:xss:tagWhiteList'] = csvToArray(xssSetting['markdown:xss:tagWhiteList']);
  135. xssSetting['markdown:xss:attrWhiteList'] = csvToArray(xssSetting['markdown:xss:attrWhiteList']);
  136. if (req.form.isValid) {
  137. await configManager.updateConfigsInTheSameNamespace('markdown', xssSetting);
  138. req.flash('successMessage', ['Successfully updated!']);
  139. }
  140. else {
  141. req.flash('errorMessage', req.form.errors);
  142. }
  143. return res.redirect('/admin/markdown');
  144. };
  145. const csvToArray = (string) => {
  146. const array = string.split(',');
  147. return array.map((item) => { return item.trim() });
  148. };
  149. // app.get('/admin/customize' , admin.customize.index);
  150. actions.customize = {};
  151. actions.customize.index = function(req, res) {
  152. const settingForm = configManager.getConfigByPrefix('crowi', 'customize:');
  153. /* eslint-disable quote-props, no-multi-spaces */
  154. const highlightJsCssSelectorOptions = {
  155. 'github': { name: '[Light] GitHub', border: false },
  156. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  157. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  158. 'xcode': { name: '[Light] Xcode', border: true },
  159. 'vs': { name: '[Light] Vs', border: true },
  160. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  161. 'hybrid': { name: '[Dark] Hybrid', border: false },
  162. 'monokai': { name: '[Dark] Monokai', border: false },
  163. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  164. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  165. };
  166. /* eslint-enable quote-props, no-multi-spaces */
  167. return res.render('admin/customize', {
  168. settingForm,
  169. highlightJsCssSelectorOptions,
  170. });
  171. };
  172. // app.get('/admin/notification' , admin.notification.index);
  173. actions.notification = {};
  174. actions.notification.index = async(req, res) => {
  175. const UpdatePost = crowi.model('UpdatePost');
  176. let slackSetting = configManager.getConfigByPrefix('notification', 'slack:');
  177. const hasSlackIwhUrl = !!configManager.getConfig('notification', 'slack:incomingWebhookUrl');
  178. const hasSlackToken = !!configManager.getConfig('notification', 'slack:token');
  179. if (!hasSlackIwhUrl) {
  180. slackSetting['slack:incomingWebhookUrl'] = '';
  181. }
  182. if (req.session.slackSetting) {
  183. slackSetting = req.session.slackSetting;
  184. req.session.slackSetting = null;
  185. }
  186. const globalNotifications = await GlobalNotificationSetting.findAll();
  187. const userNotifications = await UpdatePost.findAll();
  188. return res.render('admin/notification', {
  189. userNotifications,
  190. slackSetting,
  191. hasSlackIwhUrl,
  192. hasSlackToken,
  193. globalNotifications,
  194. });
  195. };
  196. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  197. actions.notification.slackSetting = async function(req, res) {
  198. const slackSetting = req.form.slackSetting;
  199. if (req.form.isValid) {
  200. await configManager.updateConfigsInTheSameNamespace('notification', slackSetting);
  201. req.flash('successMessage', ['Successfully Updated!']);
  202. // Re-setup
  203. crowi.setupSlack().then(() => {
  204. });
  205. }
  206. else {
  207. req.flash('errorMessage', req.form.errors);
  208. }
  209. return res.redirect('/admin/notification');
  210. };
  211. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  212. actions.notification.slackAuth = function(req, res) {
  213. const code = req.query.code;
  214. if (!code || !slackNotificationService.hasSlackConfig()) {
  215. return res.redirect('/admin/notification');
  216. }
  217. const slack = crowi.slack;
  218. slack.getOauthAccessToken(code)
  219. .then(async(data) => {
  220. debug('oauth response', data);
  221. try {
  222. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  223. req.flash('successMessage', ['Successfully Connected!']);
  224. }
  225. catch (err) {
  226. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  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. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  237. actions.notification.slackIwhSetting = async function(req, res) {
  238. const slackIwhSetting = req.form.slackIwhSetting;
  239. if (req.form.isValid) {
  240. await configManager.updateConfigsInTheSameNamespace('notification', slackIwhSetting);
  241. req.flash('successMessage', ['Successfully Updated!']);
  242. // Re-setup
  243. crowi.setupSlack().then(() => {
  244. return res.redirect('/admin/notification#slack-incoming-webhooks');
  245. });
  246. }
  247. else {
  248. req.flash('errorMessage', req.form.errors);
  249. return res.redirect('/admin/notification#slack-incoming-webhooks');
  250. }
  251. };
  252. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  253. actions.notification.disconnectFromSlack = async function(req, res) {
  254. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  255. req.flash('successMessage', ['Successfully Disconnected!']);
  256. return res.redirect('/admin/notification');
  257. };
  258. actions.globalNotification = {};
  259. actions.globalNotification.detail = async(req, res) => {
  260. const notificationSettingId = req.params.id;
  261. const renderVars = {};
  262. if (notificationSettingId) {
  263. try {
  264. renderVars.setting = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  265. }
  266. catch (err) {
  267. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  268. }
  269. }
  270. return res.render('admin/global-notification-detail', renderVars);
  271. };
  272. actions.globalNotification.create = (req, res) => {
  273. const form = req.form.notificationGlobal;
  274. let setting;
  275. switch (form.notifyToType) {
  276. case 'mail':
  277. setting = new GlobalNotificationMailSetting(crowi);
  278. setting.toEmail = form.toEmail;
  279. break;
  280. // case 'slack':
  281. // setting = new GlobalNotificationSlackSetting(crowi);
  282. // setting.slackChannels = form.slackChannels;
  283. // break;
  284. default:
  285. logger.error('GlobalNotificationSetting Type Error: undefined type');
  286. req.flash('errorMessage', 'Error occurred in creating a new global notification setting: undefined notification type');
  287. return res.redirect('/admin/notification#global-notification');
  288. }
  289. setting.triggerPath = form.triggerPath;
  290. setting.triggerEvents = getNotificationEvents(form);
  291. setting.save();
  292. return res.redirect('/admin/notification#global-notification');
  293. };
  294. actions.globalNotification.update = async(req, res) => {
  295. const form = req.form.notificationGlobal;
  296. const setting = await GlobalNotificationSetting.findOne({ _id: form.id });
  297. switch (form.notifyToType) {
  298. case 'mail':
  299. setting.toEmail = form.toEmail;
  300. break;
  301. // case 'slack':
  302. // setting.slackChannels = form.slackChannels;
  303. // break;
  304. default:
  305. logger.error('GlobalNotificationSetting Type Error: undefined type');
  306. req.flash('errorMessage', 'Error occurred in updating the global notification setting: undefined notification type');
  307. return res.redirect('/admin/notification#global-notification');
  308. }
  309. setting.triggerPath = form.triggerPath;
  310. setting.triggerEvents = getNotificationEvents(form);
  311. setting.save();
  312. return res.redirect('/admin/notification#global-notification');
  313. };
  314. actions.globalNotification.remove = async(req, res) => {
  315. const id = req.params.id;
  316. try {
  317. await GlobalNotificationSetting.findOneAndRemove({ _id: id });
  318. return res.redirect('/admin/notification#global-notification');
  319. }
  320. catch (err) {
  321. req.flash('errorMessage', 'Error in deleting global notification setting');
  322. return res.redirect('/admin/notification#global-notification');
  323. }
  324. };
  325. const getNotificationEvents = (form) => {
  326. const triggerEvents = [];
  327. const triggerEventKeys = Object.keys(form).filter((key) => { return key.match(/^triggerEvent/) });
  328. triggerEventKeys.forEach((key) => {
  329. if (form[key]) {
  330. triggerEvents.push(form[key]);
  331. }
  332. });
  333. return triggerEvents;
  334. };
  335. actions.search = {};
  336. actions.search.index = function(req, res) {
  337. const search = crowi.getSearcher();
  338. if (!search) {
  339. return res.redirect('/admin');
  340. }
  341. return res.render('admin/search', {});
  342. };
  343. actions.user = {};
  344. actions.user.index = async function(req, res) {
  345. const activeUsers = await User.countListByStatus(User.STATUS_ACTIVE);
  346. const userUpperLimit = aclService.userUpperLimit();
  347. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  348. const page = parseInt(req.query.page) || 1;
  349. const result = await User.findUsersWithPagination({
  350. page,
  351. select: User.USER_PUBLIC_FIELDS,
  352. populate: User.IMAGE_POPULATION,
  353. });
  354. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  355. return res.render('admin/users', {
  356. users: result.docs,
  357. pager,
  358. activeUsers,
  359. userUpperLimit,
  360. isUserCountExceedsUpperLimit,
  361. });
  362. };
  363. actions.user.invite = function(req, res) {
  364. const form = req.form.inviteForm;
  365. const toSendEmail = form.sendEmail || false;
  366. if (req.form.isValid) {
  367. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, (err, userList) => {
  368. if (err) {
  369. req.flash('errorMessage', req.form.errors.join('\n'));
  370. }
  371. else {
  372. req.flash('createdUser', userList);
  373. }
  374. return res.redirect('/admin/users');
  375. });
  376. }
  377. else {
  378. req.flash('errorMessage', req.form.errors.join('\n'));
  379. return res.redirect('/admin/users');
  380. }
  381. };
  382. actions.user.makeAdmin = function(req, res) {
  383. const id = req.params.id;
  384. User.findById(id, (err, userData) => {
  385. userData.makeAdmin((err, userData) => {
  386. if (err === null) {
  387. req.flash('successMessage', `${userData.name}さんのアカウントを管理者に設定しました。`);
  388. }
  389. else {
  390. req.flash('errorMessage', '更新に失敗しました。');
  391. debug(err, userData);
  392. }
  393. return res.redirect('/admin/users');
  394. });
  395. });
  396. };
  397. actions.user.removeFromAdmin = function(req, res) {
  398. const id = req.params.id;
  399. User.findById(id, (err, userData) => {
  400. userData.removeFromAdmin((err, userData) => {
  401. if (err === null) {
  402. req.flash('successMessage', `${userData.name}さんのアカウントを管理者から外しました。`);
  403. }
  404. else {
  405. req.flash('errorMessage', '更新に失敗しました。');
  406. debug(err, userData);
  407. }
  408. return res.redirect('/admin/users');
  409. });
  410. });
  411. };
  412. actions.user.activate = async function(req, res) {
  413. // check user upper limit
  414. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  415. if (isUserCountExceedsUpperLimit) {
  416. req.flash('errorMessage', 'ユーザーが上限に達したため有効化できません。');
  417. return res.redirect('/admin/users');
  418. }
  419. const id = req.params.id;
  420. User.findById(id, (err, userData) => {
  421. userData.statusActivate((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. const id = req.params.id;
  435. User.findById(id, (err, userData) => {
  436. userData.statusSuspend((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(() => { return userData });
  470. })
  471. .then((userData) => {
  472. return Page.removeByPath(`/user/${username}`).then(() => { return 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. const id = req.params.id;
  487. User.removeCompletelyById(id, (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 = async function(req, res) {
  500. const id = req.body.user_id;
  501. const User = crowi.model('User');
  502. try {
  503. const newPassword = await User.resetPasswordByRandomString(id);
  504. const user = await User.findById(id);
  505. const result = { user: user.toObject(), newPassword };
  506. return res.json(ApiResponse.success(result));
  507. }
  508. catch (err) {
  509. debug('Error on reseting password', err);
  510. return res.json(ApiResponse.error(err));
  511. }
  512. };
  513. actions.externalAccount = {};
  514. actions.externalAccount.index = function(req, res) {
  515. const page = parseInt(req.query.page) || 1;
  516. ExternalAccount.findAllWithPagination({ page })
  517. .then((result) => {
  518. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  519. return res.render('admin/external-accounts', {
  520. accounts: result.docs,
  521. pager,
  522. });
  523. });
  524. };
  525. actions.externalAccount.remove = async function(req, res) {
  526. const id = req.params.id;
  527. let account = null;
  528. try {
  529. account = await ExternalAccount.findByIdAndRemove(id);
  530. if (account == null) {
  531. throw new Error('削除に失敗しました。');
  532. }
  533. }
  534. catch (err) {
  535. req.flash('errorMessage', err.message);
  536. return res.redirect('/admin/users/external-accounts');
  537. }
  538. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  539. return res.redirect('/admin/users/external-accounts');
  540. };
  541. actions.userGroup = {};
  542. actions.userGroup.index = function(req, res) {
  543. const page = parseInt(req.query.page) || 1;
  544. const isAclEnabled = aclService.isAclEnabled();
  545. const renderVar = {
  546. userGroups: [],
  547. userGroupRelations: new Map(),
  548. pager: null,
  549. isAclEnabled,
  550. };
  551. UserGroup.findUserGroupsWithPagination({ page })
  552. .then((result) => {
  553. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  554. const userGroups = result.docs;
  555. renderVar.userGroups = userGroups;
  556. renderVar.pager = pager;
  557. return userGroups.map((userGroup) => {
  558. return new Promise((resolve, reject) => {
  559. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  560. .then((relations) => {
  561. return resolve({
  562. id: userGroup._id,
  563. relatedUsers: relations.map((relation) => {
  564. return relation.relatedUser;
  565. }),
  566. });
  567. });
  568. });
  569. });
  570. })
  571. .then((allRelationsPromise) => {
  572. return Promise.all(allRelationsPromise);
  573. })
  574. .then((relations) => {
  575. for (const relation of relations) {
  576. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  577. }
  578. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  579. return res.render('admin/user-groups', renderVar);
  580. })
  581. .catch((err) => {
  582. debug('Error on find all relations', err);
  583. return res.json(ApiResponse.error('Error'));
  584. });
  585. };
  586. // グループ詳細
  587. actions.userGroup.detail = async function(req, res) {
  588. const userGroupId = req.params.id;
  589. const renderVar = {
  590. userGroup: null,
  591. userGroupRelations: [],
  592. notRelatedusers: [],
  593. relatedPages: [],
  594. };
  595. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  596. if (userGroup == null) {
  597. logger.error('no userGroup is exists. ', userGroupId);
  598. req.flash('errorMessage', 'グループがありません');
  599. return res.redirect('/admin/user-groups');
  600. }
  601. renderVar.userGroup = userGroup;
  602. const resolves = await Promise.all([
  603. // get all user and group relations
  604. UserGroupRelation.findAllRelationForUserGroup(userGroup),
  605. // get all not related users for group
  606. UserGroupRelation.findUserByNotRelatedGroup(userGroup),
  607. // get all related pages
  608. Page.find({ grant: Page.GRANT_USER_GROUP, grantedGroup: { $in: [userGroup] } }),
  609. ]);
  610. renderVar.userGroupRelations = resolves[0];
  611. renderVar.notRelatedusers = resolves[1];
  612. renderVar.relatedPages = resolves[2];
  613. return res.render('admin/user-group-detail', renderVar);
  614. };
  615. //
  616. actions.userGroup.update = function(req, res) {
  617. const userGroupId = req.params.userGroupId;
  618. const name = crowi.xss.process(req.body.name);
  619. UserGroup.findById(userGroupId)
  620. .then((userGroupData) => {
  621. if (userGroupData == null) {
  622. req.flash('errorMessage', 'グループの検索に失敗しました。');
  623. return new Promise();
  624. }
  625. // 名前存在チェック
  626. return UserGroup.isRegisterableName(name)
  627. .then((isRegisterableName) => {
  628. // 既に存在するグループ名に更新しようとした場合はエラー
  629. if (!isRegisterableName) {
  630. req.flash('errorMessage', 'グループ名が既に存在します。');
  631. }
  632. else {
  633. return userGroupData.updateName(name)
  634. .then(() => {
  635. req.flash('successMessage', 'グループ名を更新しました。');
  636. })
  637. .catch((err) => {
  638. req.flash('errorMessage', 'グループ名の更新に失敗しました。');
  639. });
  640. }
  641. });
  642. })
  643. .then(() => {
  644. return res.redirect(`/admin/user-group-detail/${userGroupId}`);
  645. });
  646. };
  647. actions.userGroupRelation = {};
  648. actions.userGroupRelation.index = function(req, res) {
  649. };
  650. actions.userGroupRelation.create = function(req, res) {
  651. const User = crowi.model('User');
  652. const UserGroup = crowi.model('UserGroup');
  653. const UserGroupRelation = crowi.model('UserGroupRelation');
  654. // req params
  655. const userName = req.body.user_name;
  656. const userGroupId = req.body.user_group_id;
  657. let user = null;
  658. let userGroup = null;
  659. Promise.all([
  660. // ユーザグループをIDで検索
  661. UserGroup.findById(userGroupId),
  662. // ユーザを名前で検索
  663. User.findUserByUsername(userName),
  664. ])
  665. .then((resolves) => {
  666. userGroup = resolves[0];
  667. user = resolves[1];
  668. // Relation を作成
  669. UserGroupRelation.createRelation(userGroup, user);
  670. })
  671. .then((result) => {
  672. return res.redirect(`/admin/user-group-detail/${userGroup.id}`);
  673. })
  674. .catch((err) => {
  675. debug('Error on create user-group relation', err);
  676. req.flash('errorMessage', 'Error on create user-group relation');
  677. return res.redirect(`/admin/user-group-detail/${userGroup.id}`);
  678. });
  679. };
  680. actions.userGroupRelation.remove = function(req, res) {
  681. const UserGroupRelation = crowi.model('UserGroupRelation');
  682. const userGroupId = req.params.id;
  683. const relationId = req.params.relationId;
  684. UserGroupRelation.removeById(relationId)
  685. .then(() => {
  686. return res.redirect(`/admin/user-group-detail/${userGroupId}`);
  687. })
  688. .catch((err) => {
  689. debug('Error on remove user-group-relation', err);
  690. req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
  691. });
  692. };
  693. // Importer management
  694. actions.importer = {};
  695. actions.importer.index = function(req, res) {
  696. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  697. return res.render('admin/importer', {
  698. settingForm,
  699. });
  700. };
  701. actions.api = {};
  702. actions.api.appSetting = async function(req, res) {
  703. const form = req.form.settingForm;
  704. if (req.form.isValid) {
  705. debug('form content', form);
  706. // mail setting ならここで validation
  707. if (form['mail:from']) {
  708. validateMailSetting(req, form, async(err, data) => {
  709. debug('Error validate mail setting: ', err, data);
  710. if (err) {
  711. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  712. return res.json({ status: false, message: req.form.errors.join('\n') });
  713. }
  714. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  715. return res.json({ status: true });
  716. });
  717. }
  718. else {
  719. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  720. return res.json({ status: true });
  721. }
  722. }
  723. else {
  724. return res.json({ status: false, message: req.form.errors.join('\n') });
  725. }
  726. };
  727. actions.api.asyncAppSetting = async(req, res) => {
  728. const form = req.form.settingForm;
  729. if (!req.form.isValid) {
  730. return res.json({ status: false, message: req.form.errors.join('\n') });
  731. }
  732. debug('form content', form);
  733. try {
  734. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  735. return res.json({ status: true });
  736. }
  737. catch (err) {
  738. logger.error(err);
  739. return res.json({ status: false });
  740. }
  741. };
  742. actions.api.securitySetting = async function(req, res) {
  743. if (!req.form.isValid) {
  744. return res.json({ status: false, message: req.form.errors.join('\n') });
  745. }
  746. const form = req.form.settingForm;
  747. if (aclService.isWikiModeForced()) {
  748. logger.debug('security:restrictGuestMode will not be changed because wiki mode is forced to set');
  749. delete form['security:restrictGuestMode'];
  750. }
  751. try {
  752. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  753. return res.json({ status: true });
  754. }
  755. catch (err) {
  756. logger.error(err);
  757. return res.json({ status: false });
  758. }
  759. };
  760. actions.api.securityPassportLdapSetting = function(req, res) {
  761. const form = req.form.settingForm;
  762. if (!req.form.isValid) {
  763. return res.json({ status: false, message: req.form.errors.join('\n') });
  764. }
  765. debug('form content', form);
  766. return configManager.updateConfigsInTheSameNamespace('crowi', form)
  767. .then(() => {
  768. // reset strategy
  769. crowi.passportService.resetLdapStrategy();
  770. // setup strategy
  771. if (configManager.getConfig('crowi', 'security:passport-ldap:isEnabled')) {
  772. crowi.passportService.setupLdapStrategy(true);
  773. }
  774. return;
  775. })
  776. .then(() => {
  777. res.json({ status: true });
  778. });
  779. };
  780. actions.api.securityPassportSamlSetting = async(req, res) => {
  781. const form = req.form.settingForm;
  782. validateSamlSettingForm(req.form, req.t);
  783. if (!req.form.isValid) {
  784. return res.json({ status: false, message: req.form.errors.join('\n') });
  785. }
  786. debug('form content', form);
  787. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  788. // reset strategy
  789. await crowi.passportService.resetSamlStrategy();
  790. // setup strategy
  791. if (configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  792. try {
  793. await crowi.passportService.setupSamlStrategy(true);
  794. }
  795. catch (err) {
  796. // reset
  797. await crowi.passportService.resetSamlStrategy();
  798. return res.json({ status: false, message: err.message });
  799. }
  800. }
  801. return res.json({ status: true });
  802. };
  803. actions.api.securityPassportBasicSetting = async(req, res) => {
  804. const form = req.form.settingForm;
  805. if (!req.form.isValid) {
  806. return res.json({ status: false, message: req.form.errors.join('\n') });
  807. }
  808. debug('form content', form);
  809. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  810. // reset strategy
  811. await crowi.passportService.resetBasicStrategy();
  812. // setup strategy
  813. if (configManager.getConfig('crowi', 'security:passport-basic:isEnabled')) {
  814. try {
  815. await crowi.passportService.setupBasicStrategy(true);
  816. }
  817. catch (err) {
  818. // reset
  819. await crowi.passportService.resetBasicStrategy();
  820. return res.json({ status: false, message: err.message });
  821. }
  822. }
  823. return res.json({ status: true });
  824. };
  825. actions.api.securityPassportGoogleSetting = async(req, res) => {
  826. const form = req.form.settingForm;
  827. if (!req.form.isValid) {
  828. return res.json({ status: false, message: req.form.errors.join('\n') });
  829. }
  830. debug('form content', form);
  831. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  832. // reset strategy
  833. await crowi.passportService.resetGoogleStrategy();
  834. // setup strategy
  835. if (configManager.getConfig('crowi', 'security:passport-google:isEnabled')) {
  836. try {
  837. await crowi.passportService.setupGoogleStrategy(true);
  838. }
  839. catch (err) {
  840. // reset
  841. await crowi.passportService.resetGoogleStrategy();
  842. return res.json({ status: false, message: err.message });
  843. }
  844. }
  845. return res.json({ status: true });
  846. };
  847. actions.api.securityPassportGitHubSetting = async(req, res) => {
  848. const form = req.form.settingForm;
  849. if (!req.form.isValid) {
  850. return res.json({ status: false, message: req.form.errors.join('\n') });
  851. }
  852. debug('form content', form);
  853. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  854. // reset strategy
  855. await crowi.passportService.resetGitHubStrategy();
  856. // setup strategy
  857. if (configManager.getConfig('crowi', 'security:passport-github:isEnabled')) {
  858. try {
  859. await crowi.passportService.setupGitHubStrategy(true);
  860. }
  861. catch (err) {
  862. // reset
  863. await crowi.passportService.resetGitHubStrategy();
  864. return res.json({ status: false, message: err.message });
  865. }
  866. }
  867. return res.json({ status: true });
  868. };
  869. actions.api.securityPassportTwitterSetting = async(req, res) => {
  870. const form = req.form.settingForm;
  871. if (!req.form.isValid) {
  872. return res.json({ status: false, message: req.form.errors.join('\n') });
  873. }
  874. debug('form content', form);
  875. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  876. // reset strategy
  877. await crowi.passportService.resetTwitterStrategy();
  878. // setup strategy
  879. if (configManager.getConfig('crowi', 'security:passport-twitter:isEnabled')) {
  880. try {
  881. await crowi.passportService.setupTwitterStrategy(true);
  882. }
  883. catch (err) {
  884. // reset
  885. await crowi.passportService.resetTwitterStrategy();
  886. return res.json({ status: false, message: err.message });
  887. }
  888. }
  889. return res.json({ status: true });
  890. };
  891. actions.api.securityPassportOidcSetting = async(req, res) => {
  892. const form = req.form.settingForm;
  893. if (!req.form.isValid) {
  894. return res.json({ status: false, message: req.form.errors.join('\n') });
  895. }
  896. debug('form content', form);
  897. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  898. // reset strategy
  899. await crowi.passportService.resetOidcStrategy();
  900. // setup strategy
  901. if (configManager.getConfig('crowi', 'security:passport-oidc:isEnabled')) {
  902. try {
  903. await crowi.passportService.setupOidcStrategy(true);
  904. }
  905. catch (err) {
  906. // reset
  907. await crowi.passportService.resetOidcStrategy();
  908. return res.json({ status: false, message: err.message });
  909. }
  910. }
  911. return res.json({ status: true });
  912. };
  913. actions.api.customizeSetting = async function(req, res) {
  914. const form = req.form.settingForm;
  915. if (req.form.isValid) {
  916. debug('form content', form);
  917. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  918. customizeService.initCustomCss();
  919. customizeService.initCustomTitle();
  920. return res.json({ status: true });
  921. }
  922. return res.json({ status: false, message: req.form.errors.join('\n') });
  923. };
  924. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  925. actions.api.notificationAdd = function(req, res) {
  926. const UpdatePost = crowi.model('UpdatePost');
  927. const pathPattern = req.body.pathPattern;
  928. const channel = req.body.channel;
  929. debug('notification.add', pathPattern, channel);
  930. UpdatePost.create(pathPattern, channel, req.user)
  931. .then((doc) => {
  932. debug('Successfully save updatePost', doc);
  933. // fixme: うーん
  934. doc.creator = doc.creator._id.toString();
  935. return res.json(ApiResponse.success({ updatePost: doc }));
  936. })
  937. .catch((err) => {
  938. debug('Failed to save updatePost', err);
  939. return res.json(ApiResponse.error());
  940. });
  941. };
  942. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  943. actions.api.notificationRemove = function(req, res) {
  944. const UpdatePost = crowi.model('UpdatePost');
  945. const id = req.body.id;
  946. UpdatePost.remove(id)
  947. .then(() => {
  948. debug('Successfully remove updatePost');
  949. return res.json(ApiResponse.success({}));
  950. })
  951. .catch((err) => {
  952. debug('Failed to remove updatePost', err);
  953. return res.json(ApiResponse.error());
  954. });
  955. };
  956. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  957. actions.api.usersSearch = function(req, res) {
  958. const User = crowi.model('User');
  959. const email = req.query.email;
  960. User.findUsersByPartOfEmail(email, {})
  961. .then((users) => {
  962. const result = {
  963. data: users,
  964. };
  965. return res.json(ApiResponse.success(result));
  966. })
  967. .catch((err) => {
  968. return res.json(ApiResponse.error());
  969. });
  970. };
  971. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  972. const id = req.query.id;
  973. const isEnabled = (req.query.isEnabled === 'true');
  974. try {
  975. if (isEnabled) {
  976. await GlobalNotificationSetting.enable(id);
  977. }
  978. else {
  979. await GlobalNotificationSetting.disable(id);
  980. }
  981. return res.json(ApiResponse.success());
  982. }
  983. catch (err) {
  984. return res.json(ApiResponse.error());
  985. }
  986. };
  987. /**
  988. * save esa settings, update config cache, and response json
  989. *
  990. * @param {*} req
  991. * @param {*} res
  992. */
  993. actions.api.importerSettingEsa = async(req, res) => {
  994. const form = req.form.settingForm;
  995. if (!req.form.isValid) {
  996. return res.json({ status: false, message: req.form.errors.join('\n') });
  997. }
  998. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  999. importer.initializeEsaClient(); // let it run in the back aftert res
  1000. return res.json({ status: true });
  1001. };
  1002. /**
  1003. * save qiita settings, update config cache, and response json
  1004. *
  1005. * @param {*} req
  1006. * @param {*} res
  1007. */
  1008. actions.api.importerSettingQiita = async(req, res) => {
  1009. const form = req.form.settingForm;
  1010. if (!req.form.isValid) {
  1011. return res.json({ status: false, message: req.form.errors.join('\n') });
  1012. }
  1013. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  1014. importer.initializeQiitaClient(); // let it run in the back aftert res
  1015. return res.json({ status: true });
  1016. };
  1017. /**
  1018. * Import all posts from esa
  1019. *
  1020. * @param {*} req
  1021. * @param {*} res
  1022. */
  1023. actions.api.importDataFromEsa = async(req, res) => {
  1024. const user = req.user;
  1025. let errors;
  1026. try {
  1027. errors = await importer.importDataFromEsa(user);
  1028. }
  1029. catch (err) {
  1030. errors = [err];
  1031. }
  1032. if (errors.length > 0) {
  1033. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1034. }
  1035. return res.json({ status: true });
  1036. };
  1037. /**
  1038. * Import all posts from qiita
  1039. *
  1040. * @param {*} req
  1041. * @param {*} res
  1042. */
  1043. actions.api.importDataFromQiita = async(req, res) => {
  1044. const user = req.user;
  1045. let errors;
  1046. try {
  1047. errors = await importer.importDataFromQiita(user);
  1048. }
  1049. catch (err) {
  1050. errors = [err];
  1051. }
  1052. if (errors.length > 0) {
  1053. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1054. }
  1055. return res.json({ status: true });
  1056. };
  1057. /**
  1058. * Test connection to esa and response result with json
  1059. *
  1060. * @param {*} req
  1061. * @param {*} res
  1062. */
  1063. actions.api.testEsaAPI = async(req, res) => {
  1064. try {
  1065. await importer.testConnectionToEsa();
  1066. return res.json({ status: true });
  1067. }
  1068. catch (err) {
  1069. return res.json({ status: false, message: `${err}` });
  1070. }
  1071. };
  1072. /**
  1073. * Test connection to qiita and response result with json
  1074. *
  1075. * @param {*} req
  1076. * @param {*} res
  1077. */
  1078. actions.api.testQiitaAPI = async(req, res) => {
  1079. try {
  1080. await importer.testConnectionToQiita();
  1081. return res.json({ status: true });
  1082. }
  1083. catch (err) {
  1084. return res.json({ status: false, message: `${err}` });
  1085. }
  1086. };
  1087. actions.api.searchBuildIndex = async function(req, res) {
  1088. const search = crowi.getSearcher();
  1089. if (!search) {
  1090. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  1091. }
  1092. // first, delete index
  1093. try {
  1094. await search.deleteIndex();
  1095. }
  1096. catch (err) {
  1097. logger.warn('Delete index Error, but if it is initialize, its ok.', err);
  1098. }
  1099. // second, create index
  1100. try {
  1101. await search.buildIndex();
  1102. }
  1103. catch (err) {
  1104. logger.error('Error', err);
  1105. return res.json(ApiResponse.error(err));
  1106. }
  1107. searchEvent.on('addPageProgress', (total, current, skip) => {
  1108. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  1109. });
  1110. searchEvent.on('finishAddPage', (total, current, skip) => {
  1111. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  1112. });
  1113. // add all page
  1114. search
  1115. .addAllPages()
  1116. .then(() => {
  1117. debug('Data is successfully indexed. ------------------ ✧✧');
  1118. })
  1119. .catch((err) => {
  1120. logger.error('Error', err);
  1121. });
  1122. return res.json(ApiResponse.success());
  1123. };
  1124. function validateMailSetting(req, form, callback) {
  1125. const mailer = crowi.mailer;
  1126. const option = {
  1127. host: form['mail:smtpHost'],
  1128. port: form['mail:smtpPort'],
  1129. };
  1130. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1131. option.auth = {
  1132. user: form['mail:smtpUser'],
  1133. pass: form['mail:smtpPassword'],
  1134. };
  1135. }
  1136. if (option.port === 465) {
  1137. option.secure = true;
  1138. }
  1139. const smtpClient = mailer.createSMTPClient(option);
  1140. debug('mailer setup for validate SMTP setting', smtpClient);
  1141. smtpClient.sendMail({
  1142. from: form['mail:from'],
  1143. to: req.user.email,
  1144. subject: 'Wiki管理設定のアップデートによるメール通知',
  1145. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
  1146. }, callback);
  1147. }
  1148. /**
  1149. * validate setting form values for SAML
  1150. *
  1151. * This validation checks, for the value of each mandatory items,
  1152. * whether it from the environment variables is empty and form value to update it is empty.
  1153. */
  1154. function validateSamlSettingForm(form, t) {
  1155. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  1156. const formValue = form.settingForm[key];
  1157. if (configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  1158. const formItemName = t(`security_setting.form_item_name.${key}`);
  1159. form.errors.push(t('form_validation.required', formItemName));
  1160. }
  1161. }
  1162. }
  1163. return actions;
  1164. };