users.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. const loggerFactory = require('@alias/logger');
  2. const logger = loggerFactory('growi:routes:apiv3:user-group');
  3. const express = require('express');
  4. const router = express.Router();
  5. const { body, query } = require('express-validator');
  6. const { isEmail } = require('validator');
  7. const ErrorV3 = require('../../models/vo/error-apiv3');
  8. const PAGE_ITEMS = 50;
  9. const validator = {};
  10. /**
  11. * @swagger
  12. * tags:
  13. * name: Users
  14. */
  15. /**
  16. * @swagger
  17. *
  18. * components:
  19. * schemas:
  20. * User:
  21. * description: User
  22. * type: object
  23. * properties:
  24. * _id:
  25. * type: string
  26. * description: user ID
  27. * example: 5ae5fccfc5577b0004dbd8ab
  28. * lang:
  29. * type: string
  30. * description: language
  31. * example: 'en_US'
  32. * status:
  33. * type: integer
  34. * description: status
  35. * example: 0
  36. * admin:
  37. * type: boolean
  38. * description: whether the admin
  39. * example: false
  40. * email:
  41. * type: string
  42. * description: E-Mail address
  43. * example: alice@aaa.aaa
  44. * username:
  45. * type: string
  46. * description: username
  47. * example: alice
  48. * name:
  49. * type: string
  50. * description: full name
  51. * example: Alice
  52. * createdAt:
  53. * type: string
  54. * description: date created at
  55. * example: 2010-01-01T00:00:00.000Z
  56. */
  57. module.exports = (crowi) => {
  58. const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
  59. const loginRequired = require('../../middlewares/login-required')(crowi, true);
  60. const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
  61. const adminRequired = require('../../middlewares/admin-required')(crowi);
  62. const csrf = require('../../middlewares/csrf')(crowi);
  63. const apiV3FormValidator = require('../../middlewares/apiv3-form-validator')(crowi);
  64. const {
  65. User,
  66. Page,
  67. ExternalAccount,
  68. UserGroupRelation,
  69. } = crowi.models;
  70. const statusNo = {
  71. registered: User.STATUS_REGISTERED,
  72. active: User.STATUS_ACTIVE,
  73. suspended: User.STATUS_SUSPENDED,
  74. invited: User.STATUS_INVITED,
  75. };
  76. validator.statusList = [
  77. // validate status list status array match to statusNo
  78. query('selectedStatusList').custom((value) => {
  79. const error = [];
  80. value.forEach((status) => {
  81. if (!Object.keys(statusNo)) {
  82. error.push(status);
  83. }
  84. });
  85. return (error.length === 0);
  86. }),
  87. // validate sortOrder : asc or desc
  88. query('sortOrder').isIn(['asc', 'desc']),
  89. // validate sort : what column you will sort
  90. query('sort').isIn(['id', 'status', 'username', 'name', 'email', 'createdAt', 'lastLoginAt']),
  91. query('page').isInt({ min: 1 }),
  92. query('forceIncludeAttributes').toArray().custom((value, { req }) => {
  93. // only the admin user can specify forceIncludeAttributes
  94. if (value.length === 0) {
  95. return true;
  96. }
  97. return req.user.admin;
  98. }),
  99. ];
  100. validator.recentCreatedByUser = [
  101. query('limit').if(value => value != null).isInt({ max: 300 }).withMessage('You should set less than 300 or not to set limit.'),
  102. ];
  103. /**
  104. * @swagger
  105. *
  106. * paths:
  107. * /users:
  108. * get:
  109. * tags: [Users]
  110. * operationId: listUsers
  111. * summary: /users
  112. * description: Select selected columns from users order by asc or desc
  113. * parameters:
  114. * - name: page
  115. * in: query
  116. * description: page number
  117. * schema:
  118. * type: number
  119. * - name: selectedStatusList
  120. * in: query
  121. * description: status list
  122. * schema:
  123. * type: string
  124. * - name: searchText
  125. * in: query
  126. * description: For incremental search value from input box
  127. * schema:
  128. * type: string
  129. * - name: sortOrder
  130. * in: query
  131. * description: asc or desc
  132. * schema:
  133. * type: string
  134. * - name: sort
  135. * in: query
  136. * description: sorting column
  137. * schema:
  138. * type: string
  139. * responses:
  140. * 200:
  141. * description: users are fetched
  142. * content:
  143. * application/json:
  144. * schema:
  145. * properties:
  146. * paginateResult:
  147. * $ref: '#/components/schemas/PaginateResult'
  148. */
  149. router.get('/', loginRequiredStrictly, validator.statusList, apiV3FormValidator, async(req, res) => {
  150. const page = parseInt(req.query.page) || 1;
  151. // status
  152. const { selectedStatusList, forceIncludeAttributes } = req.query;
  153. const statusNoList = (selectedStatusList.includes('all')) ? Object.values(statusNo) : selectedStatusList.map(element => statusNo[element]);
  154. // Search from input
  155. const searchText = req.query.searchText || '';
  156. const searchWord = new RegExp(`${searchText}`);
  157. // Sort
  158. const { sort, sortOrder } = req.query;
  159. const sortOutput = {
  160. [sort]: (sortOrder === 'desc') ? -1 : 1,
  161. };
  162. try {
  163. const paginateResult = await User.paginate(
  164. {
  165. $and: [
  166. { status: { $in: statusNoList } },
  167. {
  168. $or: [
  169. { name: { $in: searchWord } },
  170. { username: { $in: searchWord } },
  171. { email: { $in: searchWord } },
  172. ],
  173. },
  174. ],
  175. },
  176. {
  177. sort: sortOutput,
  178. page,
  179. limit: PAGE_ITEMS,
  180. },
  181. );
  182. paginateResult.docs = paginateResult.docs.map((doc) => {
  183. // return email only when specified by query
  184. const { email } = doc;
  185. const user = doc.toObject();
  186. if (forceIncludeAttributes.includes('email')) {
  187. user.email = email;
  188. }
  189. return user;
  190. });
  191. return res.apiv3({ paginateResult });
  192. }
  193. catch (err) {
  194. const msg = 'Error occurred in fetching user group list';
  195. logger.error('Error', err);
  196. return res.apiv3Err(new ErrorV3(msg, 'user-group-list-fetch-failed'), 500);
  197. }
  198. });
  199. /**
  200. * @swagger
  201. *
  202. * paths:
  203. * /{id}/recent:
  204. * get:
  205. * tags: [Users]
  206. * operationId: recent created page of user id
  207. * summary: /usersIdReacent
  208. * parameters:
  209. * - name: id
  210. * in: path
  211. * required: true
  212. * description: id of user
  213. * schema:
  214. * type: string
  215. * responses:
  216. * 200:
  217. * description: users recent created pages are fetched
  218. * content:
  219. * application/json:
  220. * schema:
  221. * properties:
  222. * paginateResult:
  223. * $ref: '#/components/schemas/PaginateResult'
  224. */
  225. router.get('/:id/recent', accessTokenParser, loginRequired, validator.recentCreatedByUser, apiV3FormValidator, async(req, res) => {
  226. const { id } = req.params;
  227. let user;
  228. try {
  229. user = await User.findById(id);
  230. }
  231. catch (err) {
  232. const msg = 'Error occurred in find user';
  233. logger.error('Error', err);
  234. return res.apiv3Err(new ErrorV3(msg, 'retrieve-recent-created-pages-failed'), 500);
  235. }
  236. if (user == null) {
  237. return res.apiv3Err(new ErrorV3('find-user-is-not-found'));
  238. }
  239. const limit = parseInt(req.query.limit) || await crowi.configManager.getConfig('crowi', 'customize:showPageLimitationM') || 30;
  240. const page = req.query.page;
  241. const offset = (page - 1) * limit;
  242. const queryOptions = { offset, limit };
  243. try {
  244. const result = await Page.findListByCreator(user, req.user, queryOptions);
  245. // Delete unnecessary data about users
  246. result.pages = result.pages.map((page) => {
  247. const user = page.lastUpdateUser.toObject();
  248. page.lastUpdateUser = user;
  249. return page;
  250. });
  251. return res.apiv3(result);
  252. }
  253. catch (err) {
  254. const msg = 'Error occurred in retrieve recent created pages for user';
  255. logger.error('Error', err);
  256. return res.apiv3Err(new ErrorV3(msg, 'retrieve-recent-created-pages-failed'), 500);
  257. }
  258. });
  259. validator.inviteEmail = [
  260. // isEmail prevents line breaks, so use isString
  261. body('shapedEmailList').custom((value) => {
  262. const array = value.filter((value) => { return isEmail(value) });
  263. if (array.length === 0) {
  264. throw new Error('At least one valid email address is required');
  265. }
  266. return array;
  267. }),
  268. ];
  269. /**
  270. * @swagger
  271. *
  272. * paths:
  273. * /users/invite:
  274. * post:
  275. * tags: [Users]
  276. * operationId: inviteUser
  277. * summary: /users/invite
  278. * description: Create new users and send Emails
  279. * parameters:
  280. * - name: shapedEmailList
  281. * in: query
  282. * description: Invitation emailList
  283. * schema:
  284. * type: object
  285. * - name: sendEmail
  286. * in: query
  287. * description: Whether to send mail
  288. * schema:
  289. * type: boolean
  290. * responses:
  291. * 200:
  292. * description: Inviting user success
  293. * content:
  294. * application/json:
  295. * schema:
  296. * properties:
  297. * createdUserList:
  298. * type: object
  299. * description: Users successfully created
  300. * existingEmailList:
  301. * type: object
  302. * description: Users email that already exists
  303. */
  304. router.post('/invite', loginRequiredStrictly, adminRequired, csrf, validator.inviteEmail, apiV3FormValidator, async(req, res) => {
  305. try {
  306. const invitedUserList = await User.createUsersByInvitation(req.body.shapedEmailList, req.body.sendEmail);
  307. return res.apiv3({ invitedUserList });
  308. }
  309. catch (err) {
  310. logger.error('Error', err);
  311. return res.apiv3Err(new ErrorV3(err));
  312. }
  313. });
  314. /**
  315. * @swagger
  316. *
  317. * paths:
  318. * /users/{id}/giveAdmin:
  319. * put:
  320. * tags: [Users]
  321. * operationId: giveAdminUser
  322. * summary: /users/{id}/giveAdmin
  323. * description: Give user admin
  324. * parameters:
  325. * - name: id
  326. * in: path
  327. * required: true
  328. * description: id of user for admin
  329. * schema:
  330. * type: string
  331. * responses:
  332. * 200:
  333. * description: Give user admin success
  334. * content:
  335. * application/json:
  336. * schema:
  337. * properties:
  338. * userData:
  339. * type: object
  340. * description: data of admin user
  341. */
  342. router.put('/:id/giveAdmin', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  343. const { id } = req.params;
  344. try {
  345. const userData = await User.findById(id);
  346. await userData.makeAdmin();
  347. return res.apiv3({ userData });
  348. }
  349. catch (err) {
  350. logger.error('Error', err);
  351. return res.apiv3Err(new ErrorV3(err));
  352. }
  353. });
  354. /**
  355. * @swagger
  356. *
  357. * paths:
  358. * /users/{id}/removeAdmin:
  359. * put:
  360. * tags: [Users]
  361. * operationId: removeAdminUser
  362. * summary: /users/{id}/removeAdmin
  363. * description: Remove user admin
  364. * parameters:
  365. * - name: id
  366. * in: path
  367. * required: true
  368. * description: id of user for removing admin
  369. * schema:
  370. * type: string
  371. * responses:
  372. * 200:
  373. * description: Remove user admin success
  374. * content:
  375. * application/json:
  376. * schema:
  377. * properties:
  378. * userData:
  379. * type: object
  380. * description: data of removed admin user
  381. */
  382. router.put('/:id/removeAdmin', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  383. const { id } = req.params;
  384. try {
  385. const userData = await User.findById(id);
  386. await userData.removeFromAdmin();
  387. return res.apiv3({ userData });
  388. }
  389. catch (err) {
  390. logger.error('Error', err);
  391. return res.apiv3Err(new ErrorV3(err));
  392. }
  393. });
  394. /**
  395. * @swagger
  396. *
  397. * paths:
  398. * /users/{id}/activate:
  399. * put:
  400. * tags: [Users]
  401. * operationId: activateUser
  402. * summary: /users/{id}/activate
  403. * description: Activate user
  404. * parameters:
  405. * - name: id
  406. * in: path
  407. * required: true
  408. * description: id of activate user
  409. * schema:
  410. * type: string
  411. * responses:
  412. * 200:
  413. * description: Activationg user success
  414. * content:
  415. * application/json:
  416. * schema:
  417. * properties:
  418. * userData:
  419. * type: object
  420. * description: data of activate user
  421. */
  422. router.put('/:id/activate', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  423. // check user upper limit
  424. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  425. if (isUserCountExceedsUpperLimit) {
  426. const msg = 'Unable to activate because user has reached limit';
  427. logger.error('Error', msg);
  428. return res.apiv3Err(new ErrorV3(msg));
  429. }
  430. const { id } = req.params;
  431. try {
  432. const userData = await User.findById(id);
  433. await userData.statusActivate();
  434. return res.apiv3({ userData });
  435. }
  436. catch (err) {
  437. logger.error('Error', err);
  438. return res.apiv3Err(new ErrorV3(err));
  439. }
  440. });
  441. /**
  442. * @swagger
  443. *
  444. * paths:
  445. * /users/{id}/deactivate:
  446. * put:
  447. * tags: [Users]
  448. * operationId: deactivateUser
  449. * summary: /users/{id}/deactivate
  450. * description: Deactivate user
  451. * parameters:
  452. * - name: id
  453. * in: path
  454. * required: true
  455. * description: id of deactivate user
  456. * schema:
  457. * type: string
  458. * responses:
  459. * 200:
  460. * description: Deactivationg user success
  461. * content:
  462. * application/json:
  463. * schema:
  464. * properties:
  465. * userData:
  466. * type: object
  467. * description: data of deactivate user
  468. */
  469. router.put('/:id/deactivate', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  470. const { id } = req.params;
  471. try {
  472. const userData = await User.findById(id);
  473. await userData.statusSuspend();
  474. return res.apiv3({ userData });
  475. }
  476. catch (err) {
  477. logger.error('Error', err);
  478. return res.apiv3Err(new ErrorV3(err));
  479. }
  480. });
  481. /**
  482. * @swagger
  483. *
  484. * paths:
  485. * /users/{id}/remove:
  486. * delete:
  487. * tags: [Users]
  488. * operationId: removeUser
  489. * summary: /users/{id}/remove
  490. * description: Delete user
  491. * parameters:
  492. * - name: id
  493. * in: path
  494. * required: true
  495. * description: id of delete user
  496. * schema:
  497. * type: string
  498. * responses:
  499. * 200:
  500. * description: Deleting user success
  501. * content:
  502. * application/json:
  503. * schema:
  504. * properties:
  505. * userData:
  506. * type: object
  507. * description: data of delete user
  508. */
  509. router.delete('/:id/remove', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  510. const { id } = req.params;
  511. try {
  512. const userData = await User.findById(id);
  513. await UserGroupRelation.remove({ relatedUser: userData });
  514. await userData.statusDelete();
  515. await ExternalAccount.remove({ user: userData });
  516. await Page.removeByPath(`/user/${userData.username}`);
  517. return res.apiv3({ userData });
  518. }
  519. catch (err) {
  520. logger.error('Error', err);
  521. return res.apiv3Err(new ErrorV3(err));
  522. }
  523. });
  524. /**
  525. * @swagger
  526. *
  527. * paths:
  528. * /users/external-accounts:
  529. * get:
  530. * tags: [Users]
  531. * operationId: listExternalAccountsUsers
  532. * summary: /users/external-accounts
  533. * description: Get external-account
  534. * responses:
  535. * 200:
  536. * description: external-account are fetched
  537. * content:
  538. * application/json:
  539. * schema:
  540. * properties:
  541. * paginateResult:
  542. * $ref: '#/components/schemas/PaginateResult'
  543. */
  544. router.get('/external-accounts/', loginRequiredStrictly, adminRequired, async(req, res) => {
  545. const page = parseInt(req.query.page) || 1;
  546. try {
  547. const paginateResult = await ExternalAccount.findAllWithPagination({ page });
  548. return res.apiv3({ paginateResult });
  549. }
  550. catch (err) {
  551. const msg = 'Error occurred in fetching external-account list ';
  552. logger.error(msg, err);
  553. return res.apiv3Err(new ErrorV3(msg + err.message, 'external-account-list-fetch-failed'), 500);
  554. }
  555. });
  556. /**
  557. * @swagger
  558. *
  559. * paths:
  560. * /users/external-accounts/{id}/remove:
  561. * delete:
  562. * tags: [Users]
  563. * operationId: removeExternalAccountUser
  564. * summary: /users/external-accounts/{id}/remove
  565. * description: Delete ExternalAccount
  566. * parameters:
  567. * - name: id
  568. * in: path
  569. * required: true
  570. * description: id of ExternalAccount
  571. * schema:
  572. * type: string
  573. * responses:
  574. * 200:
  575. * description: External Account is removed
  576. * content:
  577. * application/json:
  578. * schema:
  579. * properties:
  580. * externalAccount:
  581. * type: object
  582. * description: A result of `ExtenralAccount.findByIdAndRemove`
  583. */
  584. router.delete('/external-accounts/:id/remove', loginRequiredStrictly, adminRequired, apiV3FormValidator, async(req, res) => {
  585. const { id } = req.params;
  586. try {
  587. const externalAccount = await ExternalAccount.findByIdAndRemove(id);
  588. return res.apiv3({ externalAccount });
  589. }
  590. catch (err) {
  591. const msg = 'Error occurred in deleting a external account ';
  592. logger.error(msg, err);
  593. return res.apiv3Err(new ErrorV3(msg + err.message, 'extenral-account-delete-failed'));
  594. }
  595. });
  596. /**
  597. * @swagger
  598. *
  599. * paths:
  600. * /users/update.imageUrlCache:
  601. * put:
  602. * tags: [Users]
  603. * operationId: update.imageUrlCache
  604. * summary: /users/update.imageUrlCache
  605. * description: update imageUrlCache
  606. * parameters:
  607. * - name: userIds
  608. * in: query
  609. * description: user id list
  610. * schema:
  611. * type: string
  612. * responses:
  613. * 200:
  614. * description: success creating imageUrlCached
  615. * content:
  616. * application/json:
  617. * schema:
  618. * properties:
  619. * userData:
  620. * type: object
  621. * description: users updated with imageUrlCached
  622. */
  623. router.put('/update.imageUrlCache', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  624. try {
  625. const userIds = req.body.userIds;
  626. const users = await User.find({ _id: { $in: userIds } });
  627. const requests = await Promise.all(users.map(async(user) => {
  628. return {
  629. updateOne: {
  630. filter: { _id: user._id },
  631. update: { $set: { imageUrlCached: await user.generateImageUrlCached() } },
  632. },
  633. };
  634. }));
  635. if (requests.length > 0) {
  636. await User.bulkWrite(requests);
  637. }
  638. return res.apiv3({});
  639. }
  640. catch (err) {
  641. logger.error('Error', err);
  642. return res.apiv3Err(new ErrorV3(err));
  643. }
  644. });
  645. /**
  646. * @swagger
  647. *
  648. * paths:
  649. * /users/reset-password:
  650. * put:
  651. * tags: [Users]
  652. * operationId: resetPassword
  653. * summary: /users/reset-password
  654. * description: update imageUrlCache
  655. * requestBody:
  656. * content:
  657. * application/json:
  658. * schema:
  659. * properties:
  660. * id:
  661. * type: string
  662. * description: user id for reset password
  663. * responses:
  664. * 200:
  665. * description: success resrt password
  666. * content:
  667. * application/json:
  668. * schema:
  669. * properties:
  670. * newPassword:
  671. * type: string
  672. * user:
  673. * type: object
  674. * description: Target user
  675. */
  676. router.put('/reset-password', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  677. const { id } = req.body;
  678. try {
  679. const [newPassword, user] = await Promise.all([
  680. await User.resetPasswordByRandomString(id),
  681. await User.findById(id)]);
  682. return res.apiv3({ newPassword, user });
  683. }
  684. catch (err) {
  685. logger.error('Error', err);
  686. return res.apiv3Err(new ErrorV3(err));
  687. }
  688. });
  689. return router;
  690. };