| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212 |
- import { ErrorV3 } from '@growi/core/dist/models';
- import { userHomepagePath } from '@growi/core/dist/utils/page-path-utils';
- import { SupportedAction } from '~/interfaces/activity';
- import Activity from '~/server/models/activity';
- import { configManager } from '~/server/service/config-manager';
- import loggerFactory from '~/utils/logger';
- import { generateAddActivityMiddleware } from '../../middlewares/add-activity';
- import { apiV3FormValidator } from '../../middlewares/apiv3-form-validator';
- const logger = loggerFactory('growi:routes:apiv3:users');
- const path = require('path');
- const express = require('express');
- const router = express.Router();
- const { body, query } = require('express-validator');
- const { isEmail } = require('validator');
- const { serializePageSecurely } = require('../../models/serializers/page-serializer');
- const { serializeUserSecurely } = require('../../models/serializers/user-serializer');
- const PAGE_ITEMS = 50;
- const validator = {};
- /**
- * @swagger
- * tags:
- * name: Users
- */
- /**
- * @swagger
- *
- * components:
- * schemas:
- * User:
- * description: User
- * type: object
- * properties:
- * _id:
- * type: string
- * description: user ID
- * example: 5ae5fccfc5577b0004dbd8ab
- * lang:
- * type: string
- * description: language
- * example: 'en_US'
- * status:
- * type: integer
- * description: status
- * example: 0
- * admin:
- * type: boolean
- * description: whether the admin
- * example: false
- * email:
- * type: string
- * description: E-Mail address
- * example: alice@aaa.aaa
- * username:
- * type: string
- * description: username
- * example: alice
- * name:
- * type: string
- * description: full name
- * example: Alice
- * createdAt:
- * type: string
- * description: date created at
- * example: 2010-01-01T00:00:00.000Z
- */
- module.exports = (crowi) => {
- const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
- const loginRequired = require('../../middlewares/login-required')(crowi, true);
- const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
- const adminRequired = require('../../middlewares/admin-required')(crowi);
- const addActivity = generateAddActivityMiddleware(crowi);
- const activityEvent = crowi.event('activity');
- const {
- User,
- Page,
- ExternalAccount,
- UserGroupRelation,
- } = crowi.models;
- const statusNo = {
- registered: User.STATUS_REGISTERED,
- active: User.STATUS_ACTIVE,
- suspended: User.STATUS_SUSPENDED,
- invited: User.STATUS_INVITED,
- };
- validator.statusList = [
- query('selectedStatusList').if(value => value != null).custom((value, { req }) => {
- const { user } = req;
- if (user != null && user.admin) {
- return value;
- }
- throw new Error('the param \'selectedStatusList\' is not allowed to use by the users except administrators');
- }),
- // validate sortOrder : asc or desc
- query('sortOrder').isIn(['asc', 'desc']),
- // validate sort : what column you will sort
- query('sort').isIn(['id', 'status', 'username', 'name', 'email', 'createdAt', 'lastLoginAt']),
- query('page').isInt({ min: 1 }),
- query('forceIncludeAttributes').toArray().custom((value, { req }) => {
- // only the admin user can specify forceIncludeAttributes
- if (value.length === 0) {
- return true;
- }
- return req.user.admin;
- }),
- ];
- validator.recentCreatedByUser = [
- query('limit').if(value => value != null).isInt({ max: 300 }).withMessage('You should set less than 300 or not to set limit.'),
- ];
- validator.usernames = [
- query('q').isString().withMessage('q is required'),
- query('offset').optional().isInt().withMessage('offset must be a number'),
- query('limit').optional().isInt({ max: 20 }).withMessage('You should set less than 20 or not to set limit.'),
- query('options').optional().isString().withMessage('options must be string'),
- ];
- // express middleware
- const certifyUserOperationOtherThenYourOwn = (req, res, next) => {
- const { id } = req.params;
- if (req.user._id.toString() === id) {
- const msg = 'This API is not available for your own users';
- logger.error(msg);
- return res.apiv3Err(new ErrorV3(msg), 400);
- }
- next();
- };
- const sendEmailByUserList = async(userList) => {
- const { appService, mailService } = crowi;
- const appTitle = appService.getAppTitle();
- const locale = configManager.getConfig('crowi', 'app:globalLang');
- const failedToSendEmailList = [];
- for (const user of userList) {
- try {
- // eslint-disable-next-line no-await-in-loop
- await mailService.send({
- to: user.email,
- subject: `Invitation to ${appTitle}`,
- template: path.join(crowi.localeDir, `${locale}/admin/userInvitation.ejs`),
- vars: {
- email: user.email,
- password: user.password,
- url: crowi.appService.getSiteUrl(),
- appTitle,
- },
- });
- // eslint-disable-next-line no-await-in-loop
- await User.updateIsInvitationEmailSended(user.user.id);
- }
- catch (err) {
- logger.error(err);
- failedToSendEmailList.push({
- email: user.email,
- reason: err.message,
- });
- }
- }
- return { failedToSendEmailList };
- };
- const sendEmailByUser = async(user) => {
- const { appService, mailService } = crowi;
- const appTitle = appService.getAppTitle();
- const locale = configManager.getConfig('crowi', 'app:globalLang');
- await mailService.send({
- to: user.email,
- subject: `New password for ${appTitle}`,
- template: path.join(crowi.localeDir, `${locale}/admin/userResetPassword.ejs`),
- vars: {
- email: user.email,
- password: user.password,
- url: crowi.appService.getSiteUrl(),
- appTitle,
- },
- });
- };
- /**
- * @swagger
- *
- * paths:
- * /users:
- * get:
- * tags: [Users]
- * operationId: listUsers
- * summary: /users
- * description: Select selected columns from users order by asc or desc
- * parameters:
- * - name: page
- * in: query
- * description: page number
- * schema:
- * type: number
- * - name: selectedStatusList
- * in: query
- * description: status list
- * schema:
- * type: string
- * - name: searchText
- * in: query
- * description: For incremental search value from input box
- * schema:
- * type: string
- * - name: sortOrder
- * in: query
- * description: asc or desc
- * schema:
- * type: string
- * - name: sort
- * in: query
- * description: sorting column
- * schema:
- * type: string
- * responses:
- * 200:
- * description: users are fetched
- * content:
- * application/json:
- * schema:
- * properties:
- * paginateResult:
- * $ref: '#/components/schemas/PaginateResult'
- */
- router.get('/', accessTokenParser, loginRequired, validator.statusList, apiV3FormValidator, async(req, res) => {
- const page = parseInt(req.query.page) || 1;
- // status
- const { forceIncludeAttributes } = req.query;
- const selectedStatusList = req.query.selectedStatusList || ['active'];
- const statusNoList = (selectedStatusList.includes('all')) ? Object.values(statusNo) : selectedStatusList.map(element => statusNo[element]);
- // Search from input
- const searchText = req.query.searchText || '';
- const searchWord = new RegExp(`${searchText}`);
- // Sort
- const { sort, sortOrder } = req.query;
- const sortOutput = {
- [sort]: (sortOrder === 'desc') ? -1 : 1,
- };
- // For more information about the external specification of the User API, see here (https://dev.growi.org/5fd7466a31d89500488248e3)
- const orConditions = [
- { name: { $in: searchWord } },
- { username: { $in: searchWord } },
- ];
- const query = {
- $and: [
- { status: { $in: statusNoList } },
- {
- $or: orConditions,
- },
- ],
- };
- try {
- if (req.user != null) {
- orConditions.push(
- {
- $and: [
- { isEmailPublished: true },
- { email: { $in: searchWord } },
- ],
- },
- );
- }
- if (forceIncludeAttributes.includes('email')) {
- orConditions.push({ email: { $in: searchWord } });
- }
- const paginateResult = await User.paginate(
- query,
- {
- sort: sortOutput,
- page,
- limit: PAGE_ITEMS,
- },
- );
- paginateResult.docs = paginateResult.docs.map((doc) => {
- // return email only when specified by query
- const { email } = doc;
- const user = serializeUserSecurely(doc);
- if (forceIncludeAttributes.includes('email')) {
- user.email = email;
- }
- return user;
- });
- return res.apiv3({ paginateResult });
- }
- catch (err) {
- const msg = 'Error occurred in fetching user group list';
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(msg, 'user-group-list-fetch-failed'), 500);
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /{id}/recent:
- * get:
- * tags: [Users]
- * operationId: recent created page of user id
- * summary: /usersIdReacent
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of user
- * schema:
- * type: string
- * responses:
- * 200:
- * description: users recent created pages are fetched
- * content:
- * application/json:
- * schema:
- * properties:
- * paginateResult:
- * $ref: '#/components/schemas/PaginateResult'
- */
- router.get('/:id/recent', accessTokenParser, loginRequired, validator.recentCreatedByUser, apiV3FormValidator, async(req, res) => {
- const { id } = req.params;
- let user;
- try {
- user = await User.findById(id);
- }
- catch (err) {
- const msg = 'Error occurred in find user';
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(msg, 'retrieve-recent-created-pages-failed'), 500);
- }
- if (user == null) {
- return res.apiv3Err(new ErrorV3('find-user-is-not-found'));
- }
- const limit = parseInt(req.query.limit) || await configManager.getConfig('crowi', 'customize:showPageLimitationM') || 30;
- const page = req.query.page;
- const offset = (page - 1) * limit;
- const queryOptions = { offset, limit };
- try {
- const result = await Page.findListByCreator(user, req.user, queryOptions);
- result.pages = result.pages.map(page => serializePageSecurely(page));
- return res.apiv3(result);
- }
- catch (err) {
- const msg = 'Error occurred in retrieve recent created pages for user';
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(msg, 'retrieve-recent-created-pages-failed'), 500);
- }
- });
- validator.inviteEmail = [
- // isEmail prevents line breaks, so use isString
- body('shapedEmailList').custom((value) => {
- const array = value.filter((value) => { return isEmail(value) });
- if (array.length === 0) {
- throw new Error('At least one valid email address is required');
- }
- return array;
- }),
- ];
- /**
- * @swagger
- *
- * paths:
- * /users/invite:
- * post:
- * tags: [Users]
- * operationId: inviteUser
- * summary: /users/invite
- * description: Create new users and send Emails
- * parameters:
- * - name: shapedEmailList
- * in: query
- * description: Invitation emailList
- * schema:
- * type: object
- * - name: sendEmail
- * in: query
- * description: Whether to send mail
- * schema:
- * type: boolean
- * responses:
- * 200:
- * description: Inviting user success
- * content:
- * application/json:
- * schema:
- * properties:
- * createdUserList:
- * type: object
- * description: Users successfully created
- * existingEmailList:
- * type: object
- * description: Users email that already exists
- * failedEmailList:
- * type: object
- * description: Users email that failed to create or send email
- */
- router.post('/invite', loginRequiredStrictly, adminRequired, addActivity, validator.inviteEmail, apiV3FormValidator, async(req, res) => {
- // Delete duplicate email addresses
- const emailList = Array.from(new Set(req.body.shapedEmailList));
- let failedEmailList = [];
- // Create users
- const createUser = await User.createUsersByEmailList(emailList);
- if (createUser.failedToCreateUserEmailList.length > 0) {
- failedEmailList = failedEmailList.concat(createUser.failedToCreateUserEmailList);
- }
- // Send email
- if (req.body.sendEmail) {
- const sendEmail = await sendEmailByUserList(createUser.createdUserList);
- if (sendEmail.failedToSendEmailList.length > 0) {
- failedEmailList = failedEmailList.concat(sendEmail.failedToSendEmailList);
- }
- }
- const parameters = { action: SupportedAction.ACTION_ADMIN_USERS_INVITE };
- activityEvent.emit('update', res.locals.activity._id, parameters);
- return res.apiv3({
- createdUserList: createUser.createdUserList,
- existingEmailList: createUser.existingEmailList,
- failedEmailList,
- }, 201);
- });
- /**
- * @swagger
- *
- * paths:
- * /users/{id}/grant-admin:
- * put:
- * tags: [Users]
- * operationId: grantAdminUser
- * summary: /users/{id}/grant-admin
- * description: Grant user admin
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of user for admin
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Grant user admin success
- * content:
- * application/json:
- * schema:
- * properties:
- * userData:
- * type: object
- * description: data of admin user
- */
- router.put('/:id/grant-admin', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
- const { id } = req.params;
- try {
- const userData = await User.findById(id);
- await userData.grantAdmin();
- const serializedUserData = serializeUserSecurely(userData);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_GRANT_ADMIN });
- return res.apiv3({ userData: serializedUserData });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/{id}/revoke-admin:
- * put:
- * tags: [Users]
- * operationId: revokeAdminUser
- * summary: /users/{id}/revoke-admin
- * description: Revoke user admin
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of user for revoking admin
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Revoke user admin success
- * content:
- * application/json:
- * schema:
- * properties:
- * userData:
- * type: object
- * description: data of revoked admin user
- */
- router.put('/:id/revoke-admin', loginRequiredStrictly, adminRequired, certifyUserOperationOtherThenYourOwn, addActivity, async(req, res) => {
- const { id } = req.params;
- try {
- const userData = await User.findById(id);
- await userData.revokeAdmin();
- const serializedUserData = serializeUserSecurely(userData);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_REVOKE_ADMIN });
- return res.apiv3({ userData: serializedUserData });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/{id}/grant-read-only:
- * put:
- * tags: [Users]
- * operationId: ReadOnly
- * summary: /users/{id}/grant-read-only
- * description: Grant user read only access
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of user for read only access
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Grant user read only access success
- * content:
- * application/json:
- * schema:
- * properties:
- * userData:
- * type: object
- * description: data of read only
- */
- router.put('/:id/grant-read-only', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
- const { id } = req.params;
- try {
- const userData = await User.findById(id);
- if (userData == null) {
- return res.apiv3Err(new ErrorV3('User not found'), 404);
- }
- await userData.grantReadOnly();
- const serializedUserData = serializeUserSecurely(userData);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_GRANT_READ_ONLY });
- return res.apiv3({ userData: serializedUserData });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/{id}/revoke-read-only:
- * put:
- * tags: [Users]
- * operationId: revokeReadOnly
- * summary: /users/{id}/revoke-read-only
- * description: Revoke user read only access
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of user for removing read only access
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Revoke user read only access success
- * content:
- * application/json:
- * schema:
- * properties:
- * userData:
- * type: object
- * description: data of revoke read only
- */
- router.put('/:id/revoke-read-only', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
- const { id } = req.params;
- try {
- const userData = await User.findById(id);
- if (userData == null) {
- return res.apiv3Err(new ErrorV3('User not found'), 404);
- }
- await userData.revokeReadOnly();
- const serializedUserData = serializeUserSecurely(userData);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_REVOKE_READ_ONLY });
- return res.apiv3({ userData: serializedUserData });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/{id}/activate:
- * put:
- * tags: [Users]
- * operationId: activateUser
- * summary: /users/{id}/activate
- * description: Activate user
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of activate user
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Activationg user success
- * content:
- * application/json:
- * schema:
- * properties:
- * userData:
- * type: object
- * description: data of activate user
- */
- router.put('/:id/activate', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
- // check user upper limit
- const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
- if (isUserCountExceedsUpperLimit) {
- const msg = 'Unable to activate because user has reached limit';
- logger.error('Error', msg);
- return res.apiv3Err(new ErrorV3(msg));
- }
- const { id } = req.params;
- try {
- const userData = await User.findById(id);
- await userData.statusActivate();
- const serializedUserData = serializeUserSecurely(userData);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_ACTIVATE });
- return res.apiv3({ userData: serializedUserData });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/{id}/deactivate:
- * put:
- * tags: [Users]
- * operationId: deactivateUser
- * summary: /users/{id}/deactivate
- * description: Deactivate user
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of deactivate user
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Deactivationg user success
- * content:
- * application/json:
- * schema:
- * properties:
- * userData:
- * type: object
- * description: data of deactivate user
- */
- router.put('/:id/deactivate', loginRequiredStrictly, adminRequired, certifyUserOperationOtherThenYourOwn, addActivity, async(req, res) => {
- const { id } = req.params;
- try {
- const userData = await User.findById(id);
- await userData.statusSuspend();
- const serializedUserData = serializeUserSecurely(userData);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_DEACTIVATE });
- return res.apiv3({ userData: serializedUserData });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/{id}/remove:
- * delete:
- * tags: [Users]
- * operationId: removeUser
- * summary: /users/{id}/remove
- * description: Delete user and if isUsersHomepageDeletionEnabled delete user homepage and subpages
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of delete user
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Deleting user success and if isUsersHomepageDeletionEnabled delete user homepage and subpages success
- * content:
- * application/json:
- * schema:
- * properties:
- * user:
- * type: object
- * description: data of deleted user
- * userHomepagePath:
- * type: string
- * description: a user homepage path
- * isUsersHomepageDeletionEnabled:
- * type: boolean
- * description: is users homepage deletion enabled
- */
- router.delete('/:id/remove', loginRequiredStrictly, adminRequired, certifyUserOperationOtherThenYourOwn, addActivity, async(req, res) => {
- const { id } = req.params;
- const isUsersHomepageDeletionEnabled = configManager.getConfig('crowi', 'security:isUsersHomepageDeletionEnabled');
- try {
- const user = await User.findById(id);
- // !! DO NOT MOVE homepagePath FROM THIS POSITION !! -- 05.31.2023
- // catch username before delete user because username will be change to deleted_at_*
- const homepagePath = userHomepagePath(user);
- await UserGroupRelation.remove({ relatedUser: user });
- await user.statusDelete();
- await ExternalAccount.remove({ user });
- const serializedUser = serializeUserSecurely(user);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_REMOVE });
- if (isUsersHomepageDeletionEnabled) {
- crowi.pageService.deleteCompletelyUserHomeBySystem(homepagePath);
- }
- return res.apiv3({ user: serializedUser });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/external-accounts:
- * get:
- * tags: [Users]
- * operationId: listExternalAccountsUsers
- * summary: /users/external-accounts
- * description: Get external-account
- * responses:
- * 200:
- * description: external-account are fetched
- * content:
- * application/json:
- * schema:
- * properties:
- * paginateResult:
- * $ref: '#/components/schemas/PaginateResult'
- */
- router.get('/external-accounts/', loginRequiredStrictly, adminRequired, async(req, res) => {
- const page = parseInt(req.query.page) || 1;
- try {
- const paginateResult = await ExternalAccount.findAllWithPagination({ page });
- return res.apiv3({ paginateResult });
- }
- catch (err) {
- const msg = 'Error occurred in fetching external-account list ';
- logger.error(msg, err);
- return res.apiv3Err(new ErrorV3(msg + err.message, 'external-account-list-fetch-failed'), 500);
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/external-accounts/{id}/remove:
- * delete:
- * tags: [Users]
- * operationId: removeExternalAccountUser
- * summary: /users/external-accounts/{id}/remove
- * description: Delete ExternalAccount
- * parameters:
- * - name: id
- * in: path
- * required: true
- * description: id of ExternalAccount
- * schema:
- * type: string
- * responses:
- * 200:
- * description: External Account is removed
- * content:
- * application/json:
- * schema:
- * properties:
- * externalAccount:
- * type: object
- * description: A result of `ExtenralAccount.findByIdAndRemove`
- */
- router.delete('/external-accounts/:id/remove', loginRequiredStrictly, adminRequired, apiV3FormValidator, async(req, res) => {
- const { id } = req.params;
- try {
- const externalAccount = await ExternalAccount.findByIdAndRemove(id);
- return res.apiv3({ externalAccount });
- }
- catch (err) {
- const msg = 'Error occurred in deleting a external account ';
- logger.error(msg, err);
- return res.apiv3Err(new ErrorV3(msg + err.message, 'extenral-account-delete-failed'));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/update.imageUrlCache:
- * put:
- * tags: [Users]
- * operationId: update.imageUrlCache
- * summary: /users/update.imageUrlCache
- * description: update imageUrlCache
- * parameters:
- * - name: userIds
- * in: query
- * description: user id list
- * schema:
- * type: string
- * responses:
- * 200:
- * description: success creating imageUrlCached
- * content:
- * application/json:
- * schema:
- * properties:
- * userData:
- * type: object
- * description: users updated with imageUrlCached
- */
- router.put('/update.imageUrlCache', loginRequiredStrictly, adminRequired, async(req, res) => {
- try {
- const userIds = req.body.userIds;
- const users = await User.find({ _id: { $in: userIds }, imageUrlCached: null });
- const requests = await Promise.all(users.map(async(user) => {
- return {
- updateOne: {
- filter: { _id: user._id },
- update: { $set: { imageUrlCached: await user.generateImageUrlCached() } },
- },
- };
- }));
- if (requests.length > 0) {
- await User.bulkWrite(requests);
- }
- return res.apiv3({});
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/reset-password:
- * put:
- * tags: [Users]
- * operationId: resetPassword
- * summary: /users/reset-password
- * description: update imageUrlCache
- * requestBody:
- * content:
- * application/json:
- * schema:
- * properties:
- * newPassword:
- * type: string
- * user:
- * type: string
- * description: user id for reset password
- * responses:
- * 200:
- * description: success reset password
- */
- router.put('/reset-password', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
- const { id } = req.body;
- try {
- const [newPassword, user] = await Promise.all([
- await User.resetPasswordByRandomString(id),
- await User.findById(id)]);
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_PASSWORD_RESET });
- return res.apiv3({ newPassword, user });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/reset-password-email:
- * put:
- * tags: [Users]
- * operationId: resetPasswordEmail
- * summary: /users/reset-password-email
- * description: send new password email
- * requestBody:
- * content:
- * application/json:
- * schema:
- * properties:
- * newPassword:
- * type: string
- * user:
- * type: string
- * description: user id for send new password email
- * responses:
- * 200:
- * description: success send new password email
- */
- router.put('/reset-password-email', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
- const { id } = req.body;
- try {
- const user = await User.findById(id);
- if (user == null) {
- throw new Error('User not found');
- }
- const userInfo = {
- email: user.email,
- password: req.body.newPassword,
- };
- await sendEmailByUser(userInfo);
- return res.apiv3();
- }
- catch (err) {
- const msg = err.message;
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(msg));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/send-invitation-email:
- * put:
- * tags: [Users]
- * operationId: sendInvitationEmail
- * summary: /users/send-invitation-email
- * description: send invitation email
- * requestBody:
- * content:
- * application/json:
- * schema:
- * properties:
- * id:
- * type: string
- * description: user id for send invitation email
- * responses:
- * 200:
- * description: success send invitation email
- * content:
- * application/json:
- * schema:
- * properties:
- * failedToSendEmail:
- * type: object
- * description: email and reasons for email sending failure
- */
- router.put('/send-invitation-email', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
- const { id } = req.body;
- try {
- const user = await User.findById(id);
- const newPassword = await User.resetPasswordByRandomString(id);
- const userList = [{
- email: user.email,
- password: newPassword,
- user: { id },
- }];
- const sendEmail = await sendEmailByUserList(userList);
- // return null if absent
- activityEvent.emit('update', res.locals.activity._id, { action: SupportedAction.ACTION_ADMIN_USERS_SEND_INVITATION_EMAIL });
- return res.apiv3({ failedToSendEmail: sendEmail.failedToSendEmailList[0] });
- }
- catch (err) {
- logger.error('Error', err);
- return res.apiv3Err(new ErrorV3(err));
- }
- });
- /**
- * @swagger
- *
- * paths:
- * /users/list:
- * get:
- * tags: [Users]
- * summary: /users/list
- * operationId: getUsersList
- * description: Get list of users
- * parameters:
- * - in: query
- * name: userIds
- * schema:
- * type: string
- * description: user IDs
- * example: 5e06fcc7516d64004dbf4da6,5e098d53baa2ac004e7d24ad
- * responses:
- * 200:
- * description: Succeeded to get list of users.
- * content:
- * application/json:
- * schema:
- * properties:
- * users:
- * type: array
- * items:
- * $ref: '#/components/schemas/User'
- * description: user list
- * 403:
- * $ref: '#/components/responses/403'
- * 500:
- * $ref: '#/components/responses/500'
- */
- router.get('/list', accessTokenParser, loginRequired, async(req, res) => {
- const userIds = req.query.userIds || null;
- let userFetcher;
- if (userIds !== null && userIds.split(',').length > 0) {
- userFetcher = User.findUsersByIds(userIds.split(','));
- }
- else {
- userFetcher = User.findAllUsers();
- }
- const data = {};
- try {
- const users = await userFetcher;
- data.users = users.map((user) => {
- // omit email
- if (user.isEmailPublished !== true) { // compare to 'true' because Crowi original data doesn't have 'isEmailPublished'
- user.email = undefined;
- }
- return user.toObject({ virtuals: true });
- });
- }
- catch (err) {
- return res.apiv3Err(new ErrorV3(err));
- }
- return res.apiv3(data);
- });
- router.get('/usernames', accessTokenParser, loginRequired, validator.usernames, apiV3FormValidator, async(req, res) => {
- const q = req.query.q;
- const offset = +req.query.offset || 0;
- const limit = +req.query.limit || 10;
- try {
- const options = JSON.parse(req.query.options || '{}');
- const data = {};
- if (options.isIncludeActiveUser == null || options.isIncludeActiveUser) {
- const activeUserData = await User.findUserByUsernameRegexWithTotalCount(q, [User.STATUS_ACTIVE], { offset, limit });
- const activeUsernames = activeUserData.users.map(user => user.username);
- Object.assign(data, { activeUser: { usernames: activeUsernames, totalCount: activeUserData.totalCount } });
- }
- if (options.isIncludeInactiveUser) {
- const inactiveUserStates = [User.STATUS_REGISTERED, User.STATUS_SUSPENDED, User.STATUS_INVITED];
- const inactiveUserData = await User.findUserByUsernameRegexWithTotalCount(q, inactiveUserStates, { offset, limit });
- const inactiveUsernames = inactiveUserData.users.map(user => user.username);
- Object.assign(data, { inactiveUser: { usernames: inactiveUsernames, totalCount: inactiveUserData.totalCount } });
- }
- if (options.isIncludeActivitySnapshotUser && req.user.admin) {
- const activitySnapshotUserData = await Activity.findSnapshotUsernamesByUsernameRegexWithTotalCount(q, { offset, limit });
- Object.assign(data, { activitySnapshotUser: activitySnapshotUserData });
- }
- // eslint-disable-next-line max-len
- const canIncludeMixedUsernames = (options.isIncludeMixedUsernames && req.user.admin) || (options.isIncludeMixedUsernames && !options.isIncludeActivitySnapshotUser);
- if (canIncludeMixedUsernames) {
- const allUsernames = [...data.activeUser?.usernames || [], ...data.inactiveUser?.usernames || [], ...data?.activitySnapshotUser?.usernames || []];
- const distinctUsernames = Array.from(new Set(allUsernames));
- Object.assign(data, { mixedUsernames: distinctUsernames });
- }
- return res.apiv3(data);
- }
- catch (err) {
- logger.error('Failed to get usernames', err);
- return res.apiv3Err(err);
- }
- });
- return router;
- };
|