admin.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  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.setupCofigFormData('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.setupCofigFormData('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.setupCofigFormData('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.setupCofigFormData('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.setupCofigFormData('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 = function(req, res) {
  409. var page = parseInt(req.query.page) || 1;
  410. User.findUsersWithPagination({page: page}, function(err, result) {
  411. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  412. return res.render('admin/users', {
  413. users: result.docs,
  414. pager: pager
  415. });
  416. });
  417. };
  418. actions.user.invite = function(req, res) {
  419. var form = req.form.inviteForm;
  420. var toSendEmail = form.sendEmail || false;
  421. if (req.form.isValid) {
  422. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, function(err, userList) {
  423. if (err) {
  424. req.flash('errorMessage', req.form.errors.join('\n'));
  425. }
  426. else {
  427. req.flash('createdUser', userList);
  428. }
  429. return res.redirect('/admin/users');
  430. });
  431. }
  432. else {
  433. req.flash('errorMessage', req.form.errors.join('\n'));
  434. return res.redirect('/admin/users');
  435. }
  436. };
  437. actions.user.makeAdmin = function(req, res) {
  438. var id = req.params.id;
  439. User.findById(id, function(err, userData) {
  440. userData.makeAdmin(function(err, userData) {
  441. if (err === null) {
  442. req.flash('successMessage', userData.name + 'さんのアカウントを管理者に設定しました。');
  443. }
  444. else {
  445. req.flash('errorMessage', '更新に失敗しました。');
  446. debug(err, userData);
  447. }
  448. return res.redirect('/admin/users');
  449. });
  450. });
  451. };
  452. actions.user.removeFromAdmin = function(req, res) {
  453. var id = req.params.id;
  454. User.findById(id, function(err, userData) {
  455. userData.removeFromAdmin(function(err, userData) {
  456. if (err === null) {
  457. req.flash('successMessage', userData.name + 'さんのアカウントを管理者から外しました。');
  458. }
  459. else {
  460. req.flash('errorMessage', '更新に失敗しました。');
  461. debug(err, userData);
  462. }
  463. return res.redirect('/admin/users');
  464. });
  465. });
  466. };
  467. actions.user.activate = function(req, res) {
  468. var id = req.params.id;
  469. User.findById(id, function(err, userData) {
  470. userData.statusActivate(function(err, userData) {
  471. if (err === null) {
  472. req.flash('successMessage', userData.name + 'さんのアカウントを有効化しました');
  473. }
  474. else {
  475. req.flash('errorMessage', '更新に失敗しました。');
  476. debug(err, userData);
  477. }
  478. return res.redirect('/admin/users');
  479. });
  480. });
  481. };
  482. actions.user.suspend = function(req, res) {
  483. var id = req.params.id;
  484. User.findById(id, function(err, userData) {
  485. userData.statusSuspend(function(err, userData) {
  486. if (err === null) {
  487. req.flash('successMessage', userData.name + 'さんのアカウントを利用停止にしました');
  488. }
  489. else {
  490. req.flash('errorMessage', '更新に失敗しました。');
  491. debug(err, userData);
  492. }
  493. return res.redirect('/admin/users');
  494. });
  495. });
  496. };
  497. actions.user.remove = function(req, res) {
  498. const id = req.params.id;
  499. let username = '';
  500. return new Promise((resolve, reject) => {
  501. User.findById(id, (err, userData) => {
  502. username = userData.username;
  503. return resolve(userData);
  504. });
  505. })
  506. .then((userData) => {
  507. return new Promise((resolve, reject) => {
  508. userData.statusDelete((err, userData) => {
  509. if (err) {
  510. reject(err);
  511. }
  512. resolve(userData);
  513. });
  514. });
  515. })
  516. .then((userData) => {
  517. // remove all External Accounts
  518. return ExternalAccount.remove({user: userData}).then(() => userData);
  519. })
  520. .then((userData) => {
  521. return Page.removePageByPath(`/user/${username}`).then(() => userData);
  522. })
  523. .then((userData) => {
  524. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  525. return res.redirect('/admin/users');
  526. })
  527. .catch((err) => {
  528. req.flash('errorMessage', '削除に失敗しました。');
  529. return res.redirect('/admin/users');
  530. });
  531. };
  532. // これやったときの relation の挙動未確認
  533. actions.user.removeCompletely = function(req, res) {
  534. // ユーザーの物理削除
  535. var id = req.params.id;
  536. User.removeCompletelyById(id, function(err, removed) {
  537. if (err) {
  538. debug('Error while removing user.', err, id);
  539. req.flash('errorMessage', '完全な削除に失敗しました。');
  540. }
  541. else {
  542. req.flash('successMessage', '削除しました');
  543. }
  544. return res.redirect('/admin/users');
  545. });
  546. };
  547. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  548. actions.user.resetPassword = function(req, res) {
  549. const id = req.body.user_id;
  550. const User = crowi.model('User');
  551. User.resetPasswordByRandomString(id)
  552. .then(function(data) {
  553. data.user = User.filterToPublicFields(data.user);
  554. return res.json(ApiResponse.success(data));
  555. }).catch(function(err) {
  556. debug('Error on reseting password', err);
  557. return res.json(ApiResponse.error('Error'));
  558. });
  559. };
  560. actions.externalAccount = {};
  561. actions.externalAccount.index = function(req, res) {
  562. const page = parseInt(req.query.page) || 1;
  563. ExternalAccount.findAllWithPagination({page})
  564. .then((result) => {
  565. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  566. return res.render('admin/external-accounts', {
  567. accounts: result.docs,
  568. pager: pager
  569. });
  570. });
  571. };
  572. actions.externalAccount.remove = function(req, res) {
  573. const accountId = req.params.id;
  574. ExternalAccount.findOneAndRemove({accountId})
  575. .then((result) => {
  576. if (result == null) {
  577. req.flash('errorMessage', '削除に失敗しました。');
  578. return res.redirect('/admin/users/external-accounts');
  579. }
  580. else {
  581. req.flash('successMessage', `外部アカウント '${accountId}' を削除しました`);
  582. return res.redirect('/admin/users/external-accounts');
  583. }
  584. });
  585. };
  586. actions.userGroup = {};
  587. actions.userGroup.index = function(req, res) {
  588. var page = parseInt(req.query.page) || 1;
  589. const isAclEnabled = !Config.isPublicWikiOnly(req.config);
  590. var renderVar = {
  591. userGroups: [],
  592. userGroupRelations: new Map(),
  593. pager: null,
  594. isAclEnabled,
  595. };
  596. UserGroup.findUserGroupsWithPagination({ page: page })
  597. .then((result) => {
  598. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  599. var userGroups = result.docs;
  600. renderVar.userGroups = userGroups;
  601. renderVar.pager = pager;
  602. return userGroups.map((userGroup) => {
  603. return new Promise((resolve, reject) => {
  604. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  605. .then((relations) => {
  606. return resolve([userGroup, relations]);
  607. });
  608. });
  609. });
  610. })
  611. .then((allRelationsPromise) => {
  612. return Promise.all(allRelationsPromise);
  613. })
  614. .then((relations) => {
  615. renderVar.userGroupRelations = new Map(relations);
  616. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  617. return res.render('admin/user-groups', renderVar);
  618. })
  619. .catch( function(err) {
  620. debug('Error on find all relations', err);
  621. return res.json(ApiResponse.error('Error'));
  622. });
  623. };
  624. // グループ詳細
  625. actions.userGroup.detail = function(req, res) {
  626. const userGroupId = req.params.id;
  627. const renderVar = {
  628. userGroup: null,
  629. userGroupRelations: [],
  630. pageGroupRelations: [],
  631. notRelatedusers: []
  632. };
  633. let targetUserGroup = null;
  634. UserGroup.findOne({ _id: userGroupId})
  635. .then(function(userGroup) {
  636. targetUserGroup = userGroup;
  637. if (targetUserGroup == null) {
  638. req.flash('errorMessage', 'グループがありません');
  639. throw new Error('no userGroup is exists. ', name);
  640. }
  641. else {
  642. renderVar.userGroup = targetUserGroup;
  643. return Promise.all([
  644. // get all user and group relations
  645. UserGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  646. // get all page and group relations
  647. PageGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  648. // get all not related users for group
  649. UserGroupRelation.findUserByNotRelatedGroup(targetUserGroup),
  650. ]);
  651. }
  652. })
  653. .then((resolves) => {
  654. renderVar.userGroupRelations = resolves[0];
  655. renderVar.pageGroupRelations = resolves[1];
  656. renderVar.notRelatedusers = resolves[2];
  657. debug('notRelatedusers', renderVar.notRelatedusers);
  658. return res.render('admin/user-group-detail', renderVar);
  659. })
  660. .catch((err) => {
  661. req.flash('errorMessage', 'ユーザグループの検索に失敗しました');
  662. debug('Error on get userGroupDetail', err);
  663. return res.redirect('/admin/user-groups');
  664. });
  665. };
  666. //グループの生成
  667. actions.userGroup.create = function(req, res) {
  668. const form = req.form.createGroupForm;
  669. if (req.form.isValid) {
  670. const userGroupName = crowi.xss.process(form.userGroupName);
  671. UserGroup.createGroupByName(userGroupName)
  672. .then((newUserGroup) => {
  673. req.flash('successMessage', newUserGroup.name);
  674. req.flash('createdUserGroup', newUserGroup);
  675. return res.redirect('/admin/user-groups');
  676. })
  677. .catch((err) => {
  678. debug('create userGroup error:', err);
  679. req.flash('errorMessage', '同じグループ名が既に存在します。');
  680. });
  681. }
  682. else {
  683. req.flash('errorMessage', req.form.errors.join('\n'));
  684. return res.redirect('/admin/user-groups');
  685. }
  686. };
  687. //
  688. actions.userGroup.update = function(req, res) {
  689. const userGroupId = req.params.userGroupId;
  690. const name = crowi.xss.process(req.body.name);
  691. UserGroup.findById(userGroupId)
  692. .then((userGroupData) => {
  693. if (userGroupData == null) {
  694. req.flash('errorMessage', 'グループの検索に失敗しました。');
  695. return new Promise();
  696. }
  697. else {
  698. // 名前存在チェック
  699. return UserGroup.isRegisterableName(name)
  700. .then((isRegisterableName) => {
  701. // 既に存在するグループ名に更新しようとした場合はエラー
  702. if (!isRegisterableName) {
  703. req.flash('errorMessage', 'グループ名が既に存在します。');
  704. }
  705. else {
  706. return userGroupData.updateName(name)
  707. .then(() => {
  708. req.flash('successMessage', 'グループ名を更新しました。');
  709. })
  710. .catch((err) => {
  711. req.flash('errorMessage', 'グループ名の更新に失敗しました。');
  712. });
  713. }
  714. });
  715. }
  716. })
  717. .then(() => {
  718. return res.redirect('/admin/user-group-detail/' + userGroupId);
  719. });
  720. };
  721. actions.userGroup.uploadGroupPicture = function(req, res) {
  722. var fileUploader = require('../service/file-uploader')(crowi, app);
  723. //var storagePlugin = new pluginService('storage');
  724. //var storage = require('../service/storage').StorageService(config);
  725. var userGroupId = req.params.userGroupId;
  726. var tmpFile = req.file || null;
  727. if (!tmpFile) {
  728. return res.json({
  729. 'status': false,
  730. 'message': 'File type error.'
  731. });
  732. }
  733. UserGroup.findById(userGroupId, function(err, userGroupData) {
  734. if (!userGroupData) {
  735. return res.json({
  736. 'status': false,
  737. 'message': 'UserGroup error.'
  738. });
  739. }
  740. var tmpPath = tmpFile.path;
  741. var filePath = UserGroup.createUserGroupPictureFilePath(userGroupData, tmpFile.filename + tmpFile.originalname);
  742. var acceptableFileType = /image\/.+/;
  743. if (!tmpFile.mimetype.match(acceptableFileType)) {
  744. return res.json({
  745. 'status': false,
  746. 'message': 'File type error. Only image files is allowed to set as user picture.',
  747. });
  748. }
  749. var tmpFileStream = fs.createReadStream(tmpPath, { flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  750. fileUploader.uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
  751. .then(function(data) {
  752. var imageUrl = fileUploader.generateUrl(filePath);
  753. userGroupData.updateImage(imageUrl)
  754. .then(() => {
  755. fs.unlink(tmpPath, function(err) {
  756. if (err) {
  757. debug('Error while deleting tmp file.', err);
  758. }
  759. return res.json({
  760. 'status': true,
  761. 'url': imageUrl,
  762. 'message': '',
  763. });
  764. });
  765. });
  766. }).catch(function(err) {
  767. debug('Uploading error', err);
  768. return res.json({
  769. 'status': false,
  770. 'message': 'Error while uploading to ',
  771. });
  772. });
  773. });
  774. };
  775. actions.userGroup.deletePicture = function(req, res) {
  776. const userGroupId = req.params.userGroupId;
  777. let userGroupName = null;
  778. UserGroup.findById(userGroupId)
  779. .then((userGroupData) => {
  780. if (userGroupData == null) {
  781. return Promise.reject();
  782. }
  783. else {
  784. userGroupName = userGroupData.name;
  785. return userGroupData.deleteImage();
  786. }
  787. })
  788. .then((updated) => {
  789. req.flash('successMessage', 'Deleted group picture');
  790. return res.redirect('/admin/user-group-detail/' + userGroupId);
  791. })
  792. .catch((err) => {
  793. debug('An error occured.', err);
  794. req.flash('errorMessage', 'Error while deleting group picture');
  795. if (userGroupName == null) {
  796. return res.redirect('/admin/user-groups/');
  797. }
  798. else {
  799. return res.redirect('/admin/user-group-detail/' + userGroupId);
  800. }
  801. });
  802. };
  803. // app.post('/_api/admin/user-group/delete' , admin.userGroup.removeCompletely);
  804. actions.userGroup.removeCompletely = function(req, res) {
  805. const id = req.body.user_group_id;
  806. const fileUploader = require('../service/file-uploader')(crowi, app);
  807. UserGroup.removeCompletelyById(id)
  808. //// TODO remove attachments
  809. // couldn't remove because filePath includes '/uploads/uploads'
  810. // Error: ENOENT: no such file or directory, unlink 'C:\dev\growi\public\uploads\uploads\userGroup\5b1df18ab69611651cc71495.png
  811. //
  812. // .then(removed => {
  813. // if (removed.image != null) {
  814. // fileUploader.deleteFile(null, removed.image);
  815. // }
  816. // })
  817. .then(() => {
  818. req.flash('successMessage', '削除しました');
  819. return res.redirect('/admin/user-groups');
  820. })
  821. .catch((err) => {
  822. debug('Error while removing userGroup.', err, id);
  823. req.flash('errorMessage', '完全な削除に失敗しました。');
  824. return res.redirect('/admin/user-groups');
  825. });
  826. };
  827. actions.userGroupRelation = {};
  828. actions.userGroupRelation.index = function(req, res) {
  829. };
  830. actions.userGroupRelation.create = function(req, res) {
  831. const User = crowi.model('User');
  832. const UserGroup = crowi.model('UserGroup');
  833. const UserGroupRelation = crowi.model('UserGroupRelation');
  834. // req params
  835. const userName = req.body.user_name;
  836. const userGroupId = req.body.user_group_id;
  837. let user = null;
  838. let userGroup = null;
  839. Promise.all([
  840. // ユーザグループをIDで検索
  841. UserGroup.findById(userGroupId),
  842. // ユーザを名前で検索
  843. User.findUserByUsername(userName),
  844. ])
  845. .then((resolves) => {
  846. userGroup = resolves[0];
  847. user = resolves[1];
  848. // Relation を作成
  849. UserGroupRelation.createRelation(userGroup, user);
  850. })
  851. .then((result) => {
  852. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  853. }).catch((err) => {
  854. debug('Error on create user-group relation', err);
  855. req.flash('errorMessage', 'Error on create user-group relation');
  856. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  857. });
  858. };
  859. actions.userGroupRelation.remove = function(req, res) {
  860. const UserGroupRelation = crowi.model('UserGroupRelation');
  861. const userGroupId = req.params.id;
  862. const relationId = req.params.relationId;
  863. UserGroupRelation.removeById(relationId)
  864. .then(() =>{
  865. return res.redirect('/admin/user-group-detail/' + userGroupId);
  866. })
  867. .catch((err) => {
  868. debug('Error on remove user-group-relation', err);
  869. req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
  870. });
  871. };
  872. // Importer management
  873. actions.importer = {};
  874. actions.importer.index = function(req, res) {
  875. var settingForm;
  876. settingForm = Config.setupCofigFormData('crowi', req.config);
  877. return res.render('admin/importer', {
  878. settingForm: settingForm,
  879. });
  880. };
  881. actions.api = {};
  882. actions.api.appSetting = function(req, res) {
  883. var form = req.form.settingForm;
  884. if (req.form.isValid) {
  885. debug('form content', form);
  886. // mail setting ならここで validation
  887. if (form['mail:from']) {
  888. validateMailSetting(req, form, function(err, data) {
  889. debug('Error validate mail setting: ', err, data);
  890. if (err) {
  891. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  892. return res.json({status: false, message: req.form.errors.join('\n')});
  893. }
  894. return saveSetting(req, res, form);
  895. });
  896. }
  897. else {
  898. return saveSetting(req, res, form);
  899. }
  900. }
  901. else {
  902. return res.json({status: false, message: req.form.errors.join('\n')});
  903. }
  904. };
  905. actions.api.securitySetting = function(req, res) {
  906. const form = req.form.settingForm;
  907. const config = crowi.getConfig();
  908. const isPublicWikiOnly = Config.isPublicWikiOnly(config);
  909. if (isPublicWikiOnly) {
  910. const basicName = form['security:basicName'];
  911. const basicSecret = form['security:basicSecret'];
  912. if (basicName != '' || basicSecret != '') {
  913. req.form.errors.push('Public Wikiのため、Basic認証は利用できません。');
  914. return res.json({status: false, message: req.form.errors.join('\n')});
  915. }
  916. const guestMode = form['security:restrictGuestMode'];
  917. if ( guestMode == 'Deny' ) {
  918. req.form.errors.push('Private Wikiへの設定変更はできません。');
  919. return res.json({status: false, message: req.form.errors.join('\n')});
  920. }
  921. }
  922. if (req.form.isValid) {
  923. debug('form content', form);
  924. return saveSetting(req, res, form);
  925. }
  926. else {
  927. return res.json({status: false, message: req.form.errors.join('\n')});
  928. }
  929. };
  930. actions.api.securityPassportLdapSetting = function(req, res) {
  931. var form = req.form.settingForm;
  932. if (!req.form.isValid) {
  933. return res.json({status: false, message: req.form.errors.join('\n')});
  934. }
  935. debug('form content', form);
  936. return saveSettingAsync(form)
  937. .then(() => {
  938. const config = crowi.getConfig();
  939. // reset strategy
  940. crowi.passportService.resetLdapStrategy();
  941. // setup strategy
  942. if (Config.isEnabledPassportLdap(config)) {
  943. crowi.passportService.setupLdapStrategy(true);
  944. }
  945. return;
  946. })
  947. .then(() => {
  948. res.json({status: true});
  949. });
  950. };
  951. actions.api.securityPassportSamlSetting = async(req, res) => {
  952. const form = req.form.settingForm;
  953. if (!req.form.isValid) {
  954. return res.json({status: false, message: req.form.errors.join('\n')});
  955. }
  956. debug('form content', form);
  957. await saveSettingAsync(form);
  958. const config = await crowi.getConfig();
  959. // reset strategy
  960. await crowi.passportService.resetSamlStrategy();
  961. // setup strategy
  962. if (Config.isEnabledPassportSaml(config)) {
  963. try {
  964. await crowi.passportService.setupSamlStrategy(true);
  965. }
  966. catch (err) {
  967. // reset
  968. await crowi.passportService.resetSamlStrategy();
  969. return res.json({status: false, message: err.message});
  970. }
  971. }
  972. return res.json({status: true});
  973. };
  974. actions.api.securityPassportGoogleSetting = async(req, res) => {
  975. const form = req.form.settingForm;
  976. if (!req.form.isValid) {
  977. return res.json({status: false, message: req.form.errors.join('\n')});
  978. }
  979. debug('form content', form);
  980. await saveSettingAsync(form);
  981. const config = await crowi.getConfig();
  982. // reset strategy
  983. await crowi.passportService.resetGoogleStrategy();
  984. // setup strategy
  985. if (Config.isEnabledPassportGoogle(config)) {
  986. try {
  987. await crowi.passportService.setupGoogleStrategy(true);
  988. }
  989. catch (err) {
  990. // reset
  991. await crowi.passportService.resetGoogleStrategy();
  992. return res.json({status: false, message: err.message});
  993. }
  994. }
  995. return res.json({status: true});
  996. };
  997. actions.api.securityPassportGitHubSetting = async(req, res) => {
  998. const form = req.form.settingForm;
  999. if (!req.form.isValid) {
  1000. return res.json({status: false, message: req.form.errors.join('\n')});
  1001. }
  1002. debug('form content', form);
  1003. await saveSettingAsync(form);
  1004. const config = await crowi.getConfig();
  1005. // reset strategy
  1006. await crowi.passportService.resetGitHubStrategy();
  1007. // setup strategy
  1008. if (Config.isEnabledPassportGitHub(config)) {
  1009. try {
  1010. await crowi.passportService.setupGitHubStrategy(true);
  1011. }
  1012. catch (err) {
  1013. // reset
  1014. await crowi.passportService.resetGitHubStrategy();
  1015. return res.json({status: false, message: err.message});
  1016. }
  1017. }
  1018. return res.json({status: true});
  1019. };
  1020. actions.api.securityPassportTwitterSetting = async(req, res) => {
  1021. const form = req.form.settingForm;
  1022. if (!req.form.isValid) {
  1023. return res.json({status: false, message: req.form.errors.join('\n')});
  1024. }
  1025. debug('form content', form);
  1026. await saveSettingAsync(form);
  1027. const config = await crowi.getConfig();
  1028. // reset strategy
  1029. await crowi.passportService.resetTwitterStrategy();
  1030. // setup strategy
  1031. if (Config.isEnabledPassportTwitter(config)) {
  1032. try {
  1033. await crowi.passportService.setupTwitterStrategy(true);
  1034. }
  1035. catch (err) {
  1036. // reset
  1037. await crowi.passportService.resetTwitterStrategy();
  1038. return res.json({status: false, message: err.message});
  1039. }
  1040. }
  1041. return res.json({status: true});
  1042. };
  1043. actions.api.customizeSetting = function(req, res) {
  1044. const form = req.form.settingForm;
  1045. if (req.form.isValid) {
  1046. debug('form content', form);
  1047. return saveSetting(req, res, form);
  1048. }
  1049. else {
  1050. return res.json({status: false, message: req.form.errors.join('\n')});
  1051. }
  1052. };
  1053. actions.api.customizeSetting = function(req, res) {
  1054. const form = req.form.settingForm;
  1055. if (req.form.isValid) {
  1056. debug('form content', form);
  1057. return saveSetting(req, res, form);
  1058. }
  1059. else {
  1060. return res.json({status: false, message: req.form.errors.join('\n')});
  1061. }
  1062. };
  1063. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  1064. actions.api.notificationAdd = function(req, res) {
  1065. var UpdatePost = crowi.model('UpdatePost');
  1066. var pathPattern = req.body.pathPattern;
  1067. var channel = req.body.channel;
  1068. debug('notification.add', pathPattern, channel);
  1069. UpdatePost.create(pathPattern, channel, req.user)
  1070. .then(function(doc) {
  1071. debug('Successfully save updatePost', doc);
  1072. // fixme: うーん
  1073. doc.creator = doc.creator._id.toString();
  1074. return res.json(ApiResponse.success({updatePost: doc}));
  1075. }).catch(function(err) {
  1076. debug('Failed to save updatePost', err);
  1077. return res.json(ApiResponse.error());
  1078. });
  1079. };
  1080. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  1081. actions.api.notificationRemove = function(req, res) {
  1082. var UpdatePost = crowi.model('UpdatePost');
  1083. var id = req.body.id;
  1084. UpdatePost.remove(id)
  1085. .then(function() {
  1086. debug('Successfully remove updatePost');
  1087. return res.json(ApiResponse.success({}));
  1088. }).catch(function(err) {
  1089. debug('Failed to remove updatePost', err);
  1090. return res.json(ApiResponse.error());
  1091. });
  1092. };
  1093. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  1094. actions.api.usersSearch = function(req, res) {
  1095. const User = crowi.model('User');
  1096. const email =req.query.email;
  1097. User.findUsersByPartOfEmail(email, {})
  1098. .then(users => {
  1099. const result = {
  1100. data: users
  1101. };
  1102. return res.json(ApiResponse.success(result));
  1103. }).catch(err => {
  1104. return res.json(ApiResponse.error());
  1105. });
  1106. };
  1107. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  1108. const id = req.query.id;
  1109. const isEnabled = (req.query.isEnabled == 'true');
  1110. try {
  1111. if (isEnabled) {
  1112. await GlobalNotificationSetting.enable(id);
  1113. }
  1114. else {
  1115. await GlobalNotificationSetting.disable(id);
  1116. }
  1117. return res.json(ApiResponse.success());
  1118. }
  1119. catch (err) {
  1120. return res.json(ApiResponse.error());
  1121. }
  1122. };
  1123. /**
  1124. * save esa settings, update config cache, and response json
  1125. *
  1126. * @param {*} req
  1127. * @param {*} res
  1128. */
  1129. actions.api.importerSettingEsa = async(req, res) => {
  1130. const form = req.form.settingForm;
  1131. if (!req.form.isValid) {
  1132. return res.json({status: false, message: req.form.errors.join('\n')});
  1133. }
  1134. await saveSetting(req, res, form);
  1135. await importer.initializeEsaClient();
  1136. };
  1137. /**
  1138. * save qiita settings, update config cache, and response json
  1139. *
  1140. * @param {*} req
  1141. * @param {*} res
  1142. */
  1143. actions.api.importerSettingQiita = async(req, res) => {
  1144. const form = req.form.settingForm;
  1145. if (!req.form.isValid) {
  1146. return res.json({status: false, message: req.form.errors.join('\n')});
  1147. }
  1148. await saveSetting(req, res, form);
  1149. await importer.initializeQiitaClient();
  1150. };
  1151. /**
  1152. * Import all posts from esa
  1153. *
  1154. * @param {*} req
  1155. * @param {*} res
  1156. */
  1157. actions.api.importDataFromEsa = async(req, res) => {
  1158. const user = req.user;
  1159. let errors;
  1160. try {
  1161. errors = await importer.importDataFromEsa(user);
  1162. }
  1163. catch (err) {
  1164. errors = [err];
  1165. }
  1166. if (errors.length > 0) {
  1167. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1168. }
  1169. return res.json({ status: true });
  1170. };
  1171. /**
  1172. * Import all posts from qiita
  1173. *
  1174. * @param {*} req
  1175. * @param {*} res
  1176. */
  1177. actions.api.importDataFromQiita = async(req, res) => {
  1178. const user = req.user;
  1179. let errors;
  1180. try {
  1181. errors = await importer.importDataFromQiita(user);
  1182. }
  1183. catch (err) {
  1184. errors = [err];
  1185. }
  1186. if (errors.length > 0) {
  1187. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1188. }
  1189. return res.json({ status: true });
  1190. };
  1191. /**
  1192. * Test connection to esa and response result with json
  1193. *
  1194. * @param {*} req
  1195. * @param {*} res
  1196. */
  1197. actions.api.testEsaAPI = async(req, res) => {
  1198. try {
  1199. await importer.testConnectionToEsa();
  1200. return res.json({ status: true });
  1201. }
  1202. catch (err) {
  1203. return res.json({ status: false, message: `${err}` });
  1204. }
  1205. };
  1206. /**
  1207. * Test connection to qiita and response result with json
  1208. *
  1209. * @param {*} req
  1210. * @param {*} res
  1211. */
  1212. actions.api.testQiitaAPI = async(req, res) => {
  1213. try {
  1214. await importer.testConnectionToQiita();
  1215. return res.json({ status: true });
  1216. }
  1217. catch (err) {
  1218. return res.json({ status: false, message: `${err}` });
  1219. }
  1220. };
  1221. /**
  1222. * save settings, update config cache, and response json
  1223. *
  1224. * @param {any} req
  1225. * @param {any} res
  1226. * @param {any} form
  1227. */
  1228. function saveSetting(req, res, form) {
  1229. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  1230. Config.updateConfigCache('crowi', config);
  1231. return res.json({status: true});
  1232. });
  1233. }
  1234. /**
  1235. * save settings, update config cache ONLY. (this method don't response json)
  1236. *
  1237. * @param {any} form
  1238. * @returns
  1239. */
  1240. function saveSettingAsync(form) {
  1241. return new Promise((resolve, reject) => {
  1242. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  1243. if (err) {
  1244. return reject(err);
  1245. }
  1246. Config.updateConfigCache('crowi', config);
  1247. return resolve();
  1248. });
  1249. });
  1250. }
  1251. function validateMailSetting(req, form, callback) {
  1252. const mailer = crowi.mailer;
  1253. const option = {
  1254. host: form['mail:smtpHost'],
  1255. port: form['mail:smtpPort'],
  1256. };
  1257. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1258. option.auth = {
  1259. user: form['mail:smtpUser'],
  1260. pass: form['mail:smtpPassword'],
  1261. };
  1262. }
  1263. if (option.port === 465) {
  1264. option.secure = true;
  1265. }
  1266. const smtpClient = mailer.createSMTPClient(option);
  1267. debug('mailer setup for validate SMTP setting', smtpClient);
  1268. smtpClient.sendMail({
  1269. from: form['mail:from'],
  1270. to: req.user.email,
  1271. subject: 'Wiki管理設定のアップデートによるメール通知',
  1272. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  1273. }, callback);
  1274. }
  1275. return actions;
  1276. };