admin.js 34 KB

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