admin.js 46 KB

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