admin.js 39 KB

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