admin.js 45 KB

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