admin.js 35 KB

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