admin.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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 = async function(req, res) {
  548. const id = req.params.id;
  549. let account = null;
  550. try {
  551. account = await ExternalAccount.findByIdAndRemove(id);
  552. if (account == null) {
  553. throw new Error('削除に失敗しました。');
  554. }
  555. }
  556. catch (err) {
  557. req.flash('errorMessage', err.message);
  558. return res.redirect('/admin/users/external-accounts');
  559. }
  560. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  561. return res.redirect('/admin/users/external-accounts');
  562. };
  563. actions.userGroup = {};
  564. actions.userGroup.index = function(req, res) {
  565. var page = parseInt(req.query.page) || 1;
  566. const isAclEnabled = !Config.isPublicWikiOnly(req.config);
  567. var renderVar = {
  568. userGroups: [],
  569. userGroupRelations: new Map(),
  570. pager: null,
  571. isAclEnabled,
  572. };
  573. UserGroup.findUserGroupsWithPagination({ page: page })
  574. .then((result) => {
  575. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  576. var userGroups = result.docs;
  577. renderVar.userGroups = userGroups;
  578. renderVar.pager = pager;
  579. return userGroups.map((userGroup) => {
  580. return new Promise((resolve, reject) => {
  581. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  582. .then((relations) => {
  583. return resolve([userGroup, relations]);
  584. });
  585. });
  586. });
  587. })
  588. .then((allRelationsPromise) => {
  589. return Promise.all(allRelationsPromise);
  590. })
  591. .then((relations) => {
  592. renderVar.userGroupRelations = new Map(relations);
  593. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  594. return res.render('admin/user-groups', renderVar);
  595. })
  596. .catch( function(err) {
  597. debug('Error on find all relations', err);
  598. return res.json(ApiResponse.error('Error'));
  599. });
  600. };
  601. // グループ詳細
  602. actions.userGroup.detail = function(req, res) {
  603. const userGroupId = req.params.id;
  604. const renderVar = {
  605. userGroup: null,
  606. userGroupRelations: [],
  607. pageGroupRelations: [],
  608. notRelatedusers: []
  609. };
  610. let targetUserGroup = null;
  611. UserGroup.findOne({ _id: userGroupId})
  612. .then(function(userGroup) {
  613. targetUserGroup = userGroup;
  614. if (targetUserGroup == null) {
  615. req.flash('errorMessage', 'グループがありません');
  616. throw new Error('no userGroup is exists. ', name);
  617. }
  618. else {
  619. renderVar.userGroup = targetUserGroup;
  620. return Promise.all([
  621. // get all user and group relations
  622. UserGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  623. // get all page and group relations
  624. PageGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  625. // get all not related users for group
  626. UserGroupRelation.findUserByNotRelatedGroup(targetUserGroup),
  627. ]);
  628. }
  629. })
  630. .then((resolves) => {
  631. renderVar.userGroupRelations = resolves[0];
  632. renderVar.pageGroupRelations = resolves[1];
  633. renderVar.notRelatedusers = resolves[2];
  634. debug('notRelatedusers', renderVar.notRelatedusers);
  635. return res.render('admin/user-group-detail', renderVar);
  636. })
  637. .catch((err) => {
  638. req.flash('errorMessage', 'ユーザグループの検索に失敗しました');
  639. debug('Error on get userGroupDetail', err);
  640. return res.redirect('/admin/user-groups');
  641. });
  642. };
  643. //グループの生成
  644. actions.userGroup.create = function(req, res) {
  645. const form = req.form.createGroupForm;
  646. if (req.form.isValid) {
  647. const userGroupName = crowi.xss.process(form.userGroupName);
  648. UserGroup.createGroupByName(userGroupName)
  649. .then((newUserGroup) => {
  650. req.flash('successMessage', newUserGroup.name);
  651. req.flash('createdUserGroup', newUserGroup);
  652. return res.redirect('/admin/user-groups');
  653. })
  654. .catch((err) => {
  655. debug('create userGroup error:', err);
  656. req.flash('errorMessage', '同じグループ名が既に存在します。');
  657. });
  658. }
  659. else {
  660. req.flash('errorMessage', req.form.errors.join('\n'));
  661. return res.redirect('/admin/user-groups');
  662. }
  663. };
  664. //
  665. actions.userGroup.update = function(req, res) {
  666. const userGroupId = req.params.userGroupId;
  667. const name = crowi.xss.process(req.body.name);
  668. UserGroup.findById(userGroupId)
  669. .then((userGroupData) => {
  670. if (userGroupData == null) {
  671. req.flash('errorMessage', 'グループの検索に失敗しました。');
  672. return new Promise();
  673. }
  674. else {
  675. // 名前存在チェック
  676. return UserGroup.isRegisterableName(name)
  677. .then((isRegisterableName) => {
  678. // 既に存在するグループ名に更新しようとした場合はエラー
  679. if (!isRegisterableName) {
  680. req.flash('errorMessage', 'グループ名が既に存在します。');
  681. }
  682. else {
  683. return userGroupData.updateName(name)
  684. .then(() => {
  685. req.flash('successMessage', 'グループ名を更新しました。');
  686. })
  687. .catch((err) => {
  688. req.flash('errorMessage', 'グループ名の更新に失敗しました。');
  689. });
  690. }
  691. });
  692. }
  693. })
  694. .then(() => {
  695. return res.redirect('/admin/user-group-detail/' + userGroupId);
  696. });
  697. };
  698. actions.userGroup.uploadGroupPicture = function(req, res) {
  699. var fileUploader = require('../service/file-uploader')(crowi, app);
  700. //var storagePlugin = new pluginService('storage');
  701. //var storage = require('../service/storage').StorageService(config);
  702. var userGroupId = req.params.userGroupId;
  703. var tmpFile = req.file || null;
  704. if (!tmpFile) {
  705. return res.json({
  706. 'status': false,
  707. 'message': 'File type error.'
  708. });
  709. }
  710. UserGroup.findById(userGroupId, function(err, userGroupData) {
  711. if (!userGroupData) {
  712. return res.json({
  713. 'status': false,
  714. 'message': 'UserGroup error.'
  715. });
  716. }
  717. var tmpPath = tmpFile.path;
  718. var filePath = UserGroup.createUserGroupPictureFilePath(userGroupData, tmpFile.filename + tmpFile.originalname);
  719. var acceptableFileType = /image\/.+/;
  720. if (!tmpFile.mimetype.match(acceptableFileType)) {
  721. return res.json({
  722. 'status': false,
  723. 'message': 'File type error. Only image files is allowed to set as user picture.',
  724. });
  725. }
  726. var tmpFileStream = fs.createReadStream(tmpPath, { flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  727. fileUploader.uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
  728. .then(function(data) {
  729. var imageUrl = fileUploader.generateUrl(filePath);
  730. userGroupData.updateImage(imageUrl)
  731. .then(() => {
  732. fs.unlink(tmpPath, function(err) {
  733. if (err) {
  734. debug('Error while deleting tmp file.', err);
  735. }
  736. return res.json({
  737. 'status': true,
  738. 'url': imageUrl,
  739. 'message': '',
  740. });
  741. });
  742. });
  743. }).catch(function(err) {
  744. debug('Uploading error', err);
  745. return res.json({
  746. 'status': false,
  747. 'message': 'Error while uploading to ',
  748. });
  749. });
  750. });
  751. };
  752. actions.userGroup.deletePicture = function(req, res) {
  753. const userGroupId = req.params.userGroupId;
  754. let userGroupName = null;
  755. UserGroup.findById(userGroupId)
  756. .then((userGroupData) => {
  757. if (userGroupData == null) {
  758. return Promise.reject();
  759. }
  760. else {
  761. userGroupName = userGroupData.name;
  762. return userGroupData.deleteImage();
  763. }
  764. })
  765. .then((updated) => {
  766. req.flash('successMessage', 'Deleted group picture');
  767. return res.redirect('/admin/user-group-detail/' + userGroupId);
  768. })
  769. .catch((err) => {
  770. debug('An error occured.', err);
  771. req.flash('errorMessage', 'Error while deleting group picture');
  772. if (userGroupName == null) {
  773. return res.redirect('/admin/user-groups/');
  774. }
  775. else {
  776. return res.redirect('/admin/user-group-detail/' + userGroupId);
  777. }
  778. });
  779. };
  780. // app.post('/_api/admin/user-group/delete' , admin.userGroup.removeCompletely);
  781. actions.userGroup.removeCompletely = function(req, res) {
  782. const id = req.body.user_group_id;
  783. const fileUploader = require('../service/file-uploader')(crowi, app);
  784. UserGroup.removeCompletelyById(id)
  785. //// TODO remove attachments
  786. // couldn't remove because filePath includes '/uploads/uploads'
  787. // Error: ENOENT: no such file or directory, unlink 'C:\dev\growi\public\uploads\uploads\userGroup\5b1df18ab69611651cc71495.png
  788. //
  789. // .then(removed => {
  790. // if (removed.image != null) {
  791. // fileUploader.deleteFile(null, removed.image);
  792. // }
  793. // })
  794. .then(() => {
  795. req.flash('successMessage', '削除しました');
  796. return res.redirect('/admin/user-groups');
  797. })
  798. .catch((err) => {
  799. debug('Error while removing userGroup.', err, id);
  800. req.flash('errorMessage', '完全な削除に失敗しました。');
  801. return res.redirect('/admin/user-groups');
  802. });
  803. };
  804. actions.userGroupRelation = {};
  805. actions.userGroupRelation.index = function(req, res) {
  806. };
  807. actions.userGroupRelation.create = function(req, res) {
  808. const User = crowi.model('User');
  809. const UserGroup = crowi.model('UserGroup');
  810. const UserGroupRelation = crowi.model('UserGroupRelation');
  811. // req params
  812. const userName = req.body.user_name;
  813. const userGroupId = req.body.user_group_id;
  814. let user = null;
  815. let userGroup = null;
  816. Promise.all([
  817. // ユーザグループをIDで検索
  818. UserGroup.findById(userGroupId),
  819. // ユーザを名前で検索
  820. User.findUserByUsername(userName),
  821. ])
  822. .then((resolves) => {
  823. userGroup = resolves[0];
  824. user = resolves[1];
  825. // Relation を作成
  826. UserGroupRelation.createRelation(userGroup, user);
  827. })
  828. .then((result) => {
  829. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  830. }).catch((err) => {
  831. debug('Error on create user-group relation', err);
  832. req.flash('errorMessage', 'Error on create user-group relation');
  833. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  834. });
  835. };
  836. actions.userGroupRelation.remove = function(req, res) {
  837. const UserGroupRelation = crowi.model('UserGroupRelation');
  838. const userGroupId = req.params.id;
  839. const relationId = req.params.relationId;
  840. UserGroupRelation.removeById(relationId)
  841. .then(() =>{
  842. return res.redirect('/admin/user-group-detail/' + userGroupId);
  843. })
  844. .catch((err) => {
  845. debug('Error on remove user-group-relation', err);
  846. req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
  847. });
  848. };
  849. // Importer management
  850. actions.importer = {};
  851. actions.importer.index = function(req, res) {
  852. var settingForm;
  853. settingForm = Config.setupConfigFormData('crowi', req.config);
  854. return res.render('admin/importer', {
  855. settingForm: settingForm,
  856. });
  857. };
  858. actions.api = {};
  859. actions.api.appSetting = function(req, res) {
  860. var form = req.form.settingForm;
  861. if (req.form.isValid) {
  862. debug('form content', form);
  863. // mail setting ならここで validation
  864. if (form['mail:from']) {
  865. validateMailSetting(req, form, function(err, data) {
  866. debug('Error validate mail setting: ', err, data);
  867. if (err) {
  868. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  869. return res.json({status: false, message: req.form.errors.join('\n')});
  870. }
  871. return saveSetting(req, res, form);
  872. });
  873. }
  874. else {
  875. return saveSetting(req, res, form);
  876. }
  877. }
  878. else {
  879. return res.json({status: false, message: req.form.errors.join('\n')});
  880. }
  881. };
  882. actions.api.asyncAppSetting = async(req, res) => {
  883. const form = req.form.settingForm;
  884. if (!req.form.isValid) {
  885. return res.json({status: false, message: req.form.errors.join('\n')});
  886. }
  887. debug('form content', form);
  888. try {
  889. await crowi.configManager.updateConfigsInTheSameNamespace('crowi', form);
  890. return res.json({status: true});
  891. }
  892. catch (err) {
  893. logger.error(err);
  894. return res.json({status: false});
  895. }
  896. };
  897. actions.api.securitySetting = function(req, res) {
  898. const form = req.form.settingForm;
  899. const config = crowi.getConfig();
  900. const isPublicWikiOnly = Config.isPublicWikiOnly(config);
  901. if (isPublicWikiOnly) {
  902. const basicName = form['security:basicName'];
  903. const basicSecret = form['security:basicSecret'];
  904. if (basicName != '' || basicSecret != '') {
  905. req.form.errors.push('Public Wikiのため、Basic認証は利用できません。');
  906. return res.json({status: false, message: req.form.errors.join('\n')});
  907. }
  908. const guestMode = form['security:restrictGuestMode'];
  909. if ( guestMode == 'Deny' ) {
  910. req.form.errors.push('Private Wikiへの設定変更はできません。');
  911. return res.json({status: false, message: req.form.errors.join('\n')});
  912. }
  913. }
  914. if (req.form.isValid) {
  915. debug('form content', form);
  916. return saveSetting(req, res, form);
  917. }
  918. else {
  919. return res.json({status: false, message: req.form.errors.join('\n')});
  920. }
  921. };
  922. actions.api.securityPassportLdapSetting = function(req, res) {
  923. var form = req.form.settingForm;
  924. if (!req.form.isValid) {
  925. return res.json({status: false, message: req.form.errors.join('\n')});
  926. }
  927. debug('form content', form);
  928. return saveSettingAsync(form)
  929. .then(() => {
  930. const config = crowi.getConfig();
  931. // reset strategy
  932. crowi.passportService.resetLdapStrategy();
  933. // setup strategy
  934. if (Config.isEnabledPassportLdap(config)) {
  935. crowi.passportService.setupLdapStrategy(true);
  936. }
  937. return;
  938. })
  939. .then(() => {
  940. res.json({status: true});
  941. });
  942. };
  943. actions.api.securityPassportSamlSetting = async(req, res) => {
  944. const form = req.form.settingForm;
  945. validateSamlSettingForm(req.form, req.t);
  946. if (!req.form.isValid) {
  947. return res.json({status: false, message: req.form.errors.join('\n')});
  948. }
  949. debug('form content', form);
  950. await crowi.configManager.updateConfigsInTheSameNamespace('crowi', form);
  951. // reset strategy
  952. await crowi.passportService.resetSamlStrategy();
  953. // setup strategy
  954. if (crowi.configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  955. try {
  956. await crowi.passportService.setupSamlStrategy(true);
  957. }
  958. catch (err) {
  959. // reset
  960. await crowi.passportService.resetSamlStrategy();
  961. return res.json({status: false, message: err.message});
  962. }
  963. }
  964. return res.json({status: true});
  965. };
  966. actions.api.securityPassportGoogleSetting = async(req, res) => {
  967. const form = req.form.settingForm;
  968. if (!req.form.isValid) {
  969. return res.json({status: false, message: req.form.errors.join('\n')});
  970. }
  971. debug('form content', form);
  972. await saveSettingAsync(form);
  973. const config = await crowi.getConfig();
  974. // reset strategy
  975. await crowi.passportService.resetGoogleStrategy();
  976. // setup strategy
  977. if (Config.isEnabledPassportGoogle(config)) {
  978. try {
  979. await crowi.passportService.setupGoogleStrategy(true);
  980. }
  981. catch (err) {
  982. // reset
  983. await crowi.passportService.resetGoogleStrategy();
  984. return res.json({status: false, message: err.message});
  985. }
  986. }
  987. return res.json({status: true});
  988. };
  989. actions.api.securityPassportGitHubSetting = async(req, res) => {
  990. const form = req.form.settingForm;
  991. if (!req.form.isValid) {
  992. return res.json({status: false, message: req.form.errors.join('\n')});
  993. }
  994. debug('form content', form);
  995. await saveSettingAsync(form);
  996. const config = await crowi.getConfig();
  997. // reset strategy
  998. await crowi.passportService.resetGitHubStrategy();
  999. // setup strategy
  1000. if (Config.isEnabledPassportGitHub(config)) {
  1001. try {
  1002. await crowi.passportService.setupGitHubStrategy(true);
  1003. }
  1004. catch (err) {
  1005. // reset
  1006. await crowi.passportService.resetGitHubStrategy();
  1007. return res.json({status: false, message: err.message});
  1008. }
  1009. }
  1010. return res.json({status: true});
  1011. };
  1012. actions.api.securityPassportTwitterSetting = async(req, res) => {
  1013. const form = req.form.settingForm;
  1014. if (!req.form.isValid) {
  1015. return res.json({status: false, message: req.form.errors.join('\n')});
  1016. }
  1017. debug('form content', form);
  1018. await saveSettingAsync(form);
  1019. const config = await crowi.getConfig();
  1020. // reset strategy
  1021. await crowi.passportService.resetTwitterStrategy();
  1022. // setup strategy
  1023. if (Config.isEnabledPassportTwitter(config)) {
  1024. try {
  1025. await crowi.passportService.setupTwitterStrategy(true);
  1026. }
  1027. catch (err) {
  1028. // reset
  1029. await crowi.passportService.resetTwitterStrategy();
  1030. return res.json({status: false, message: err.message});
  1031. }
  1032. }
  1033. return res.json({status: true});
  1034. };
  1035. actions.api.customizeSetting = function(req, res) {
  1036. const form = req.form.settingForm;
  1037. if (req.form.isValid) {
  1038. debug('form content', form);
  1039. return saveSetting(req, res, form);
  1040. }
  1041. else {
  1042. return res.json({status: false, message: req.form.errors.join('\n')});
  1043. }
  1044. };
  1045. actions.api.customizeSetting = function(req, res) {
  1046. const form = req.form.settingForm;
  1047. if (req.form.isValid) {
  1048. debug('form content', form);
  1049. return saveSetting(req, res, form);
  1050. }
  1051. else {
  1052. return res.json({status: false, message: req.form.errors.join('\n')});
  1053. }
  1054. };
  1055. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  1056. actions.api.notificationAdd = function(req, res) {
  1057. var UpdatePost = crowi.model('UpdatePost');
  1058. var pathPattern = req.body.pathPattern;
  1059. var channel = req.body.channel;
  1060. debug('notification.add', pathPattern, channel);
  1061. UpdatePost.create(pathPattern, channel, req.user)
  1062. .then(function(doc) {
  1063. debug('Successfully save updatePost', doc);
  1064. // fixme: うーん
  1065. doc.creator = doc.creator._id.toString();
  1066. return res.json(ApiResponse.success({updatePost: doc}));
  1067. }).catch(function(err) {
  1068. debug('Failed to save updatePost', err);
  1069. return res.json(ApiResponse.error());
  1070. });
  1071. };
  1072. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  1073. actions.api.notificationRemove = function(req, res) {
  1074. var UpdatePost = crowi.model('UpdatePost');
  1075. var id = req.body.id;
  1076. UpdatePost.remove(id)
  1077. .then(function() {
  1078. debug('Successfully remove updatePost');
  1079. return res.json(ApiResponse.success({}));
  1080. }).catch(function(err) {
  1081. debug('Failed to remove updatePost', err);
  1082. return res.json(ApiResponse.error());
  1083. });
  1084. };
  1085. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  1086. actions.api.usersSearch = function(req, res) {
  1087. const User = crowi.model('User');
  1088. const email =req.query.email;
  1089. User.findUsersByPartOfEmail(email, {})
  1090. .then(users => {
  1091. const result = {
  1092. data: users
  1093. };
  1094. return res.json(ApiResponse.success(result));
  1095. }).catch(err => {
  1096. return res.json(ApiResponse.error());
  1097. });
  1098. };
  1099. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  1100. const id = req.query.id;
  1101. const isEnabled = (req.query.isEnabled == 'true');
  1102. try {
  1103. if (isEnabled) {
  1104. await GlobalNotificationSetting.enable(id);
  1105. }
  1106. else {
  1107. await GlobalNotificationSetting.disable(id);
  1108. }
  1109. return res.json(ApiResponse.success());
  1110. }
  1111. catch (err) {
  1112. return res.json(ApiResponse.error());
  1113. }
  1114. };
  1115. /**
  1116. * save esa settings, update config cache, and response json
  1117. *
  1118. * @param {*} req
  1119. * @param {*} res
  1120. */
  1121. actions.api.importerSettingEsa = async(req, res) => {
  1122. const form = req.form.settingForm;
  1123. if (!req.form.isValid) {
  1124. return res.json({status: false, message: req.form.errors.join('\n')});
  1125. }
  1126. await saveSetting(req, res, form);
  1127. await importer.initializeEsaClient();
  1128. };
  1129. /**
  1130. * save qiita settings, update config cache, and response json
  1131. *
  1132. * @param {*} req
  1133. * @param {*} res
  1134. */
  1135. actions.api.importerSettingQiita = async(req, res) => {
  1136. const form = req.form.settingForm;
  1137. if (!req.form.isValid) {
  1138. return res.json({status: false, message: req.form.errors.join('\n')});
  1139. }
  1140. await saveSetting(req, res, form);
  1141. await importer.initializeQiitaClient();
  1142. };
  1143. /**
  1144. * Import all posts from esa
  1145. *
  1146. * @param {*} req
  1147. * @param {*} res
  1148. */
  1149. actions.api.importDataFromEsa = async(req, res) => {
  1150. const user = req.user;
  1151. let errors;
  1152. try {
  1153. errors = await importer.importDataFromEsa(user);
  1154. }
  1155. catch (err) {
  1156. errors = [err];
  1157. }
  1158. if (errors.length > 0) {
  1159. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1160. }
  1161. return res.json({ status: true });
  1162. };
  1163. /**
  1164. * Import all posts from qiita
  1165. *
  1166. * @param {*} req
  1167. * @param {*} res
  1168. */
  1169. actions.api.importDataFromQiita = async(req, res) => {
  1170. const user = req.user;
  1171. let errors;
  1172. try {
  1173. errors = await importer.importDataFromQiita(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. * Test connection to esa and response result with json
  1185. *
  1186. * @param {*} req
  1187. * @param {*} res
  1188. */
  1189. actions.api.testEsaAPI = async(req, res) => {
  1190. try {
  1191. await importer.testConnectionToEsa();
  1192. return res.json({ status: true });
  1193. }
  1194. catch (err) {
  1195. return res.json({ status: false, message: `${err}` });
  1196. }
  1197. };
  1198. /**
  1199. * Test connection to qiita and response result with json
  1200. *
  1201. * @param {*} req
  1202. * @param {*} res
  1203. */
  1204. actions.api.testQiitaAPI = async(req, res) => {
  1205. try {
  1206. await importer.testConnectionToQiita();
  1207. return res.json({ status: true });
  1208. }
  1209. catch (err) {
  1210. return res.json({ status: false, message: `${err}` });
  1211. }
  1212. };
  1213. actions.api.searchBuildIndex = async function(req, res) {
  1214. const search = crowi.getSearcher();
  1215. if (!search) {
  1216. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  1217. }
  1218. // first, delete index
  1219. try {
  1220. await search.deleteIndex();
  1221. }
  1222. catch (err) {
  1223. logger.warn('Delete index Error, but if it is initialize, its ok.', err);
  1224. }
  1225. // second, create index
  1226. try {
  1227. await search.buildIndex();
  1228. }
  1229. catch (err) {
  1230. logger.error('Error', err);
  1231. return res.json(ApiResponse.error(err));
  1232. }
  1233. searchEvent.on('addPageProgress', (total, current, skip) => {
  1234. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  1235. });
  1236. searchEvent.on('finishAddPage', (total, current, skip) => {
  1237. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  1238. });
  1239. // add all page
  1240. search
  1241. .addAllPages()
  1242. .then(() => {
  1243. debug('Data is successfully indexed. ------------------ ✧✧');
  1244. })
  1245. .catch(err => {
  1246. logger.error('Error', err);
  1247. });
  1248. return res.json(ApiResponse.success());
  1249. };
  1250. /**
  1251. * save settings, update config cache, and response json
  1252. *
  1253. * @param {any} req
  1254. * @param {any} res
  1255. * @param {any} form
  1256. */
  1257. function saveSetting(req, res, form) {
  1258. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  1259. Config.updateConfigCache('crowi', config);
  1260. return res.json({status: true});
  1261. });
  1262. }
  1263. /**
  1264. * save settings, update config cache ONLY. (this method don't response json)
  1265. *
  1266. * @param {any} form
  1267. * @returns
  1268. */
  1269. function saveSettingAsync(form) {
  1270. return new Promise((resolve, reject) => {
  1271. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  1272. if (err) {
  1273. return reject(err);
  1274. }
  1275. Config.updateConfigCache('crowi', config);
  1276. return resolve();
  1277. });
  1278. });
  1279. }
  1280. function validateMailSetting(req, form, callback) {
  1281. const mailer = crowi.mailer;
  1282. const option = {
  1283. host: form['mail:smtpHost'],
  1284. port: form['mail:smtpPort'],
  1285. };
  1286. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1287. option.auth = {
  1288. user: form['mail:smtpUser'],
  1289. pass: form['mail:smtpPassword'],
  1290. };
  1291. }
  1292. if (option.port === 465) {
  1293. option.secure = true;
  1294. }
  1295. const smtpClient = mailer.createSMTPClient(option);
  1296. debug('mailer setup for validate SMTP setting', smtpClient);
  1297. smtpClient.sendMail({
  1298. from: form['mail:from'],
  1299. to: req.user.email,
  1300. subject: 'Wiki管理設定のアップデートによるメール通知',
  1301. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  1302. }, callback);
  1303. }
  1304. /**
  1305. * validate setting form values for SAML
  1306. *
  1307. * This validation checks, for the value of each mandatory items,
  1308. * whether it from the environment variables is empty and form value to update it is empty.
  1309. */
  1310. function validateSamlSettingForm(form, t) {
  1311. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  1312. const formValue = form.settingForm[key];
  1313. if (crowi.configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  1314. const formItemName = t(`security_setting.form_item_name.${key}`);
  1315. form.errors.push(t('form_validation.required', formItemName));
  1316. }
  1317. }
  1318. }
  1319. return actions;
  1320. };