admin.js 46 KB

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