admin.js 45 KB

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