users.js 22 KB

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