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