admin.js 42 KB

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