admin.js 38 KB

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