2
0

admin.js 37 KB

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