admin.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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 User = models.User;
  7. const ExternalAccount = models.ExternalAccount;
  8. const UserGroup = models.UserGroup;
  9. const UserGroupRelation = models.UserGroupRelation;
  10. const GlobalNotificationSetting = models.GlobalNotificationSetting;
  11. const GlobalNotificationMailSetting = models.GlobalNotificationMailSetting;
  12. const GlobalNotificationSlackSetting = models.GlobalNotificationSlackSetting; // eslint-disable-line no-unused-vars
  13. const {
  14. configManager,
  15. aclService,
  16. slackNotificationService,
  17. customizeService,
  18. exportService,
  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 GlobalNotificationSetting.TYPE.MAIL:
  279. setting = new GlobalNotificationMailSetting(crowi);
  280. setting.toEmail = form.toEmail;
  281. break;
  282. case GlobalNotificationSetting.TYPE.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 models = {
  299. [GlobalNotificationSetting.TYPE.MAIL]: GlobalNotificationMailSetting,
  300. [GlobalNotificationSetting.TYPE.SLACK]: GlobalNotificationSlackSetting,
  301. };
  302. let setting = await GlobalNotificationSetting.findOne({ _id: form.id });
  303. setting = setting.toObject();
  304. // when switching from one type to another,
  305. // remove toEmail from slack setting and slackChannels from mail setting
  306. if (setting.__t !== form.notifyToType) {
  307. setting = models[setting.__t].hydrate(setting);
  308. setting.toEmail = undefined;
  309. setting.slackChannels = undefined;
  310. await setting.save();
  311. setting = setting.toObject();
  312. }
  313. switch (form.notifyToType) {
  314. case GlobalNotificationSetting.TYPE.MAIL:
  315. setting = GlobalNotificationMailSetting.hydrate(setting);
  316. setting.toEmail = form.toEmail;
  317. break;
  318. case GlobalNotificationSetting.TYPE.SLACK:
  319. setting = GlobalNotificationSlackSetting.hydrate(setting);
  320. setting.slackChannels = form.slackChannels;
  321. break;
  322. default:
  323. logger.error('GlobalNotificationSetting Type Error: undefined type');
  324. req.flash('errorMessage', 'Error occurred in updating the global notification setting: undefined notification type');
  325. return res.redirect('/admin/notification#global-notification');
  326. }
  327. setting.__t = form.notifyToType;
  328. setting.triggerPath = form.triggerPath;
  329. setting.triggerEvents = getNotificationEvents(form);
  330. await setting.save();
  331. return res.redirect('/admin/notification#global-notification');
  332. };
  333. actions.globalNotification.remove = async(req, res) => {
  334. const id = req.params.id;
  335. try {
  336. await GlobalNotificationSetting.findOneAndRemove({ _id: id });
  337. return res.redirect('/admin/notification#global-notification');
  338. }
  339. catch (err) {
  340. req.flash('errorMessage', 'Error in deleting global notification setting');
  341. return res.redirect('/admin/notification#global-notification');
  342. }
  343. };
  344. const getNotificationEvents = (form) => {
  345. const triggerEvents = [];
  346. const triggerEventKeys = Object.keys(form).filter((key) => { return key.match(/^triggerEvent/) });
  347. triggerEventKeys.forEach((key) => {
  348. if (form[key]) {
  349. triggerEvents.push(form[key]);
  350. }
  351. });
  352. return triggerEvents;
  353. };
  354. actions.search = {};
  355. actions.search.index = function(req, res) {
  356. const search = crowi.getSearcher();
  357. if (!search) {
  358. return res.redirect('/admin');
  359. }
  360. return res.render('admin/search', {});
  361. };
  362. actions.user = {};
  363. actions.user.index = async function(req, res) {
  364. const activeUsers = await User.countListByStatus(User.STATUS_ACTIVE);
  365. const userUpperLimit = aclService.userUpperLimit();
  366. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  367. const page = parseInt(req.query.page) || 1;
  368. const result = await User.findUsersWithPagination({
  369. page,
  370. select: `${User.USER_PUBLIC_FIELDS} lastLoginAt`,
  371. populate: User.IMAGE_POPULATION,
  372. });
  373. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  374. return res.render('admin/users', {
  375. users: result.docs,
  376. pager,
  377. activeUsers,
  378. userUpperLimit,
  379. isUserCountExceedsUpperLimit,
  380. });
  381. };
  382. // これやったときの relation の挙動未確認
  383. actions.user.removeCompletely = function(req, res) {
  384. // ユーザーの物理削除
  385. const id = req.params.id;
  386. User.removeCompletelyById(id, (err, removed) => {
  387. if (err) {
  388. debug('Error while removing user.', err, id);
  389. req.flash('errorMessage', '完全な削除に失敗しました。');
  390. }
  391. else {
  392. req.flash('successMessage', '削除しました');
  393. }
  394. return res.redirect('/admin/users');
  395. });
  396. };
  397. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  398. actions.user.resetPassword = async function(req, res) {
  399. const id = req.body.user_id;
  400. const User = crowi.model('User');
  401. try {
  402. const newPassword = await User.resetPasswordByRandomString(id);
  403. const user = await User.findById(id);
  404. const result = { user: user.toObject(), newPassword };
  405. return res.json(ApiResponse.success(result));
  406. }
  407. catch (err) {
  408. debug('Error on reseting password', err);
  409. return res.json(ApiResponse.error(err));
  410. }
  411. };
  412. actions.externalAccount = {};
  413. actions.externalAccount.index = function(req, res) {
  414. const page = parseInt(req.query.page) || 1;
  415. ExternalAccount.findAllWithPagination({ page })
  416. .then((result) => {
  417. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  418. return res.render('admin/external-accounts', {
  419. accounts: result.docs,
  420. pager,
  421. });
  422. });
  423. };
  424. actions.externalAccount.remove = async function(req, res) {
  425. const id = req.params.id;
  426. let account = null;
  427. try {
  428. account = await ExternalAccount.findByIdAndRemove(id);
  429. if (account == null) {
  430. throw new Error('削除に失敗しました。');
  431. }
  432. }
  433. catch (err) {
  434. req.flash('errorMessage', err.message);
  435. return res.redirect('/admin/users/external-accounts');
  436. }
  437. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  438. return res.redirect('/admin/users/external-accounts');
  439. };
  440. actions.userGroup = {};
  441. actions.userGroup.index = function(req, res) {
  442. const page = parseInt(req.query.page) || 1;
  443. const isAclEnabled = aclService.isAclEnabled();
  444. const renderVar = {
  445. userGroups: [],
  446. userGroupRelations: new Map(),
  447. pager: null,
  448. isAclEnabled,
  449. };
  450. UserGroup.findUserGroupsWithPagination({ page })
  451. .then((result) => {
  452. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  453. const userGroups = result.docs;
  454. renderVar.userGroups = userGroups;
  455. renderVar.pager = pager;
  456. return userGroups.map((userGroup) => {
  457. return new Promise((resolve, reject) => {
  458. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  459. .then((relations) => {
  460. return resolve({
  461. id: userGroup._id,
  462. relatedUsers: relations.map((relation) => {
  463. return relation.relatedUser;
  464. }),
  465. });
  466. });
  467. });
  468. });
  469. })
  470. .then((allRelationsPromise) => {
  471. return Promise.all(allRelationsPromise);
  472. })
  473. .then((relations) => {
  474. for (const relation of relations) {
  475. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  476. }
  477. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  478. return res.render('admin/user-groups', renderVar);
  479. })
  480. .catch((err) => {
  481. debug('Error on find all relations', err);
  482. return res.json(ApiResponse.error('Error'));
  483. });
  484. };
  485. // グループ詳細
  486. actions.userGroup.detail = async function(req, res) {
  487. const userGroupId = req.params.id;
  488. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  489. if (userGroup == null) {
  490. logger.error('no userGroup is exists. ', userGroupId);
  491. return res.redirect('/admin/user-groups');
  492. }
  493. return res.render('admin/user-group-detail', { userGroup });
  494. };
  495. // Importer management
  496. actions.importer = {};
  497. actions.importer.api = api;
  498. api.validators = {};
  499. api.validators.importer = {};
  500. actions.importer.index = function(req, res) {
  501. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  502. return res.render('admin/importer', {
  503. settingForm,
  504. });
  505. };
  506. api.validators.importer.esa = function() {
  507. const validator = [
  508. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  509. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  510. ];
  511. return validator;
  512. };
  513. api.validators.importer.qiita = function() {
  514. const validator = [
  515. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  516. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  517. ];
  518. return validator;
  519. };
  520. // Export management
  521. actions.export = {};
  522. actions.export.index = (req, res) => {
  523. return res.render('admin/export');
  524. };
  525. actions.export.download = (req, res) => {
  526. // TODO: add express validator
  527. const { fileName } = req.params;
  528. try {
  529. const zipFile = exportService.getFile(fileName);
  530. return res.download(zipFile);
  531. }
  532. catch (err) {
  533. // TODO: use ApiV3Error
  534. logger.error(err);
  535. return res.json(ApiResponse.error());
  536. }
  537. };
  538. actions.api = {};
  539. actions.api.appSetting = async function(req, res) {
  540. const form = req.form.settingForm;
  541. if (req.form.isValid) {
  542. debug('form content', form);
  543. // mail setting ならここで validation
  544. if (form['mail:from']) {
  545. validateMailSetting(req, form, async(err, data) => {
  546. debug('Error validate mail setting: ', err, data);
  547. if (err) {
  548. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  549. return res.json({ status: false, message: req.form.errors.join('\n') });
  550. }
  551. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  552. return res.json({ status: true });
  553. });
  554. }
  555. else {
  556. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  557. return res.json({ status: true });
  558. }
  559. }
  560. else {
  561. return res.json({ status: false, message: req.form.errors.join('\n') });
  562. }
  563. };
  564. actions.api.asyncAppSetting = async(req, res) => {
  565. const form = req.form.settingForm;
  566. if (!req.form.isValid) {
  567. return res.json({ status: false, message: req.form.errors.join('\n') });
  568. }
  569. debug('form content', form);
  570. try {
  571. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  572. return res.json({ status: true });
  573. }
  574. catch (err) {
  575. logger.error(err);
  576. return res.json({ status: false });
  577. }
  578. };
  579. actions.api.securitySetting = async function(req, res) {
  580. if (!req.form.isValid) {
  581. return res.json({ status: false, message: req.form.errors.join('\n') });
  582. }
  583. const form = req.form.settingForm;
  584. if (aclService.isWikiModeForced()) {
  585. logger.debug('security:restrictGuestMode will not be changed because wiki mode is forced to set');
  586. delete form['security:restrictGuestMode'];
  587. }
  588. try {
  589. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  590. return res.json({ status: true });
  591. }
  592. catch (err) {
  593. logger.error(err);
  594. return res.json({ status: false });
  595. }
  596. };
  597. actions.api.securityPassportLocalSetting = async function(req, res) {
  598. const form = req.form.settingForm;
  599. if (!req.form.isValid) {
  600. return res.json({ status: false, message: req.form.errors.join('\n') });
  601. }
  602. debug('form content', form);
  603. try {
  604. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  605. // reset strategy
  606. crowi.passportService.resetLocalStrategy();
  607. // setup strategy
  608. if (configManager.getConfig('crowi', 'security:passport-local:isEnabled')) {
  609. crowi.passportService.setupLocalStrategy(true);
  610. }
  611. }
  612. catch (err) {
  613. logger.error(err);
  614. return res.json({ status: false, message: err.message });
  615. }
  616. return res.json({ status: true });
  617. };
  618. actions.api.securityPassportLdapSetting = async function(req, res) {
  619. const form = req.form.settingForm;
  620. if (!req.form.isValid) {
  621. return res.json({ status: false, message: req.form.errors.join('\n') });
  622. }
  623. debug('form content', form);
  624. try {
  625. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  626. // reset strategy
  627. crowi.passportService.resetLdapStrategy();
  628. // setup strategy
  629. if (configManager.getConfig('crowi', 'security:passport-ldap:isEnabled')) {
  630. crowi.passportService.setupLdapStrategy(true);
  631. }
  632. }
  633. catch (err) {
  634. logger.error(err);
  635. return res.json({ status: false, message: err.message });
  636. }
  637. return res.json({ status: true });
  638. };
  639. actions.api.securityPassportSamlSetting = async(req, res) => {
  640. const form = req.form.settingForm;
  641. validateSamlSettingForm(req.form, req.t);
  642. if (!req.form.isValid) {
  643. return res.json({ status: false, message: req.form.errors.join('\n') });
  644. }
  645. debug('form content', form);
  646. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  647. // reset strategy
  648. await crowi.passportService.resetSamlStrategy();
  649. // setup strategy
  650. if (configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  651. try {
  652. await crowi.passportService.setupSamlStrategy(true);
  653. }
  654. catch (err) {
  655. // reset
  656. await crowi.passportService.resetSamlStrategy();
  657. return res.json({ status: false, message: err.message });
  658. }
  659. }
  660. return res.json({ status: true });
  661. };
  662. actions.api.securityPassportBasicSetting = async(req, res) => {
  663. const form = req.form.settingForm;
  664. if (!req.form.isValid) {
  665. return res.json({ status: false, message: req.form.errors.join('\n') });
  666. }
  667. debug('form content', form);
  668. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  669. // reset strategy
  670. await crowi.passportService.resetBasicStrategy();
  671. // setup strategy
  672. if (configManager.getConfig('crowi', 'security:passport-basic:isEnabled')) {
  673. try {
  674. await crowi.passportService.setupBasicStrategy(true);
  675. }
  676. catch (err) {
  677. // reset
  678. await crowi.passportService.resetBasicStrategy();
  679. return res.json({ status: false, message: err.message });
  680. }
  681. }
  682. return res.json({ status: true });
  683. };
  684. actions.api.securityPassportGoogleSetting = async(req, res) => {
  685. const form = req.form.settingForm;
  686. if (!req.form.isValid) {
  687. return res.json({ status: false, message: req.form.errors.join('\n') });
  688. }
  689. debug('form content', form);
  690. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  691. // reset strategy
  692. await crowi.passportService.resetGoogleStrategy();
  693. // setup strategy
  694. if (configManager.getConfig('crowi', 'security:passport-google:isEnabled')) {
  695. try {
  696. await crowi.passportService.setupGoogleStrategy(true);
  697. }
  698. catch (err) {
  699. // reset
  700. await crowi.passportService.resetGoogleStrategy();
  701. return res.json({ status: false, message: err.message });
  702. }
  703. }
  704. return res.json({ status: true });
  705. };
  706. actions.api.securityPassportGitHubSetting = async(req, res) => {
  707. const form = req.form.settingForm;
  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.resetGitHubStrategy();
  715. // setup strategy
  716. if (configManager.getConfig('crowi', 'security:passport-github:isEnabled')) {
  717. try {
  718. await crowi.passportService.setupGitHubStrategy(true);
  719. }
  720. catch (err) {
  721. // reset
  722. await crowi.passportService.resetGitHubStrategy();
  723. return res.json({ status: false, message: err.message });
  724. }
  725. }
  726. return res.json({ status: true });
  727. };
  728. actions.api.securityPassportTwitterSetting = 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.resetTwitterStrategy();
  737. // setup strategy
  738. if (configManager.getConfig('crowi', 'security:passport-twitter:isEnabled')) {
  739. try {
  740. await crowi.passportService.setupTwitterStrategy(true);
  741. }
  742. catch (err) {
  743. // reset
  744. await crowi.passportService.resetTwitterStrategy();
  745. return res.json({ status: false, message: err.message });
  746. }
  747. }
  748. return res.json({ status: true });
  749. };
  750. actions.api.securityPassportOidcSetting = 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.resetOidcStrategy();
  759. // setup strategy
  760. if (configManager.getConfig('crowi', 'security:passport-oidc:isEnabled')) {
  761. try {
  762. await crowi.passportService.setupOidcStrategy(true);
  763. }
  764. catch (err) {
  765. // reset
  766. await crowi.passportService.resetOidcStrategy();
  767. return res.json({ status: false, message: err.message });
  768. }
  769. }
  770. return res.json({ status: true });
  771. };
  772. actions.api.customizeSetting = async function(req, res) {
  773. const form = req.form.settingForm;
  774. if (req.form.isValid) {
  775. debug('form content', form);
  776. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  777. customizeService.initCustomCss();
  778. customizeService.initCustomTitle();
  779. return res.json({ status: true });
  780. }
  781. return res.json({ status: false, message: req.form.errors.join('\n') });
  782. };
  783. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  784. actions.api.notificationAdd = function(req, res) {
  785. const UpdatePost = crowi.model('UpdatePost');
  786. const pathPattern = req.body.pathPattern;
  787. const channel = req.body.channel;
  788. debug('notification.add', pathPattern, channel);
  789. UpdatePost.create(pathPattern, channel, req.user)
  790. .then((doc) => {
  791. debug('Successfully save updatePost', doc);
  792. // fixme: うーん
  793. doc.creator = doc.creator._id.toString();
  794. return res.json(ApiResponse.success({ updatePost: doc }));
  795. })
  796. .catch((err) => {
  797. debug('Failed to save updatePost', err);
  798. return res.json(ApiResponse.error());
  799. });
  800. };
  801. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  802. actions.api.notificationRemove = function(req, res) {
  803. const UpdatePost = crowi.model('UpdatePost');
  804. const id = req.body.id;
  805. UpdatePost.remove(id)
  806. .then(() => {
  807. debug('Successfully remove updatePost');
  808. return res.json(ApiResponse.success({}));
  809. })
  810. .catch((err) => {
  811. debug('Failed to remove updatePost', err);
  812. return res.json(ApiResponse.error());
  813. });
  814. };
  815. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  816. actions.api.usersSearch = function(req, res) {
  817. const User = crowi.model('User');
  818. const email = req.query.email;
  819. User.findUsersByPartOfEmail(email, {})
  820. .then((users) => {
  821. const result = {
  822. data: users,
  823. };
  824. return res.json(ApiResponse.success(result));
  825. })
  826. .catch((err) => {
  827. return res.json(ApiResponse.error());
  828. });
  829. };
  830. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  831. const id = req.query.id;
  832. const isEnabled = (req.query.isEnabled === 'true');
  833. try {
  834. if (isEnabled) {
  835. await GlobalNotificationSetting.enable(id);
  836. }
  837. else {
  838. await GlobalNotificationSetting.disable(id);
  839. }
  840. return res.json(ApiResponse.success());
  841. }
  842. catch (err) {
  843. return res.json(ApiResponse.error());
  844. }
  845. };
  846. /**
  847. * save esa settings, update config cache, and response json
  848. *
  849. * @param {*} req
  850. * @param {*} res
  851. */
  852. actions.api.importerSettingEsa = async(req, res) => {
  853. const form = req.body;
  854. const { validationResult } = require('express-validator');
  855. const errors = validationResult(req);
  856. if (!errors.isEmpty()) {
  857. return res.json(ApiResponse.error('esa.io form is blank'));
  858. }
  859. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  860. importer.initializeEsaClient(); // let it run in the back aftert res
  861. return res.json(ApiResponse.success());
  862. };
  863. /**
  864. * save qiita settings, update config cache, and response json
  865. *
  866. * @param {*} req
  867. * @param {*} res
  868. */
  869. actions.api.importerSettingQiita = async(req, res) => {
  870. const form = req.body;
  871. const { validationResult } = require('express-validator');
  872. const errors = validationResult(req);
  873. if (!errors.isEmpty()) {
  874. console.log('validator', errors);
  875. return res.json(ApiResponse.error('Qiita form is blank'));
  876. }
  877. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  878. importer.initializeQiitaClient(); // let it run in the back aftert res
  879. return res.json(ApiResponse.success());
  880. };
  881. /**
  882. * Import all posts from esa
  883. *
  884. * @param {*} req
  885. * @param {*} res
  886. */
  887. actions.api.importDataFromEsa = async(req, res) => {
  888. const user = req.user;
  889. let errors;
  890. try {
  891. errors = await importer.importDataFromEsa(user);
  892. }
  893. catch (err) {
  894. errors = [err];
  895. }
  896. if (errors.length > 0) {
  897. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  898. }
  899. return res.json(ApiResponse.success());
  900. };
  901. /**
  902. * Import all posts from qiita
  903. *
  904. * @param {*} req
  905. * @param {*} res
  906. */
  907. actions.api.importDataFromQiita = async(req, res) => {
  908. const user = req.user;
  909. let errors;
  910. try {
  911. errors = await importer.importDataFromQiita(user);
  912. }
  913. catch (err) {
  914. errors = [err];
  915. }
  916. if (errors.length > 0) {
  917. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  918. }
  919. return res.json(ApiResponse.success());
  920. };
  921. /**
  922. * Test connection to esa and response result with json
  923. *
  924. * @param {*} req
  925. * @param {*} res
  926. */
  927. actions.api.testEsaAPI = async(req, res) => {
  928. try {
  929. await importer.testConnectionToEsa();
  930. return res.json(ApiResponse.success());
  931. }
  932. catch (err) {
  933. return res.json(ApiResponse.error(err));
  934. }
  935. };
  936. /**
  937. * Test connection to qiita and response result with json
  938. *
  939. * @param {*} req
  940. * @param {*} res
  941. */
  942. actions.api.testQiitaAPI = async(req, res) => {
  943. try {
  944. await importer.testConnectionToQiita();
  945. return res.json(ApiResponse.success());
  946. }
  947. catch (err) {
  948. return res.json(ApiResponse.error(err));
  949. }
  950. };
  951. actions.api.searchBuildIndex = async function(req, res) {
  952. const search = crowi.getSearcher();
  953. if (!search) {
  954. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  955. }
  956. searchEvent.on('addPageProgress', (total, current, skip) => {
  957. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  958. });
  959. searchEvent.on('finishAddPage', (total, current, skip) => {
  960. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  961. });
  962. await search.buildIndex();
  963. return res.json(ApiResponse.success());
  964. };
  965. function validateMailSetting(req, form, callback) {
  966. const mailer = crowi.mailer;
  967. const option = {
  968. host: form['mail:smtpHost'],
  969. port: form['mail:smtpPort'],
  970. };
  971. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  972. option.auth = {
  973. user: form['mail:smtpUser'],
  974. pass: form['mail:smtpPassword'],
  975. };
  976. }
  977. if (option.port === 465) {
  978. option.secure = true;
  979. }
  980. const smtpClient = mailer.createSMTPClient(option);
  981. debug('mailer setup for validate SMTP setting', smtpClient);
  982. smtpClient.sendMail({
  983. from: form['mail:from'],
  984. to: req.user.email,
  985. subject: 'Wiki管理設定のアップデートによるメール通知',
  986. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
  987. }, callback);
  988. }
  989. /**
  990. * validate setting form values for SAML
  991. *
  992. * This validation checks, for the value of each mandatory items,
  993. * whether it from the environment variables is empty and form value to update it is empty.
  994. */
  995. function validateSamlSettingForm(form, t) {
  996. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  997. const formValue = form.settingForm[key];
  998. if (configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  999. const formItemName = t(`security_setting.form_item_name.${key}`);
  1000. form.errors.push(t('form_validation.required', formItemName));
  1001. }
  1002. }
  1003. }
  1004. return actions;
  1005. };