admin.js 35 KB

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