admin.js 36 KB

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