admin.js 35 KB

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