admin.js 39 KB

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