admin.js 35 KB

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