2
0

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