admin.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  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.customizeSetting = function(req, res) {
  963. const form = req.form.settingForm;
  964. if (req.form.isValid) {
  965. debug('form content', form);
  966. return saveSetting(req, res, form);
  967. }
  968. else {
  969. return res.json({status: false, message: req.form.errors.join('\n')});
  970. }
  971. };
  972. actions.api.customizeSetting = function(req, res) {
  973. const form = req.form.settingForm;
  974. if (req.form.isValid) {
  975. debug('form content', form);
  976. return saveSetting(req, res, form);
  977. }
  978. else {
  979. return res.json({status: false, message: req.form.errors.join('\n')});
  980. }
  981. };
  982. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  983. actions.api.notificationAdd = function(req, res) {
  984. var UpdatePost = crowi.model('UpdatePost');
  985. var pathPattern = req.body.pathPattern;
  986. var channel = req.body.channel;
  987. debug('notification.add', pathPattern, channel);
  988. UpdatePost.create(pathPattern, channel, req.user)
  989. .then(function(doc) {
  990. debug('Successfully save updatePost', doc);
  991. // fixme: うーん
  992. doc.creator = doc.creator._id.toString();
  993. return res.json(ApiResponse.success({updatePost: doc}));
  994. }).catch(function(err) {
  995. debug('Failed to save updatePost', err);
  996. return res.json(ApiResponse.error());
  997. });
  998. };
  999. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  1000. actions.api.notificationRemove = function(req, res) {
  1001. var UpdatePost = crowi.model('UpdatePost');
  1002. var id = req.body.id;
  1003. UpdatePost.remove(id)
  1004. .then(function() {
  1005. debug('Successfully remove updatePost');
  1006. return res.json(ApiResponse.success({}));
  1007. }).catch(function(err) {
  1008. debug('Failed to remove updatePost', err);
  1009. return res.json(ApiResponse.error());
  1010. });
  1011. };
  1012. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  1013. actions.api.usersSearch = function(req, res) {
  1014. const User = crowi.model('User');
  1015. const email =req.query.email;
  1016. User.findUsersByPartOfEmail(email, {})
  1017. .then(users => {
  1018. const result = {
  1019. data: users
  1020. };
  1021. return res.json(ApiResponse.success(result));
  1022. }).catch(err => {
  1023. return res.json(ApiResponse.error());
  1024. });
  1025. };
  1026. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  1027. const id = req.query.id;
  1028. const isEnabled = (req.query.isEnabled == 'true');
  1029. try {
  1030. if (isEnabled) {
  1031. await GlobalNotificationSetting.enable(id);
  1032. }
  1033. else {
  1034. await GlobalNotificationSetting.disable(id);
  1035. }
  1036. return res.json(ApiResponse.success());
  1037. }
  1038. catch (err) {
  1039. return res.json(ApiResponse.error());
  1040. }
  1041. };
  1042. /**
  1043. * save settings, update config cache, and response json
  1044. *
  1045. * @param {*} req
  1046. * @param {*} res
  1047. */
  1048. actions.api.importerSetting = async(req, res) => {
  1049. const form = req.form.settingForm;
  1050. if (!req.form.isValid) {
  1051. return res.json({status: false, message: req.form.errors.join('\n')});
  1052. }
  1053. await saveSetting(req, res, form);
  1054. await importer.initialize();
  1055. };
  1056. /**
  1057. * Import all posts from esa
  1058. *
  1059. * @param {*} req
  1060. * @param {*} res
  1061. */
  1062. actions.api.importDataFromEsa = async(req, res) => {
  1063. const user = req.user;
  1064. const errors = await importer.importDataFromEsa(user);
  1065. if (errors) {
  1066. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1067. }
  1068. return res.json({ status: true });
  1069. };
  1070. /**
  1071. * Import all posts from qiita
  1072. *
  1073. * @param {*} req
  1074. * @param {*} res
  1075. */
  1076. actions.api.importDataFromQiita = async(req, res) => {
  1077. const user = req.user;
  1078. const errors = await importer.importDataFromQiita(user);
  1079. if (errors) {
  1080. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1081. }
  1082. return res.json({ status: true });
  1083. };
  1084. /**
  1085. * Test connection to esa and response result with json
  1086. *
  1087. * @param {*} req
  1088. * @param {*} res
  1089. */
  1090. actions.api.testEsaAPI = async(req, res) => {
  1091. try {
  1092. await importer.testConnectionToEsa();
  1093. return res.json({ status: true });
  1094. }
  1095. catch (err) {
  1096. return res.json({ status: false, message: `${err}` });
  1097. }
  1098. };
  1099. /**
  1100. * Test connection to qiita and response result with json
  1101. *
  1102. * @param {*} req
  1103. * @param {*} res
  1104. */
  1105. actions.api.testQiitaAPI = async(req, res) => {
  1106. try {
  1107. await importer.testConnectionToQiita();
  1108. return res.json({ status: true });
  1109. }
  1110. catch (err) {
  1111. return res.json({ status: false, message: `${err}` });
  1112. }
  1113. };
  1114. /**
  1115. * save settings, update config cache, and response json
  1116. *
  1117. * @param {any} req
  1118. * @param {any} res
  1119. * @param {any} form
  1120. */
  1121. function saveSetting(req, res, form) {
  1122. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  1123. Config.updateConfigCache('crowi', config);
  1124. return res.json({status: true});
  1125. });
  1126. }
  1127. /**
  1128. * save settings, update config cache ONLY. (this method don't response json)
  1129. *
  1130. * @param {any} form
  1131. * @returns
  1132. */
  1133. function saveSettingAsync(form) {
  1134. return new Promise((resolve, reject) => {
  1135. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  1136. if (err) {
  1137. return reject(err);
  1138. }
  1139. Config.updateConfigCache('crowi', config);
  1140. return resolve();
  1141. });
  1142. });
  1143. }
  1144. function validateMailSetting(req, form, callback) {
  1145. var mailer = crowi.mailer;
  1146. var option = {
  1147. host: form['mail:smtpHost'],
  1148. port: form['mail:smtpPort'],
  1149. };
  1150. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1151. option.auth = {
  1152. user: form['mail:smtpUser'],
  1153. pass: form['mail:smtpPassword'],
  1154. };
  1155. }
  1156. if (option.port === 465) {
  1157. option.secure = true;
  1158. }
  1159. var smtpClient = mailer.createSMTPClient(option);
  1160. debug('mailer setup for validate SMTP setting', smtpClient);
  1161. smtpClient.sendMail({
  1162. from: form['mail:from'],
  1163. to: req.user.email,
  1164. subject: 'Wiki管理設定のアップデートによるメール通知',
  1165. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  1166. }, callback);
  1167. }
  1168. return actions;
  1169. };