admin.js 35 KB

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