admin.js 44 KB

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