admin.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. , MAX_PAGE_LIST = 50
  17. , actions = {};
  18. function createPager(total, limit, page, pagesCount, maxPageList) {
  19. const pager = {
  20. page: page,
  21. pagesCount: pagesCount,
  22. pages: [],
  23. total: total,
  24. previous: null,
  25. previousDots: false,
  26. next: null,
  27. nextDots: false,
  28. };
  29. if (page > 1) {
  30. pager.previous = page - 1;
  31. }
  32. if (page < pagesCount) {
  33. pager.next = page + 1;
  34. }
  35. let pagerMin = Math.max(1, Math.ceil(page - maxPageList/2));
  36. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList/2));
  37. if (pagerMin === 1) {
  38. if (MAX_PAGE_LIST < pagesCount) {
  39. pagerMax = MAX_PAGE_LIST;
  40. }
  41. else {
  42. pagerMax = pagesCount;
  43. }
  44. }
  45. if (pagerMax === pagesCount) {
  46. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  47. pagerMin = 1;
  48. }
  49. else {
  50. pagerMin = pagerMax - MAX_PAGE_LIST;
  51. }
  52. }
  53. pager.previousDots = null;
  54. if (pagerMin > 1) {
  55. pager.previousDots = true;
  56. }
  57. pager.nextDots = null;
  58. if (pagerMax < pagesCount) {
  59. pager.nextDots = true;
  60. }
  61. for (let i = pagerMin; i <= pagerMax; i++) {
  62. pager.pages.push(i);
  63. }
  64. return pager;
  65. }
  66. actions.index = function(req, res) {
  67. return res.render('admin/index', {
  68. plugins: pluginUtils.listPlugins(crowi.rootDir),
  69. });
  70. };
  71. // app.get('/admin/app' , admin.app.index);
  72. actions.app = {};
  73. actions.app.index = function(req, res) {
  74. var settingForm;
  75. settingForm = Config.setupCofigFormData('crowi', req.config);
  76. return res.render('admin/app', {
  77. settingForm: settingForm,
  78. });
  79. };
  80. actions.app.settingUpdate = function(req, res) {
  81. };
  82. // app.get('/admin/security' , admin.security.index);
  83. actions.security = {};
  84. actions.security.index = function(req, res) {
  85. const settingForm = Config.setupCofigFormData('crowi', req.config);
  86. return res.render('admin/security', { settingForm });
  87. };
  88. // app.get('/admin/markdown' , admin.markdown.index);
  89. actions.markdown = {};
  90. actions.markdown.index = function(req, res) {
  91. var config = crowi.getConfig();
  92. var markdownSetting = Config.setupCofigFormData('markdown', config);
  93. return res.render('admin/markdown', {
  94. markdownSetting: markdownSetting,
  95. });
  96. };
  97. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  98. actions.markdown.lineBreaksSetting = function(req, res) {
  99. var markdownSetting = req.form.markdownSetting;
  100. req.session.markdownSetting = markdownSetting;
  101. if (req.form.isValid) {
  102. Config.updateNamespaceByArray('markdown', markdownSetting, function(err, config) {
  103. Config.updateConfigCache('markdown', config);
  104. req.session.markdownSetting = null;
  105. req.flash('successMessage', ['Successfully updated!']);
  106. return res.redirect('/admin/markdown');
  107. });
  108. }
  109. else {
  110. req.flash('errorMessage', req.form.errors);
  111. return res.redirect('/admin/markdown');
  112. }
  113. };
  114. // app.post('/admin/markdown/XSSSetting' , admin.markdown.XSSSetting);
  115. actions.markdown.XSSSetting = function(req, res) {
  116. let XSSSetting = req.form.markdownSetting;
  117. XSSSetting['markdown:XSS:tagWhiteList'] = stringToArray(XSSSetting['markdown:XSS:tagWhiteList']);
  118. XSSSetting['markdown:XSS:attrWhiteList'] = stringToArray(XSSSetting['markdown:XSS:attrWhiteList']);
  119. req.session.markdownSetting = XSSSetting;
  120. if (req.form.isValid) {
  121. Config.updateNamespaceByArray('markdown', XSSSetting, function(err, config) {
  122. Config.updateConfigCache('markdown', config);
  123. req.session.XSSSetting = null;
  124. req.flash('successMessage', ['Successfully updated!']);
  125. return res.redirect('/admin/markdown');
  126. });
  127. }
  128. else {
  129. req.flash('errorMessage', req.form.errors);
  130. return res.redirect('/admin/markdown');
  131. }
  132. };
  133. const stringToArray = (string) => {
  134. let array = string.split(',');
  135. for (let i = 0; i < array.length; i++) {
  136. array[i] = array[i].trim();
  137. }
  138. return array;
  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. var 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. ExternalAccount.remove({user: userData})
  421. .then((err) => {
  422. if (err) {
  423. throw new Error(err.message);
  424. }
  425. return userData;
  426. });
  427. })
  428. .then((userData) => {
  429. return Page.removePageByPath(`/user/${username}`)
  430. .then(() => userData);
  431. })
  432. .then((userData) => {
  433. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  434. return res.redirect('/admin/users');
  435. })
  436. .catch((err) => {
  437. req.flash('errorMessage', '削除に失敗しました。');
  438. return res.redirect('/admin/users');
  439. });
  440. };
  441. // これやったときの relation の挙動未確認
  442. actions.user.removeCompletely = function(req, res) {
  443. // ユーザーの物理削除
  444. var id = req.params.id;
  445. User.removeCompletelyById(id, function(err, removed) {
  446. if (err) {
  447. debug('Error while removing user.', err, id);
  448. req.flash('errorMessage', '完全な削除に失敗しました。');
  449. }
  450. else {
  451. req.flash('successMessage', '削除しました');
  452. }
  453. return res.redirect('/admin/users');
  454. });
  455. };
  456. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  457. actions.user.resetPassword = function(req, res) {
  458. const id = req.body.user_id;
  459. const User = crowi.model('User');
  460. User.resetPasswordByRandomString(id)
  461. .then(function(data) {
  462. data.user = User.filterToPublicFields(data.user);
  463. return res.json(ApiResponse.success(data));
  464. }).catch(function(err) {
  465. debug('Error on reseting password', err);
  466. return res.json(ApiResponse.error('Error'));
  467. });
  468. };
  469. actions.externalAccount = {};
  470. actions.externalAccount.index = function(req, res) {
  471. const page = parseInt(req.query.page) || 1;
  472. ExternalAccount.findAllWithPagination({page})
  473. .then((result) => {
  474. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  475. return res.render('admin/external-accounts', {
  476. accounts: result.docs,
  477. pager: pager
  478. });
  479. });
  480. };
  481. actions.externalAccount.remove = function(req, res) {
  482. const accountId = req.params.id;
  483. ExternalAccount.findOneAndRemove({accountId})
  484. .then((result) => {
  485. if (result == null) {
  486. req.flash('errorMessage', '削除に失敗しました。');
  487. return res.redirect('/admin/users/external-accounts');
  488. }
  489. else {
  490. req.flash('successMessage', `外部アカウント '${accountId}' を削除しました`);
  491. return res.redirect('/admin/users/external-accounts');
  492. }
  493. });
  494. };
  495. actions.userGroup = {};
  496. actions.userGroup.index = function(req, res) {
  497. var page = parseInt(req.query.page) || 1;
  498. var renderVar = {
  499. userGroups: [],
  500. userGroupRelations: new Map(),
  501. pager: null,
  502. };
  503. UserGroup.findUserGroupsWithPagination({ page: page })
  504. .then((result) => {
  505. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  506. var userGroups = result.docs;
  507. renderVar.userGroups = userGroups;
  508. renderVar.pager = pager;
  509. return userGroups.map((userGroup) => {
  510. return new Promise((resolve, reject) => {
  511. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  512. .then((relations) => {
  513. return resolve([userGroup, relations]);
  514. });
  515. });
  516. });
  517. })
  518. .then((allRelationsPromise) => {
  519. return Promise.all(allRelationsPromise);
  520. })
  521. .then((relations) => {
  522. renderVar.userGroupRelations = new Map(relations);
  523. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  524. return res.render('admin/user-groups', renderVar);
  525. })
  526. .catch( function(err) {
  527. debug('Error on find all relations', err);
  528. return res.json(ApiResponse.error('Error'));
  529. });
  530. };
  531. // グループ詳細
  532. actions.userGroup.detail = function(req, res) {
  533. var name = req.params.name;
  534. var renderVar = {
  535. userGroup: null,
  536. userGroupRelations: [],
  537. pageGroupRelations: [],
  538. notRelatedusers: []
  539. };
  540. var targetUserGroup = null;
  541. UserGroup.findUserGroupByName(name)
  542. .then(function(userGroup) {
  543. targetUserGroup = userGroup;
  544. if (targetUserGroup == null) {
  545. req.flash('errorMessage', 'グループがありません');
  546. throw new Error('no userGroup is exists. ', name);
  547. }
  548. else {
  549. renderVar.userGroup = targetUserGroup;
  550. return Promise.all([
  551. // get all user and group relations
  552. UserGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  553. // get all page and group relations
  554. PageGroupRelation.findAllRelationForUserGroup(targetUserGroup),
  555. // get all not related users for group
  556. UserGroupRelation.findUserByNotRelatedGroup(targetUserGroup),
  557. ]);
  558. }
  559. })
  560. .then((resolves) => {
  561. renderVar.userGroupRelations = resolves[0];
  562. renderVar.pageGroupRelations = resolves[1];
  563. renderVar.notRelatedusers = resolves[2];
  564. debug('notRelatedusers', renderVar.notRelatedusers);
  565. return res.render('admin/user-group-detail', renderVar);
  566. })
  567. .catch((err) => {
  568. req.flash('errorMessage', 'ユーザグループの検索に失敗しました');
  569. debug('Error on get userGroupDetail', err);
  570. return res.redirect('/admin/user-groups');
  571. });
  572. };
  573. //グループの生成
  574. actions.userGroup.create = function(req, res) {
  575. var form = req.form.createGroupForm;
  576. if (req.form.isValid) {
  577. UserGroup.createGroupByName(form.userGroupName)
  578. .then((newUserGroup) => {
  579. req.flash('successMessage', newUserGroup.name);
  580. req.flash('createdUserGroup', newUserGroup);
  581. return res.redirect('/admin/user-groups');
  582. })
  583. .catch((err) => {
  584. debug('create userGroup error:', err);
  585. req.flash('errorMessage', '同じグループ名が既に存在します。');
  586. });
  587. }
  588. else {
  589. req.flash('errorMessage', req.form.errors.join('\n'));
  590. return res.redirect('/admin/user-groups');
  591. }
  592. };
  593. //
  594. actions.userGroup.update = function(req, res) {
  595. var userGroupId = req.params.userGroupId;
  596. var name = req.body.name;
  597. UserGroup.findById(userGroupId)
  598. .then((userGroupData) => {
  599. if (userGroupData == null) {
  600. req.flash('errorMessage', 'グループの検索に失敗しました。');
  601. return new Promise();
  602. }
  603. else {
  604. // 名前存在チェック
  605. return UserGroup.isRegisterableName(name)
  606. .then((isRegisterableName) => {
  607. // 既に存在するグループ名に更新しようとした場合はエラー
  608. if (!isRegisterableName) {
  609. req.flash('errorMessage', 'グループ名が既に存在します。');
  610. }
  611. else {
  612. return userGroupData.updateName(name)
  613. .then(() => {
  614. req.flash('successMessage', 'グループ名を更新しました。');
  615. })
  616. .catch((err) => {
  617. req.flash('errorMessage', 'グループ名の更新に失敗しました。');
  618. });
  619. }
  620. });
  621. }
  622. })
  623. .then(() => {
  624. return res.redirect('/admin/user-group-detail/' + name);
  625. });
  626. };
  627. actions.userGroup.uploadGroupPicture = function(req, res) {
  628. var fileUploader = require('../util/fileUploader')(crowi, app);
  629. //var storagePlugin = new pluginService('storage');
  630. //var storage = require('../service/storage').StorageService(config);
  631. var userGroupId = req.params.userGroupId;
  632. var tmpFile = req.file || null;
  633. if (!tmpFile) {
  634. return res.json({
  635. 'status': false,
  636. 'message': 'File type error.'
  637. });
  638. }
  639. UserGroup.findById(userGroupId, function(err, userGroupData) {
  640. if (!userGroupData) {
  641. return res.json({
  642. 'status': false,
  643. 'message': 'UserGroup error.'
  644. });
  645. }
  646. var tmpPath = tmpFile.path;
  647. var filePath = UserGroup.createUserGroupPictureFilePath(userGroupData, tmpFile.filename + tmpFile.originalname);
  648. var acceptableFileType = /image\/.+/;
  649. if (!tmpFile.mimetype.match(acceptableFileType)) {
  650. return res.json({
  651. 'status': false,
  652. 'message': 'File type error. Only image files is allowed to set as user picture.',
  653. });
  654. }
  655. var tmpFileStream = fs.createReadStream(tmpPath, { flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  656. fileUploader.uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
  657. .then(function(data) {
  658. var imageUrl = fileUploader.generateUrl(filePath);
  659. userGroupData.updateImage(imageUrl)
  660. .then(() => {
  661. fs.unlink(tmpPath, function(err) {
  662. if (err) {
  663. debug('Error while deleting tmp file.', err);
  664. }
  665. return res.json({
  666. 'status': true,
  667. 'url': imageUrl,
  668. 'message': '',
  669. });
  670. });
  671. });
  672. }).catch(function(err) {
  673. debug('Uploading error', err);
  674. return res.json({
  675. 'status': false,
  676. 'message': 'Error while uploading to ',
  677. });
  678. });
  679. });
  680. };
  681. actions.userGroup.deletePicture = function(req, res) {
  682. var userGroupId = req.params.userGroupId;
  683. let userGroupName = null;
  684. UserGroup.findById(userGroupId)
  685. .then((userGroupData) => {
  686. if (userGroupData == null) {
  687. return Promise.reject();
  688. }
  689. else {
  690. userGroupName = userGroupData.name;
  691. return userGroupData.deleteImage();
  692. }
  693. })
  694. .then((updated) => {
  695. req.flash('successMessage', 'Deleted group picture');
  696. return res.redirect('/admin/user-group-detail/' + userGroupName);
  697. })
  698. .catch((err) => {
  699. debug('An error occured.', err);
  700. req.flash('errorMessage', 'Error while deleting group picture');
  701. if (userGroupName == null) {
  702. return res.redirect('/admin/user-groups/');
  703. }
  704. else {
  705. return res.redirect('/admin/user-group-detail/' + userGroupName);
  706. }
  707. });
  708. };
  709. // app.post('/_api/admin/user-group/delete' , admin.userGroup.removeCompletely);
  710. actions.userGroup.removeCompletely = function(req, res) {
  711. const id = req.body.user_group_id;
  712. const fileUploader = require('../util/fileUploader')(crowi, app);
  713. UserGroup.removeCompletelyById(id)
  714. //// TODO remove attachments
  715. // couldn't remove because filePath includes '/uploads/uploads'
  716. // Error: ENOENT: no such file or directory, unlink 'C:\dev\growi\public\uploads\uploads\userGroup\5b1df18ab69611651cc71495.png
  717. //
  718. // .then(removed => {
  719. // if (removed.image != null) {
  720. // fileUploader.deleteFile(null, removed.image);
  721. // }
  722. // })
  723. .then(() => {
  724. req.flash('successMessage', '削除しました');
  725. return res.redirect('/admin/user-groups');
  726. })
  727. .catch((err) => {
  728. debug('Error while removing userGroup.', err, id);
  729. req.flash('errorMessage', '完全な削除に失敗しました。');
  730. return res.redirect('/admin/user-groups');
  731. });
  732. };
  733. actions.userGroupRelation = {};
  734. actions.userGroupRelation.index = function(req, res) {
  735. };
  736. actions.userGroupRelation.create = function(req, res) {
  737. const User = crowi.model('User');
  738. const UserGroup = crowi.model('UserGroup');
  739. const UserGroupRelation = crowi.model('UserGroupRelation');
  740. // req params
  741. const userName = req.body.user_name;
  742. const userGroupId = req.body.user_group_id;
  743. let user = null;
  744. let userGroup = null;
  745. Promise.all([
  746. // ユーザグループをIDで検索
  747. UserGroup.findById(userGroupId),
  748. // ユーザを名前で検索
  749. User.findUserByUsername(userName),
  750. ])
  751. .then((resolves) => {
  752. userGroup = resolves[0];
  753. user = resolves[1];
  754. // Relation を作成
  755. UserGroupRelation.createRelation(userGroup, user);
  756. })
  757. .then((result) => {
  758. return res.redirect('/admin/user-group-detail/' + userGroup.name);
  759. }).catch((err) => {
  760. debug('Error on create user-group relation', err);
  761. req.flash('errorMessage', 'Error on create user-group relation');
  762. return res.redirect('/admin/user-group-detail/' + userGroup.name);
  763. });
  764. };
  765. actions.userGroupRelation.remove = function(req, res) {
  766. const UserGroupRelation = crowi.model('UserGroupRelation');
  767. var name = req.params.name;
  768. var relationId = req.params.relationId;
  769. debug(name, relationId);
  770. UserGroupRelation.removeById(relationId)
  771. .then(() =>{
  772. return res.redirect('/admin/user-group-detail/' + name);
  773. })
  774. .catch((err) => {
  775. debug('Error on remove user-group-relation', err);
  776. req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
  777. });
  778. };
  779. actions.api = {};
  780. actions.api.appSetting = function(req, res) {
  781. var form = req.form.settingForm;
  782. if (req.form.isValid) {
  783. debug('form content', form);
  784. // mail setting ならここで validation
  785. if (form['mail:from']) {
  786. validateMailSetting(req, form, function(err, data) {
  787. debug('Error validate mail setting: ', err, data);
  788. if (err) {
  789. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  790. return res.json({status: false, message: req.form.errors.join('\n')});
  791. }
  792. return saveSetting(req, res, form);
  793. });
  794. }
  795. else {
  796. return saveSetting(req, res, form);
  797. }
  798. }
  799. else {
  800. return res.json({status: false, message: req.form.errors.join('\n')});
  801. }
  802. };
  803. actions.api.securitySetting = function(req, res) {
  804. const form = req.form.settingForm;
  805. if (req.form.isValid) {
  806. debug('form content', form);
  807. return saveSetting(req, res, form);
  808. }
  809. else {
  810. return res.json({status: false, message: req.form.errors.join('\n')});
  811. }
  812. };
  813. actions.api.securityPassportLdapSetting = function(req, res) {
  814. var form = req.form.settingForm;
  815. if (!req.form.isValid) {
  816. return res.json({status: false, message: req.form.errors.join('\n')});
  817. }
  818. debug('form content', form);
  819. return saveSettingAsync(form)
  820. .then(() => {
  821. const config = crowi.getConfig();
  822. // reset strategy
  823. crowi.passportService.resetLdapStrategy();
  824. // setup strategy
  825. if (Config.isEnabledPassportLdap(config)) {
  826. crowi.passportService.setupLdapStrategy(true);
  827. }
  828. return;
  829. })
  830. .then(() => {
  831. res.json({status: true});
  832. });
  833. };
  834. actions.api.securityPassportGoogleSetting = async(req, res) => {
  835. const form = req.form.settingForm;
  836. if (!req.form.isValid) {
  837. return res.json({status: false, message: req.form.errors.join('\n')});
  838. }
  839. debug('form content', form);
  840. await saveSettingAsync(form);
  841. const config = await crowi.getConfig();
  842. // reset strategy
  843. await crowi.passportService.resetGoogleStrategy();
  844. // setup strategy
  845. if (Config.isEnabledPassportGoogle(config)) {
  846. try {
  847. await crowi.passportService.setupGoogleStrategy(true);
  848. }
  849. catch (err) {
  850. // reset
  851. await crowi.passportService.resetGoogleStrategy();
  852. return res.json({status: false, message: err.message});
  853. }
  854. }
  855. return res.json({status: true});
  856. };
  857. actions.api.securityPassportGitHubSetting = async(req, res) => {
  858. const form = req.form.settingForm;
  859. if (!req.form.isValid) {
  860. return res.json({status: false, message: req.form.errors.join('\n')});
  861. }
  862. debug('form content', form);
  863. await saveSettingAsync(form);
  864. const config = await crowi.getConfig();
  865. // reset strategy
  866. await crowi.passportService.resetGitHubStrategy();
  867. // setup strategy
  868. if (Config.isEnabledPassportGoogle(config)) {
  869. try {
  870. await crowi.passportService.setupGitHubStrategy(true);
  871. }
  872. catch (err) {
  873. // reset
  874. await crowi.passportService.resetGoogleStrategy();
  875. return res.json({status: false, message: err.message});
  876. }
  877. }
  878. return res.json({status: true});
  879. };
  880. actions.api.customizeSetting = function(req, res) {
  881. const form = req.form.settingForm;
  882. if (req.form.isValid) {
  883. debug('form content', form);
  884. return saveSetting(req, res, form);
  885. }
  886. else {
  887. return res.json({status: false, message: req.form.errors.join('\n')});
  888. }
  889. };
  890. actions.api.customizeSetting = function(req, res) {
  891. const form = req.form.settingForm;
  892. if (req.form.isValid) {
  893. debug('form content', form);
  894. return saveSetting(req, res, form);
  895. }
  896. else {
  897. return res.json({status: false, message: req.form.errors.join('\n')});
  898. }
  899. };
  900. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  901. actions.api.notificationAdd = function(req, res) {
  902. var UpdatePost = crowi.model('UpdatePost');
  903. var pathPattern = req.body.pathPattern;
  904. var channel = req.body.channel;
  905. debug('notification.add', pathPattern, channel);
  906. UpdatePost.create(pathPattern, channel, req.user)
  907. .then(function(doc) {
  908. debug('Successfully save updatePost', doc);
  909. // fixme: うーん
  910. doc.creator = doc.creator._id.toString();
  911. return res.json(ApiResponse.success({updatePost: doc}));
  912. }).catch(function(err) {
  913. debug('Failed to save updatePost', err);
  914. return res.json(ApiResponse.error());
  915. });
  916. };
  917. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  918. actions.api.notificationRemove = function(req, res) {
  919. var UpdatePost = crowi.model('UpdatePost');
  920. var id = req.body.id;
  921. UpdatePost.remove(id)
  922. .then(function() {
  923. debug('Successfully remove updatePost');
  924. return res.json(ApiResponse.success({}));
  925. }).catch(function(err) {
  926. debug('Failed to remove updatePost', err);
  927. return res.json(ApiResponse.error());
  928. });
  929. };
  930. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  931. actions.api.usersSearch = function(req, res) {
  932. const User = crowi.model('User');
  933. const email =req.query.email;
  934. User.findUsersByPartOfEmail(email, {})
  935. .then(users => {
  936. const result = {
  937. data: users
  938. };
  939. return res.json(ApiResponse.success(result));
  940. }).catch(err => {
  941. return res.json(ApiResponse.error());
  942. });
  943. };
  944. /**
  945. * save settings, update config cache, and response json
  946. *
  947. * @param {any} req
  948. * @param {any} res
  949. * @param {any} form
  950. */
  951. function saveSetting(req, res, form) {
  952. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  953. Config.updateConfigCache('crowi', config);
  954. return res.json({status: true});
  955. });
  956. }
  957. /**
  958. * save settings, update config cache ONLY. (this method don't response json)
  959. *
  960. * @param {any} form
  961. * @returns
  962. */
  963. function saveSettingAsync(form) {
  964. return new Promise((resolve, reject) => {
  965. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  966. if (err) {
  967. return reject(err);
  968. }
  969. Config.updateConfigCache('crowi', config);
  970. return resolve();
  971. });
  972. });
  973. }
  974. function validateMailSetting(req, form, callback) {
  975. var mailer = crowi.mailer;
  976. var option = {
  977. host: form['mail:smtpHost'],
  978. port: form['mail:smtpPort'],
  979. };
  980. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  981. option.auth = {
  982. user: form['mail:smtpUser'],
  983. pass: form['mail:smtpPassword'],
  984. };
  985. }
  986. if (option.port === 465) {
  987. option.secure = true;
  988. }
  989. var smtpClient = mailer.createSMTPClient(option);
  990. debug('mailer setup for validate SMTP setting', smtpClient);
  991. smtpClient.sendMail({
  992. to: req.user.email,
  993. subject: 'Wiki管理設定のアップデートによるメール通知',
  994. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  995. }, callback);
  996. }
  997. return actions;
  998. };