users.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. import { ErrorV3 } from '@growi/core/dist/models';
  2. import { userHomepagePath } from '@growi/core/dist/utils/page-path-utils';
  3. import { SupportedAction } from '~/interfaces/activity';
  4. import Activity from '~/server/models/activity';
  5. import { configManager } from '~/server/service/config-manager';
  6. import loggerFactory from '~/utils/logger';
  7. import { generateAddActivityMiddleware } from '../../middlewares/add-activity';
  8. import { apiV3FormValidator } from '../../middlewares/apiv3-form-validator';
  9. const logger = loggerFactory('growi:routes:apiv3:users');
  10. const path = require('path');
  11. const express = require('express');
  12. const router = express.Router();
  13. const { body, query } = require('express-validator');
  14. const { isEmail } = require('validator');
  15. const { serializePageSecurely } = require('../../models/serializers/page-serializer');
  16. const { serializeUserSecurely } = require('../../models/serializers/user-serializer');
  17. const PAGE_ITEMS = 50;
  18. const validator = {};
  19. /**
  20. * @swagger
  21. * tags:
  22. * name: Users
  23. */
  24. /**
  25. * @swagger
  26. *
  27. * components:
  28. * schemas:
  29. * User:
  30. * description: User
  31. * type: object
  32. * properties:
  33. * _id:
  34. * type: string
  35. * description: user ID
  36. * example: 5ae5fccfc5577b0004dbd8ab
  37. * lang:
  38. * type: string
  39. * description: language
  40. * example: 'en_US'
  41. * status:
  42. * type: integer
  43. * description: status
  44. * example: 0
  45. * admin:
  46. * type: boolean
  47. * description: whether the admin
  48. * example: false
  49. * email:
  50. * type: string
  51. * description: E-Mail address
  52. * example: alice@aaa.aaa
  53. * username:
  54. * type: string
  55. * description: username
  56. * example: alice
  57. * name:
  58. * type: string
  59. * description: full name
  60. * example: Alice
  61. * createdAt:
  62. * type: string
  63. * description: date created at
  64. * example: 2010-01-01T00:00:00.000Z
  65. */
  66. module.exports = (crowi) => {
  67. const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
  68. const loginRequired = require('../../middlewares/login-required')(crowi, true);
  69. const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
  70. const adminRequired = require('../../middlewares/admin-required')(crowi);
  71. const addActivity = generateAddActivityMiddleware(crowi);
  72. const activityEvent = crowi.event('activity');
  73. const {
  74. User,
  75. Page,
  76. ExternalAccount,
  77. UserGroupRelation,
  78. } = crowi.models;
  79. const statusNo = {
  80. registered: User.STATUS_REGISTERED,
  81. active: User.STATUS_ACTIVE,
  82. suspended: User.STATUS_SUSPENDED,
  83. invited: User.STATUS_INVITED,
  84. };
  85. validator.statusList = [
  86. query('selectedStatusList').if(value => value != null).custom((value, { req }) => {
  87. const { user } = req;
  88. if (user != null && user.admin) {
  89. return value;
  90. }
  91. throw new Error('the param \'selectedStatusList\' is not allowed to use by the users except administrators');
  92. }),
  93. // validate sortOrder : asc or desc
  94. query('sortOrder').isIn(['asc', 'desc']),
  95. // validate sort : what column you will sort
  96. query('sort').isIn(['id', 'status', 'username', 'name', 'email', 'createdAt', 'lastLoginAt']),
  97. query('page').isInt({ min: 1 }),
  98. query('forceIncludeAttributes').toArray().custom((value, { req }) => {
  99. // only the admin user can specify forceIncludeAttributes
  100. if (value.length === 0) {
  101. return true;
  102. }
  103. return req.user.admin;
  104. }),
  105. ];
  106. validator.recentCreatedByUser = [
  107. query('limit').if(value => value != null).isInt({ max: 300 }).withMessage('You should set less than 300 or not to set limit.'),
  108. ];
  109. validator.usernames = [
  110. query('q').isString().withMessage('q is required'),
  111. query('offset').optional().isInt().withMessage('offset must be a number'),
  112. query('limit').optional().isInt({ max: 20 }).withMessage('You should set less than 20 or not to set limit.'),
  113. query('options').optional().isString().withMessage('options must be string'),
  114. ];
  115. // express middleware
  116. const certifyUserOperationOtherThenYourOwn = (req, res, next) => {
  117. const { id } = req.params;
  118. if (req.user._id.toString() === id) {
  119. const msg = 'This API is not available for your own users';
  120. logger.error(msg);
  121. return res.apiv3Err(new ErrorV3(msg), 400);
  122. }
  123. next();
  124. };
  125. const sendEmailByUserList = async(userList) => {
  126. const { appService, mailService } = crowi;
  127. const appTitle = appService.getAppTitle();
  128. const locale = configManager.getConfig('crowi', 'app:globalLang');
  129. const failedToSendEmailList = [];
  130. for (const user of userList) {
  131. try {
  132. // eslint-disable-next-line no-await-in-loop
  133. await mailService.send({
  134. to: user.email,
  135. subject: `Invitation to ${appTitle}`,
  136. template: path.join(crowi.localeDir, `${locale}/admin/userInvitation.ejs`),
  137. vars: {
  138. email: user.email,
  139. password: user.password,
  140. url: crowi.appService.getSiteUrl(),
  141. appTitle,
  142. },
  143. });
  144. // eslint-disable-next-line no-await-in-loop
  145. await User.updateIsInvitationEmailSended(user.user.id);
  146. }
  147. catch (err) {
  148. logger.error(err);
  149. failedToSendEmailList.push({
  150. email: user.email,
  151. reason: err.message,
  152. });
  153. }
  154. }
  155. return { failedToSendEmailList };
  156. };
  157. const sendEmailByUser = async(user) => {
  158. const { appService, mailService } = crowi;
  159. const appTitle = appService.getAppTitle();
  160. const locale = configManager.getConfig('crowi', 'app:globalLang');
  161. await mailService.send({
  162. to: user.email,
  163. subject: `New password for ${appTitle}`,
  164. template: path.join(crowi.localeDir, `${locale}/admin/userResetPassword.ejs`),
  165. vars: {
  166. email: user.email,
  167. password: user.password,
  168. url: crowi.appService.getSiteUrl(),
  169. appTitle,
  170. },
  171. });
  172. };
  173. /**
  174. * @swagger
  175. *
  176. * paths:
  177. * /users:
  178. * get:
  179. * tags: [Users]
  180. * operationId: listUsers
  181. * summary: /users
  182. * description: Select selected columns from users order by asc or desc
  183. * parameters:
  184. * - name: page
  185. * in: query
  186. * description: page number
  187. * schema:
  188. * type: number
  189. * - name: selectedStatusList
  190. * in: query
  191. * description: status list
  192. * schema:
  193. * type: string
  194. * - name: searchText
  195. * in: query
  196. * description: For incremental search value from input box
  197. * schema:
  198. * type: string
  199. * - name: sortOrder
  200. * in: query
  201. * description: asc or desc
  202. * schema:
  203. * type: string
  204. * - name: sort
  205. * in: query
  206. * description: sorting column
  207. * schema:
  208. * type: string
  209. * responses:
  210. * 200:
  211. * description: users are fetched
  212. * content:
  213. * application/json:
  214. * schema:
  215. * properties:
  216. * paginateResult:
  217. * $ref: '#/components/schemas/PaginateResult'
  218. */
  219. router.get('/', accessTokenParser, loginRequired, validator.statusList, apiV3FormValidator, async(req, res) => {
  220. const page = parseInt(req.query.page) || 1;
  221. // status
  222. const { forceIncludeAttributes } = req.query;
  223. const selectedStatusList = req.query.selectedStatusList || ['active'];
  224. const statusNoList = (selectedStatusList.includes('all')) ? Object.values(statusNo) : selectedStatusList.map(element => statusNo[element]);
  225. // Search from input
  226. const searchText = req.query.searchText || '';
  227. const searchWord = new RegExp(`${searchText}`);
  228. // Sort
  229. const { sort, sortOrder } = req.query;
  230. const sortOutput = {
  231. [sort]: (sortOrder === 'desc') ? -1 : 1,
  232. };
  233. // For more information about the external specification of the User API, see here (https://dev.growi.org/5fd7466a31d89500488248e3)
  234. const orConditions = [
  235. { name: { $in: searchWord } },
  236. { username: { $in: searchWord } },
  237. ];
  238. const query = {
  239. $and: [
  240. { status: { $in: statusNoList } },
  241. {
  242. $or: orConditions,
  243. },
  244. ],
  245. };
  246. try {
  247. if (req.user != null) {
  248. orConditions.push(
  249. {
  250. $and: [
  251. { isEmailPublished: true },
  252. { email: { $in: searchWord } },
  253. ],
  254. },
  255. );
  256. }
  257. if (forceIncludeAttributes.includes('email')) {
  258. orConditions.push({ email: { $in: searchWord } });
  259. }
  260. const paginateResult = await User.paginate(
  261. query,
  262. {
  263. sort: sortOutput,
  264. page,
  265. limit: PAGE_ITEMS,
  266. },
  267. );
  268. paginateResult.docs = paginateResult.docs.map((doc) => {
  269. // return email only when specified by query
  270. const { email } = doc;
  271. const user = serializeUserSecurely(doc);
  272. if (forceIncludeAttributes.includes('email')) {
  273. user.email = email;
  274. }
  275. return user;
  276. });
  277. return res.apiv3({ paginateResult });
  278. }
  279. catch (err) {
  280. const msg = 'Error occurred in fetching user group list';
  281. logger.error('Error', err);
  282. return res.apiv3Err(new ErrorV3(msg, 'user-group-list-fetch-failed'), 500);
  283. }
  284. });
  285. /**
  286. * @swagger
  287. *
  288. * paths:
  289. * /{id}/recent:
  290. * get:
  291. * tags: [Users]
  292. * operationId: recent created page of user id
  293. * summary: /usersIdReacent
  294. * parameters:
  295. * - name: id
  296. * in: path
  297. * required: true
  298. * description: id of user
  299. * schema:
  300. * type: string
  301. * responses:
  302. * 200:
  303. * description: users recent created pages are fetched
  304. * content:
  305. * application/json:
  306. * schema:
  307. * properties:
  308. * paginateResult:
  309. * $ref: '#/components/schemas/PaginateResult'
  310. */
  311. router.get('/:id/recent', accessTokenParser, loginRequired, validator.recentCreatedByUser, apiV3FormValidator, async(req, res) => {
  312. const { id } = req.params;
  313. let user;
  314. try {
  315. user = await User.findById(id);
  316. }
  317. catch (err) {
  318. const msg = 'Error occurred in find user';
  319. logger.error('Error', err);
  320. return res.apiv3Err(new ErrorV3(msg, 'retrieve-recent-created-pages-failed'), 500);
  321. }
  322. if (user == null) {
  323. return res.apiv3Err(new ErrorV3('find-user-is-not-found'));
  324. }
  325. const limit = parseInt(req.query.limit) || await configManager.getConfig('crowi', 'customize:showPageLimitationM') || 30;
  326. const page = req.query.page;
  327. const offset = (page - 1) * limit;
  328. const queryOptions = { offset, limit };
  329. try {
  330. const result = await Page.findListByCreator(user, req.user, queryOptions);
  331. result.pages = result.pages.map(page => serializePageSecurely(page));
  332. return res.apiv3(result);
  333. }
  334. catch (err) {
  335. const msg = 'Error occurred in retrieve recent created pages for user';
  336. logger.error('Error', err);
  337. return res.apiv3Err(new ErrorV3(msg, 'retrieve-recent-created-pages-failed'), 500);
  338. }
  339. });
  340. validator.inviteEmail = [
  341. // isEmail prevents line breaks, so use isString
  342. body('shapedEmailList').custom((value) => {
  343. const array = value.filter((value) => { return isEmail(value) });
  344. if (array.length === 0) {
  345. throw new Error('At least one valid email address is required');
  346. }
  347. return array;
  348. }),
  349. ];
  350. /**
  351. * @swagger
  352. *
  353. * paths:
  354. * /users/invite:
  355. * post:
  356. * tags: [Users]
  357. * operationId: inviteUser
  358. * summary: /users/invite
  359. * description: Create new users and send Emails
  360. * parameters:
  361. * - name: shapedEmailList
  362. * in: query
  363. * description: Invitation emailList
  364. * schema:
  365. * type: object
  366. * - name: sendEmail
  367. * in: query
  368. * description: Whether to send mail
  369. * schema:
  370. * type: boolean
  371. * responses:
  372. * 200:
  373. * description: Inviting user success
  374. * content:
  375. * application/json:
  376. * schema:
  377. * properties:
  378. * createdUserList:
  379. * type: object
  380. * description: Users successfully created
  381. * existingEmailList:
  382. * type: object
  383. * description: Users email that already exists
  384. * failedEmailList:
  385. * type: object
  386. * description: Users email that failed to create or send email
  387. */
  388. router.post('/invite', loginRequiredStrictly, adminRequired, addActivity, validator.inviteEmail, apiV3FormValidator, async(req, res) => {
  389. // Delete duplicate email addresses
  390. const emailList = Array.from(new Set(req.body.shapedEmailList));
  391. let failedEmailList = [];
  392. // Create users
  393. const createUser = await User.createUsersByEmailList(emailList);
  394. if (createUser.failedToCreateUserEmailList.length > 0) {
  395. failedEmailList = failedEmailList.concat(createUser.failedToCreateUserEmailList);
  396. }
  397. // Send email
  398. if (req.body.sendEmail) {
  399. const sendEmail = await sendEmailByUserList(createUser.createdUserList);
  400. if (sendEmail.failedToSendEmailList.length > 0) {
  401. failedEmailList = failedEmailList.concat(sendEmail.failedToSendEmailList);
  402. }
  403. }
  404. const parameters = { action: SupportedAction.ACTION_ADMIN_USERS_INVITE };
  405. activityEvent.emit('update', res.locals.activity._id, parameters);
  406. return res.apiv3({
  407. createdUserList: createUser.createdUserList,
  408. existingEmailList: createUser.existingEmailList,
  409. failedEmailList,
  410. }, 201);
  411. });
  412. /**
  413. * @swagger
  414. *
  415. * paths:
  416. * /users/{id}/grant-admin:
  417. * put:
  418. * tags: [Users]
  419. * operationId: grantAdminUser
  420. * summary: /users/{id}/grant-admin
  421. * description: Grant user admin
  422. * parameters:
  423. * - name: id
  424. * in: path
  425. * required: true
  426. * description: id of user for admin
  427. * schema:
  428. * type: string
  429. * responses:
  430. * 200:
  431. * description: Grant user admin success
  432. * content:
  433. * application/json:
  434. * schema:
  435. * properties:
  436. * userData:
  437. * type: object
  438. * description: data of admin user
  439. */
  440. router.put('/:id/grant-admin', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
  441. const { id } = req.params;
  442. try {
  443. const userData = await User.findById(id);
  444. await userData.grantAdmin();
  445. const serializedUserData = serializeUserSecurely(userData);
  446. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_GRANT_ADMIN });
  447. return res.apiv3({ userData: serializedUserData });
  448. }
  449. catch (err) {
  450. logger.error('Error', err);
  451. return res.apiv3Err(new ErrorV3(err));
  452. }
  453. });
  454. /**
  455. * @swagger
  456. *
  457. * paths:
  458. * /users/{id}/revoke-admin:
  459. * put:
  460. * tags: [Users]
  461. * operationId: revokeAdminUser
  462. * summary: /users/{id}/revoke-admin
  463. * description: Revoke user admin
  464. * parameters:
  465. * - name: id
  466. * in: path
  467. * required: true
  468. * description: id of user for revoking admin
  469. * schema:
  470. * type: string
  471. * responses:
  472. * 200:
  473. * description: Revoke user admin success
  474. * content:
  475. * application/json:
  476. * schema:
  477. * properties:
  478. * userData:
  479. * type: object
  480. * description: data of revoked admin user
  481. */
  482. router.put('/:id/revoke-admin', loginRequiredStrictly, adminRequired, certifyUserOperationOtherThenYourOwn, addActivity, async(req, res) => {
  483. const { id } = req.params;
  484. try {
  485. const userData = await User.findById(id);
  486. await userData.revokeAdmin();
  487. const serializedUserData = serializeUserSecurely(userData);
  488. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_REVOKE_ADMIN });
  489. return res.apiv3({ userData: serializedUserData });
  490. }
  491. catch (err) {
  492. logger.error('Error', err);
  493. return res.apiv3Err(new ErrorV3(err));
  494. }
  495. });
  496. /**
  497. * @swagger
  498. *
  499. * paths:
  500. * /users/{id}/grant-read-only:
  501. * put:
  502. * tags: [Users]
  503. * operationId: ReadOnly
  504. * summary: /users/{id}/grant-read-only
  505. * description: Grant user read only access
  506. * parameters:
  507. * - name: id
  508. * in: path
  509. * required: true
  510. * description: id of user for read only access
  511. * schema:
  512. * type: string
  513. * responses:
  514. * 200:
  515. * description: Grant user read only access success
  516. * content:
  517. * application/json:
  518. * schema:
  519. * properties:
  520. * userData:
  521. * type: object
  522. * description: data of read only
  523. */
  524. router.put('/:id/grant-read-only', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
  525. const { id } = req.params;
  526. try {
  527. const userData = await User.findById(id);
  528. if (userData == null) {
  529. return res.apiv3Err(new ErrorV3('User not found'), 404);
  530. }
  531. await userData.grantReadOnly();
  532. const serializedUserData = serializeUserSecurely(userData);
  533. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_GRANT_READ_ONLY });
  534. return res.apiv3({ userData: serializedUserData });
  535. }
  536. catch (err) {
  537. logger.error('Error', err);
  538. return res.apiv3Err(new ErrorV3(err));
  539. }
  540. });
  541. /**
  542. * @swagger
  543. *
  544. * paths:
  545. * /users/{id}/revoke-read-only:
  546. * put:
  547. * tags: [Users]
  548. * operationId: revokeReadOnly
  549. * summary: /users/{id}/revoke-read-only
  550. * description: Revoke user read only access
  551. * parameters:
  552. * - name: id
  553. * in: path
  554. * required: true
  555. * description: id of user for removing read only access
  556. * schema:
  557. * type: string
  558. * responses:
  559. * 200:
  560. * description: Revoke user read only access success
  561. * content:
  562. * application/json:
  563. * schema:
  564. * properties:
  565. * userData:
  566. * type: object
  567. * description: data of revoke read only
  568. */
  569. router.put('/:id/revoke-read-only', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
  570. const { id } = req.params;
  571. try {
  572. const userData = await User.findById(id);
  573. if (userData == null) {
  574. return res.apiv3Err(new ErrorV3('User not found'), 404);
  575. }
  576. await userData.revokeReadOnly();
  577. const serializedUserData = serializeUserSecurely(userData);
  578. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_REVOKE_READ_ONLY });
  579. return res.apiv3({ userData: serializedUserData });
  580. }
  581. catch (err) {
  582. logger.error('Error', err);
  583. return res.apiv3Err(new ErrorV3(err));
  584. }
  585. });
  586. /**
  587. * @swagger
  588. *
  589. * paths:
  590. * /users/{id}/activate:
  591. * put:
  592. * tags: [Users]
  593. * operationId: activateUser
  594. * summary: /users/{id}/activate
  595. * description: Activate user
  596. * parameters:
  597. * - name: id
  598. * in: path
  599. * required: true
  600. * description: id of activate user
  601. * schema:
  602. * type: string
  603. * responses:
  604. * 200:
  605. * description: Activationg user success
  606. * content:
  607. * application/json:
  608. * schema:
  609. * properties:
  610. * userData:
  611. * type: object
  612. * description: data of activate user
  613. */
  614. router.put('/:id/activate', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
  615. // check user upper limit
  616. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  617. if (isUserCountExceedsUpperLimit) {
  618. const msg = 'Unable to activate because user has reached limit';
  619. logger.error('Error', msg);
  620. return res.apiv3Err(new ErrorV3(msg));
  621. }
  622. const { id } = req.params;
  623. try {
  624. const userData = await User.findById(id);
  625. await userData.statusActivate();
  626. const serializedUserData = serializeUserSecurely(userData);
  627. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_ACTIVATE });
  628. return res.apiv3({ userData: serializedUserData });
  629. }
  630. catch (err) {
  631. logger.error('Error', err);
  632. return res.apiv3Err(new ErrorV3(err));
  633. }
  634. });
  635. /**
  636. * @swagger
  637. *
  638. * paths:
  639. * /users/{id}/deactivate:
  640. * put:
  641. * tags: [Users]
  642. * operationId: deactivateUser
  643. * summary: /users/{id}/deactivate
  644. * description: Deactivate user
  645. * parameters:
  646. * - name: id
  647. * in: path
  648. * required: true
  649. * description: id of deactivate user
  650. * schema:
  651. * type: string
  652. * responses:
  653. * 200:
  654. * description: Deactivationg user success
  655. * content:
  656. * application/json:
  657. * schema:
  658. * properties:
  659. * userData:
  660. * type: object
  661. * description: data of deactivate user
  662. */
  663. router.put('/:id/deactivate', loginRequiredStrictly, adminRequired, certifyUserOperationOtherThenYourOwn, addActivity, async(req, res) => {
  664. const { id } = req.params;
  665. try {
  666. const userData = await User.findById(id);
  667. await userData.statusSuspend();
  668. const serializedUserData = serializeUserSecurely(userData);
  669. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_DEACTIVATE });
  670. return res.apiv3({ userData: serializedUserData });
  671. }
  672. catch (err) {
  673. logger.error('Error', err);
  674. return res.apiv3Err(new ErrorV3(err));
  675. }
  676. });
  677. /**
  678. * @swagger
  679. *
  680. * paths:
  681. * /users/{id}/remove:
  682. * delete:
  683. * tags: [Users]
  684. * operationId: removeUser
  685. * summary: /users/{id}/remove
  686. * description: Delete user and if isUsersHomepageDeletionEnabled delete user homepage and subpages
  687. * parameters:
  688. * - name: id
  689. * in: path
  690. * required: true
  691. * description: id of delete user
  692. * schema:
  693. * type: string
  694. * responses:
  695. * 200:
  696. * description: Deleting user success and if isUsersHomepageDeletionEnabled delete user homepage and subpages success
  697. * content:
  698. * application/json:
  699. * schema:
  700. * properties:
  701. * user:
  702. * type: object
  703. * description: data of deleted user
  704. * userHomepagePath:
  705. * type: string
  706. * description: a user homepage path
  707. * isUsersHomepageDeletionEnabled:
  708. * type: boolean
  709. * description: is users homepage deletion enabled
  710. */
  711. router.delete('/:id/remove', loginRequiredStrictly, adminRequired, certifyUserOperationOtherThenYourOwn, addActivity, async(req, res) => {
  712. const { id } = req.params;
  713. const isUsersHomepageDeletionEnabled = configManager.getConfig('crowi', 'security:isUsersHomepageDeletionEnabled');
  714. try {
  715. const user = await User.findById(id);
  716. // !! DO NOT MOVE homepagePath FROM THIS POSITION !! -- 05.31.2023
  717. // catch username before delete user because username will be change to deleted_at_*
  718. const homepagePath = userHomepagePath(user);
  719. await UserGroupRelation.remove({ relatedUser: user });
  720. await user.statusDelete();
  721. await ExternalAccount.remove({ user });
  722. const serializedUser = serializeUserSecurely(user);
  723. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_REMOVE });
  724. if (isUsersHomepageDeletionEnabled) {
  725. crowi.pageService.deleteCompletelyUserHomeBySystem(homepagePath);
  726. }
  727. return res.apiv3({ user: serializedUser });
  728. }
  729. catch (err) {
  730. logger.error('Error', err);
  731. return res.apiv3Err(new ErrorV3(err));
  732. }
  733. });
  734. /**
  735. * @swagger
  736. *
  737. * paths:
  738. * /users/external-accounts:
  739. * get:
  740. * tags: [Users]
  741. * operationId: listExternalAccountsUsers
  742. * summary: /users/external-accounts
  743. * description: Get external-account
  744. * responses:
  745. * 200:
  746. * description: external-account are fetched
  747. * content:
  748. * application/json:
  749. * schema:
  750. * properties:
  751. * paginateResult:
  752. * $ref: '#/components/schemas/PaginateResult'
  753. */
  754. router.get('/external-accounts/', loginRequiredStrictly, adminRequired, async(req, res) => {
  755. const page = parseInt(req.query.page) || 1;
  756. try {
  757. const paginateResult = await ExternalAccount.findAllWithPagination({ page });
  758. return res.apiv3({ paginateResult });
  759. }
  760. catch (err) {
  761. const msg = 'Error occurred in fetching external-account list ';
  762. logger.error(msg, err);
  763. return res.apiv3Err(new ErrorV3(msg + err.message, 'external-account-list-fetch-failed'), 500);
  764. }
  765. });
  766. /**
  767. * @swagger
  768. *
  769. * paths:
  770. * /users/external-accounts/{id}/remove:
  771. * delete:
  772. * tags: [Users]
  773. * operationId: removeExternalAccountUser
  774. * summary: /users/external-accounts/{id}/remove
  775. * description: Delete ExternalAccount
  776. * parameters:
  777. * - name: id
  778. * in: path
  779. * required: true
  780. * description: id of ExternalAccount
  781. * schema:
  782. * type: string
  783. * responses:
  784. * 200:
  785. * description: External Account is removed
  786. * content:
  787. * application/json:
  788. * schema:
  789. * properties:
  790. * externalAccount:
  791. * type: object
  792. * description: A result of `ExtenralAccount.findByIdAndRemove`
  793. */
  794. router.delete('/external-accounts/:id/remove', loginRequiredStrictly, adminRequired, apiV3FormValidator, async(req, res) => {
  795. const { id } = req.params;
  796. try {
  797. const externalAccount = await ExternalAccount.findByIdAndRemove(id);
  798. return res.apiv3({ externalAccount });
  799. }
  800. catch (err) {
  801. const msg = 'Error occurred in deleting a external account ';
  802. logger.error(msg, err);
  803. return res.apiv3Err(new ErrorV3(msg + err.message, 'extenral-account-delete-failed'));
  804. }
  805. });
  806. /**
  807. * @swagger
  808. *
  809. * paths:
  810. * /users/update.imageUrlCache:
  811. * put:
  812. * tags: [Users]
  813. * operationId: update.imageUrlCache
  814. * summary: /users/update.imageUrlCache
  815. * description: update imageUrlCache
  816. * parameters:
  817. * - name: userIds
  818. * in: query
  819. * description: user id list
  820. * schema:
  821. * type: string
  822. * responses:
  823. * 200:
  824. * description: success creating imageUrlCached
  825. * content:
  826. * application/json:
  827. * schema:
  828. * properties:
  829. * userData:
  830. * type: object
  831. * description: users updated with imageUrlCached
  832. */
  833. router.put('/update.imageUrlCache', loginRequiredStrictly, adminRequired, async(req, res) => {
  834. try {
  835. const userIds = req.body.userIds;
  836. const users = await User.find({ _id: { $in: userIds }, imageUrlCached: null });
  837. const requests = await Promise.all(users.map(async(user) => {
  838. return {
  839. updateOne: {
  840. filter: { _id: user._id },
  841. update: { $set: { imageUrlCached: await user.generateImageUrlCached() } },
  842. },
  843. };
  844. }));
  845. if (requests.length > 0) {
  846. await User.bulkWrite(requests);
  847. }
  848. return res.apiv3({});
  849. }
  850. catch (err) {
  851. logger.error('Error', err);
  852. return res.apiv3Err(new ErrorV3(err));
  853. }
  854. });
  855. /**
  856. * @swagger
  857. *
  858. * paths:
  859. * /users/reset-password:
  860. * put:
  861. * tags: [Users]
  862. * operationId: resetPassword
  863. * summary: /users/reset-password
  864. * description: update imageUrlCache
  865. * requestBody:
  866. * content:
  867. * application/json:
  868. * schema:
  869. * properties:
  870. * newPassword:
  871. * type: string
  872. * user:
  873. * type: string
  874. * description: user id for reset password
  875. * responses:
  876. * 200:
  877. * description: success reset password
  878. */
  879. router.put('/reset-password', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
  880. const { id } = req.body;
  881. try {
  882. const [newPassword, user] = await Promise.all([
  883. await User.resetPasswordByRandomString(id),
  884. await User.findById(id)]);
  885. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_PASSWORD_RESET });
  886. return res.apiv3({ newPassword, user });
  887. }
  888. catch (err) {
  889. logger.error('Error', err);
  890. return res.apiv3Err(new ErrorV3(err));
  891. }
  892. });
  893. /**
  894. * @swagger
  895. *
  896. * paths:
  897. * /users/reset-password-email:
  898. * put:
  899. * tags: [Users]
  900. * operationId: resetPasswordEmail
  901. * summary: /users/reset-password-email
  902. * description: send new password email
  903. * requestBody:
  904. * content:
  905. * application/json:
  906. * schema:
  907. * properties:
  908. * newPassword:
  909. * type: string
  910. * user:
  911. * type: string
  912. * description: user id for send new password email
  913. * responses:
  914. * 200:
  915. * description: success send new password email
  916. */
  917. router.put('/reset-password-email', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
  918. const { id } = req.body;
  919. try {
  920. const user = await User.findById(id);
  921. if (user == null) {
  922. throw new Error('User not found');
  923. }
  924. const userInfo = {
  925. email: user.email,
  926. password: req.body.newPassword,
  927. };
  928. await sendEmailByUser(userInfo);
  929. return res.apiv3();
  930. }
  931. catch (err) {
  932. const msg = err.message;
  933. logger.error('Error', err);
  934. return res.apiv3Err(new ErrorV3(msg));
  935. }
  936. });
  937. /**
  938. * @swagger
  939. *
  940. * paths:
  941. * /users/send-invitation-email:
  942. * put:
  943. * tags: [Users]
  944. * operationId: sendInvitationEmail
  945. * summary: /users/send-invitation-email
  946. * description: send invitation email
  947. * requestBody:
  948. * content:
  949. * application/json:
  950. * schema:
  951. * properties:
  952. * id:
  953. * type: string
  954. * description: user id for send invitation email
  955. * responses:
  956. * 200:
  957. * description: success send invitation email
  958. * content:
  959. * application/json:
  960. * schema:
  961. * properties:
  962. * failedToSendEmail:
  963. * type: object
  964. * description: email and reasons for email sending failure
  965. */
  966. router.put('/send-invitation-email', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
  967. const { id } = req.body;
  968. try {
  969. const user = await User.findById(id);
  970. const newPassword = await User.resetPasswordByRandomString(id);
  971. const userList = [{
  972. email: user.email,
  973. password: newPassword,
  974. user: { id },
  975. }];
  976. const sendEmail = await sendEmailByUserList(userList);
  977. // return null if absent
  978. activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_SEND_INVITATION_EMAIL });
  979. return res.apiv3({ failedToSendEmail: sendEmail.failedToSendEmailList[0] });
  980. }
  981. catch (err) {
  982. logger.error('Error', err);
  983. return res.apiv3Err(new ErrorV3(err));
  984. }
  985. });
  986. /**
  987. * @swagger
  988. *
  989. * paths:
  990. * /users/list:
  991. * get:
  992. * tags: [Users]
  993. * summary: /users/list
  994. * operationId: getUsersList
  995. * description: Get list of users
  996. * parameters:
  997. * - in: query
  998. * name: userIds
  999. * schema:
  1000. * type: string
  1001. * description: user IDs
  1002. * example: 5e06fcc7516d64004dbf4da6,5e098d53baa2ac004e7d24ad
  1003. * responses:
  1004. * 200:
  1005. * description: Succeeded to get list of users.
  1006. * content:
  1007. * application/json:
  1008. * schema:
  1009. * properties:
  1010. * users:
  1011. * type: array
  1012. * items:
  1013. * $ref: '#/components/schemas/User'
  1014. * description: user list
  1015. * 403:
  1016. * $ref: '#/components/responses/403'
  1017. * 500:
  1018. * $ref: '#/components/responses/500'
  1019. */
  1020. router.get('/list', accessTokenParser, loginRequired, async(req, res) => {
  1021. const userIds = req.query.userIds || null;
  1022. let userFetcher;
  1023. if (userIds !== null && userIds.split(',').length > 0) {
  1024. userFetcher = User.findUsersByIds(userIds.split(','));
  1025. }
  1026. else {
  1027. userFetcher = User.findAllUsers();
  1028. }
  1029. const data = {};
  1030. try {
  1031. const users = await userFetcher;
  1032. data.users = users.map((user) => {
  1033. // omit email
  1034. if (user.isEmailPublished !== true) { // compare to 'true' because Crowi original data doesn't have 'isEmailPublished'
  1035. user.email = undefined;
  1036. }
  1037. return user.toObject({ virtuals: true });
  1038. });
  1039. }
  1040. catch (err) {
  1041. return res.apiv3Err(new ErrorV3(err));
  1042. }
  1043. return res.apiv3(data);
  1044. });
  1045. router.get('/usernames', accessTokenParser, loginRequired, validator.usernames, apiV3FormValidator, async(req, res) => {
  1046. const q = req.query.q;
  1047. const offset = +req.query.offset || 0;
  1048. const limit = +req.query.limit || 10;
  1049. try {
  1050. const options = JSON.parse(req.query.options || '{}');
  1051. const data = {};
  1052. if (options.isIncludeActiveUser == null || options.isIncludeActiveUser) {
  1053. const activeUserData = await User.findUserByUsernameRegexWithTotalCount(q, [User.STATUS_ACTIVE], { offset, limit });
  1054. const activeUsernames = activeUserData.users.map(user => user.username);
  1055. Object.assign(data, { activeUser: { usernames: activeUsernames, totalCount: activeUserData.totalCount } });
  1056. }
  1057. if (options.isIncludeInactiveUser) {
  1058. const inactiveUserStates = [User.STATUS_REGISTERED, User.STATUS_SUSPENDED, User.STATUS_INVITED];
  1059. const inactiveUserData = await User.findUserByUsernameRegexWithTotalCount(q, inactiveUserStates, { offset, limit });
  1060. const inactiveUsernames = inactiveUserData.users.map(user => user.username);
  1061. Object.assign(data, { inactiveUser: { usernames: inactiveUsernames, totalCount: inactiveUserData.totalCount } });
  1062. }
  1063. if (options.isIncludeActivitySnapshotUser && req.user.admin) {
  1064. const activitySnapshotUserData = await Activity.findSnapshotUsernamesByUsernameRegexWithTotalCount(q, { offset, limit });
  1065. Object.assign(data, { activitySnapshotUser: activitySnapshotUserData });
  1066. }
  1067. // eslint-disable-next-line max-len
  1068. const canIncludeMixedUsernames = (options.isIncludeMixedUsernames && req.user.admin) || (options.isIncludeMixedUsernames && !options.isIncludeActivitySnapshotUser);
  1069. if (canIncludeMixedUsernames) {
  1070. const allUsernames = [...data.activeUser?.usernames || [], ...data.inactiveUser?.usernames || [], ...data?.activitySnapshotUser?.usernames || []];
  1071. const distinctUsernames = Array.from(new Set(allUsernames));
  1072. Object.assign(data, { mixedUsernames: distinctUsernames });
  1073. }
  1074. return res.apiv3(data);
  1075. }
  1076. catch (err) {
  1077. logger.error('Failed to get usernames', err);
  1078. return res.apiv3Err(err);
  1079. }
  1080. });
  1081. return router;
  1082. };