PeerTube/server/controllers/api/users/index.ts

413 lines
13 KiB
TypeScript
Raw Normal View History

2021-08-27 14:32:44 +02:00
import express from 'express'
import RateLimit from 'express-rate-limit'
2020-07-24 15:05:51 +02:00
import { tokensRouter } from '@server/controllers/api/users/token'
import { Hooks } from '@server/lib/plugins/hooks'
import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
2020-07-24 15:05:51 +02:00
import { MUser, MUserAccountDefault } from '@server/types/models'
2021-07-13 14:23:01 +02:00
import { UserCreate, UserCreateResult, UserRight, UserRole, UserUpdate } from '../../../../shared'
2021-07-16 10:42:24 +02:00
import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes'
2020-07-24 15:05:51 +02:00
import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
import { UserRegister } from '../../../../shared/models/users/user-register.model'
import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
2018-08-16 11:26:22 +02:00
import { logger } from '../../../helpers/logger'
import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
2020-07-24 15:05:51 +02:00
import { CONFIG } from '../../../initializers/config'
import { WEBSERVER } from '../../../initializers/constants'
2020-07-24 15:05:51 +02:00
import { sequelizeTypescript } from '../../../initializers/database'
2018-08-16 11:26:22 +02:00
import { Emailer } from '../../../lib/emailer'
2020-07-24 15:05:51 +02:00
import { Notifier } from '../../../lib/notifier'
2018-08-16 11:26:22 +02:00
import { Redis } from '../../../lib/redis'
2019-06-11 11:54:33 +02:00
import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
2017-05-15 22:22:03 +02:00
import {
2018-01-30 15:16:24 +01:00
asyncMiddleware,
2018-06-13 14:27:40 +02:00
asyncRetryTransactionMiddleware,
2018-01-30 15:16:24 +01:00
authenticate,
ensureUserHasRight,
ensureUserRegistrationAllowed,
ensureUserRegistrationAllowedForIP,
2018-01-30 15:16:24 +01:00
paginationValidator,
setDefaultPagination,
setDefaultSort,
Users can change ownership of their video [#510] (#888) * [#510] Create a new route to get the list of user names To be able to transfer ownership to a user, we need to be able to select him from the list of users. Because the list could be too big, we add a autocomplete feature. This commit does the following: * Add a API endpoint to get a list of user names by searching its name * [#510] The user can choose the next owner of the video To be able to transfer ownership to a user, we need the owner to be able to select the user. The server can autocomplete the name of the user to give the ownership. We add a dialog for the user to actually select it. This commit does the following: * Create a modal for the owner to select the next one * Opens this modal with a button into the menu *more* * Make the dependency injection * [#510] When the user choose the next owner, create a request in database For the change of ownership to happen, we need to store the temporary requests. When the user make the request, save it to database. This commit does the following: * Create the model to persist change ownership requests * Add an API to manage ownership operations * Add a route to persist an ownership request * [#510] A user can fetch its ownership requests sent to him To be able to accept or refuse a change of ownership, the user must be able to fetch them. This commit does the following: * Add an API to list ownership for a user * Add the query to database model * [#510] A user can validate an ownership requests sent to him - server The user can accept or refuse any ownership request that was sent to him. This commit focus only on the server part. This commit does the following: * Add an API for the user to accept or refuse a video ownership * Add validators to ensure security access * Add a query to load a specific video change ownership request * [#510] A user can validate an ownership requests sent to him - web The user can accept or refuse any ownership request that was sent to him. This commit focus only on the web part. This commit does the following: * Add a page to list user ownership changes * Add actions to accept or refuse them * When accepting, show a modal requiring the channel to send the video * Correct lint - to squash * [#510] PR reviews - to squash This commit does the following: * Search parameter for user autocompletion is required from middleware directly * [#510] PR reviews - to squash with creation in database commit This commit does the following: * Add the status attribute in model * Set this attribute on instance creation * Use AccountModel method `loadLocalByName` * [#510] PR reviews - to squash with fetch ownership This commit does the following: * Add the scope `FULL` for database queries with includes * Add classic pagination middlewares * [#510] PR reviews - to squash with ownership validation - server This commit does the following: * Add a middleware to validate whether a user can validate an ownership * Change the ownership status instead of deleting the row * [#510] PR reviews - to squash with ownership validation - client This commit does the following: * Correct indentation of html files with two-spaces indentation * Use event emitter instead of function for accept event * Update the sort of ownership change table for a decreasing order by creation date * Add the status in ownership change table * Use classic method syntax * code style - to squash * Add new user right - to squash * Move the change to my-account instead of video-watch - to squash As requested in pull-request, move the action to change ownership into my videos page. The rest of the logic was not really changed. This commit does the following: - Move the modal into my video page - Create the generic component `button` to keep some styles and logic * [#510] Add tests for the new feature To avoid regression, we add tests for all api of ownership change. This commit does the following: - Create an end-to-end test for ownership change - Divide it to one test per request * [#510] Do not send twice the same request to avoid spam We can send several time the same request to change ownership. However, it will spam the user. To avoid this, we do not save a request already existing in database. This commit does the following: - Check whether the request exist in database - Add tests to verify this new condition * [#510] Change icons Change icons so they remains logic with the rest of the application. This commit does the following: - Add svg for missing icons - Add icons in `my-button` component - Use these new icons * [#510] Add control about the user quota The user should be able to accept a new video only if his quota allows it. This commit does the following: - Update the middleware to control the quota - Add tests verifying the control * Correct merge - Use new modal system - Move button to new directory `buttons` * PR reviews - to squash
2018-09-04 08:57:13 +02:00
userAutocompleteValidator,
2018-01-30 15:16:24 +01:00
usersAddValidator,
usersGetValidator,
2020-07-24 15:05:51 +02:00
usersListValidator,
2018-01-30 15:16:24 +01:00
usersRegisterValidator,
usersRemoveValidator,
usersSortValidator,
2018-08-16 11:26:22 +02:00
usersUpdateValidator
} from '../../../middlewares'
import {
ensureCanManageUser,
2018-09-19 17:02:16 +02:00
usersAskResetPasswordValidator,
usersAskSendVerifyEmailValidator,
usersBlockingValidator,
usersResetPasswordValidator,
usersVerifyEmailValidator
} from '../../../middlewares/validators'
2021-05-11 11:15:29 +02:00
import { UserModel } from '../../../models/user/user'
2018-08-16 11:26:22 +02:00
import { meRouter } from './me'
2020-07-24 15:05:51 +02:00
import { myAbusesRouter } from './my-abuses'
import { myBlocklistRouter } from './my-blocklist'
import { myVideosHistoryRouter } from './my-history'
2018-12-26 10:36:24 +01:00
import { myNotificationsRouter } from './my-notifications'
import { mySubscriptionsRouter } from './my-subscriptions'
2020-07-24 15:05:51 +02:00
import { myVideoPlaylistsRouter } from './my-video-playlists'
const auditLogger = auditLoggerFactory('users')
2017-05-15 22:22:03 +02:00
const signupRateLimiter = RateLimit({
windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
skipFailedRequests: true
2018-03-29 10:58:24 +02:00
})
2017-12-29 19:10:13 +01:00
2020-06-17 10:55:40 +02:00
const askSendEmailLimiter = RateLimit({
windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
})
2017-05-15 22:22:03 +02:00
const usersRouter = express.Router()
usersRouter.use('/', tokensRouter)
2018-12-26 10:36:24 +01:00
usersRouter.use('/', myNotificationsRouter)
usersRouter.use('/', mySubscriptionsRouter)
usersRouter.use('/', myBlocklistRouter)
usersRouter.use('/', myVideosHistoryRouter)
2019-03-07 17:06:00 +01:00
usersRouter.use('/', myVideoPlaylistsRouter)
2020-07-24 15:05:51 +02:00
usersRouter.use('/', myAbusesRouter)
usersRouter.use('/', meRouter)
Users can change ownership of their video [#510] (#888) * [#510] Create a new route to get the list of user names To be able to transfer ownership to a user, we need to be able to select him from the list of users. Because the list could be too big, we add a autocomplete feature. This commit does the following: * Add a API endpoint to get a list of user names by searching its name * [#510] The user can choose the next owner of the video To be able to transfer ownership to a user, we need the owner to be able to select the user. The server can autocomplete the name of the user to give the ownership. We add a dialog for the user to actually select it. This commit does the following: * Create a modal for the owner to select the next one * Opens this modal with a button into the menu *more* * Make the dependency injection * [#510] When the user choose the next owner, create a request in database For the change of ownership to happen, we need to store the temporary requests. When the user make the request, save it to database. This commit does the following: * Create the model to persist change ownership requests * Add an API to manage ownership operations * Add a route to persist an ownership request * [#510] A user can fetch its ownership requests sent to him To be able to accept or refuse a change of ownership, the user must be able to fetch them. This commit does the following: * Add an API to list ownership for a user * Add the query to database model * [#510] A user can validate an ownership requests sent to him - server The user can accept or refuse any ownership request that was sent to him. This commit focus only on the server part. This commit does the following: * Add an API for the user to accept or refuse a video ownership * Add validators to ensure security access * Add a query to load a specific video change ownership request * [#510] A user can validate an ownership requests sent to him - web The user can accept or refuse any ownership request that was sent to him. This commit focus only on the web part. This commit does the following: * Add a page to list user ownership changes * Add actions to accept or refuse them * When accepting, show a modal requiring the channel to send the video * Correct lint - to squash * [#510] PR reviews - to squash This commit does the following: * Search parameter for user autocompletion is required from middleware directly * [#510] PR reviews - to squash with creation in database commit This commit does the following: * Add the status attribute in model * Set this attribute on instance creation * Use AccountModel method `loadLocalByName` * [#510] PR reviews - to squash with fetch ownership This commit does the following: * Add the scope `FULL` for database queries with includes * Add classic pagination middlewares * [#510] PR reviews - to squash with ownership validation - server This commit does the following: * Add a middleware to validate whether a user can validate an ownership * Change the ownership status instead of deleting the row * [#510] PR reviews - to squash with ownership validation - client This commit does the following: * Correct indentation of html files with two-spaces indentation * Use event emitter instead of function for accept event * Update the sort of ownership change table for a decreasing order by creation date * Add the status in ownership change table * Use classic method syntax * code style - to squash * Add new user right - to squash * Move the change to my-account instead of video-watch - to squash As requested in pull-request, move the action to change ownership into my videos page. The rest of the logic was not really changed. This commit does the following: - Move the modal into my video page - Create the generic component `button` to keep some styles and logic * [#510] Add tests for the new feature To avoid regression, we add tests for all api of ownership change. This commit does the following: - Create an end-to-end test for ownership change - Divide it to one test per request * [#510] Do not send twice the same request to avoid spam We can send several time the same request to change ownership. However, it will spam the user. To avoid this, we do not save a request already existing in database. This commit does the following: - Check whether the request exist in database - Add tests to verify this new condition * [#510] Change icons Change icons so they remains logic with the rest of the application. This commit does the following: - Add svg for missing icons - Add icons in `my-button` component - Use these new icons * [#510] Add control about the user quota The user should be able to accept a new video only if his quota allows it. This commit does the following: - Update the middleware to control the quota - Add tests verifying the control * Correct merge - Use new modal system - Move button to new directory `buttons` * PR reviews - to squash
2018-09-04 08:57:13 +02:00
usersRouter.get('/autocomplete',
userAutocompleteValidator,
asyncMiddleware(autocompleteUsers)
)
2017-05-15 22:22:03 +02:00
usersRouter.get('/',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-05-15 22:22:03 +02:00
paginationValidator,
usersSortValidator,
2018-01-17 10:50:33 +01:00
setDefaultSort,
setDefaultPagination,
usersListValidator,
2017-10-25 11:55:06 +02:00
asyncMiddleware(listUsers)
2016-08-16 22:31:45 +02:00
)
2018-08-08 14:58:21 +02:00
usersRouter.post('/:id/block',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
asyncMiddleware(usersBlockingValidator),
2019-07-30 09:59:19 +02:00
ensureCanManageUser,
2018-08-08 14:58:21 +02:00
asyncMiddleware(blockUser)
)
usersRouter.post('/:id/unblock',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
asyncMiddleware(usersBlockingValidator),
2019-07-30 09:59:19 +02:00
ensureCanManageUser,
2018-08-08 14:58:21 +02:00
asyncMiddleware(unblockUser)
)
2017-09-05 21:29:39 +02:00
usersRouter.get('/:id',
2018-04-16 10:48:17 +02:00
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 17:30:46 +01:00
asyncMiddleware(usersGetValidator),
2017-09-05 21:29:39 +02:00
getUser
)
2017-05-15 22:22:03 +02:00
usersRouter.post('/',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 17:30:46 +01:00
asyncMiddleware(usersAddValidator),
2018-06-13 14:27:40 +02:00
asyncRetryTransactionMiddleware(createUser)
)
2017-05-15 22:22:03 +02:00
usersRouter.post('/register',
signupRateLimiter,
2017-11-27 17:30:46 +01:00
asyncMiddleware(ensureUserRegistrationAllowed),
ensureUserRegistrationAllowedForIP,
2017-11-27 17:30:46 +01:00
asyncMiddleware(usersRegisterValidator),
2018-06-13 14:27:40 +02:00
asyncRetryTransactionMiddleware(registerUser)
)
2017-05-15 22:22:03 +02:00
usersRouter.put('/:id',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 17:30:46 +01:00
asyncMiddleware(usersUpdateValidator),
2019-07-30 09:59:19 +02:00
ensureCanManageUser,
2017-10-25 11:55:06 +02:00
asyncMiddleware(updateUser)
)
2017-05-15 22:22:03 +02:00
usersRouter.delete('/:id',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 17:30:46 +01:00
asyncMiddleware(usersRemoveValidator),
2019-07-30 09:59:19 +02:00
ensureCanManageUser,
2017-10-25 11:55:06 +02:00
asyncMiddleware(removeUser)
)
2016-08-05 16:09:39 +02:00
2018-01-30 13:27:07 +01:00
usersRouter.post('/ask-reset-password',
asyncMiddleware(usersAskResetPasswordValidator),
asyncMiddleware(askResetUserPassword)
)
usersRouter.post('/:id/reset-password',
asyncMiddleware(usersResetPasswordValidator),
asyncMiddleware(resetUserPassword)
)
usersRouter.post('/ask-send-verify-email',
askSendEmailLimiter,
asyncMiddleware(usersAskSendVerifyEmailValidator),
2019-06-11 11:54:33 +02:00
asyncMiddleware(reSendVerifyUserEmail)
)
usersRouter.post('/:id/verify-email',
asyncMiddleware(usersVerifyEmailValidator),
asyncMiddleware(verifyUserEmail)
)
2016-03-21 11:56:33 +01:00
// ---------------------------------------------------------------------------
2017-05-15 22:22:03 +02:00
export {
usersRouter
}
2016-03-21 11:56:33 +01:00
// ---------------------------------------------------------------------------
2018-06-13 14:27:40 +02:00
async function createUser (req: express.Request, res: express.Response) {
const body: UserCreate = req.body
const userToCreate = new UserModel({
username: body.username,
password: body.password,
email: body.email,
nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
autoPlayVideo: true,
role: body.role,
videoQuota: body.videoQuota,
2019-04-15 10:49:46 +02:00
videoQuotaDaily: body.videoQuotaDaily,
adminFlags: body.adminFlags || UserAdminFlag.NONE
2019-08-20 19:05:31 +02:00
}) as MUser
// NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
const createPassword = userToCreate.password === ''
if (createPassword) {
userToCreate.password = await generateRandomString(20)
}
const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
userToCreate,
channelNames: body.channelName && { name: body.channelName, displayName: body.channelName }
})
2017-10-25 11:55:06 +02:00
2018-09-19 17:02:16 +02:00
auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
2017-11-10 14:48:08 +01:00
logger.info('User %s with its channel and account created.', body.username)
if (createPassword) {
// this will send an email for newly created users, so then can set their first password.
logger.info('Sending to user %s a create password email', body.username)
const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
}
2019-12-06 15:59:12 +01:00
Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
2020-07-02 14:23:50 +02:00
return res.json({
2018-06-13 14:27:40 +02:00
user: {
id: user.id,
account: {
2019-05-31 14:02:26 +02:00
id: account.id
2018-06-13 14:27:40 +02:00
}
2021-07-13 14:23:01 +02:00
} as UserCreateResult
})
2017-11-16 18:40:50 +01:00
}
2018-06-13 14:27:40 +02:00
async function registerUser (req: express.Request, res: express.Response) {
const body: UserRegister = req.body
2017-09-06 16:35:40 +02:00
const userToCreate = new UserModel({
2017-09-06 16:35:40 +02:00
username: body.username,
password: body.password,
email: body.email,
nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
autoPlayVideo: true,
role: UserRole.USER,
videoQuota: CONFIG.USER.VIDEO_QUOTA,
videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
2017-09-06 16:35:40 +02:00
})
2019-12-06 15:59:12 +01:00
const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
userToCreate: userToCreate,
userDisplayName: body.displayName || undefined,
channelNames: body.channel
})
2017-11-16 18:40:50 +01:00
auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
2017-11-16 18:40:50 +01:00
logger.info('User %s with its channel and account registered.', body.username)
2018-06-13 14:27:40 +02:00
if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
await sendVerifyUserEmail(user)
}
Notifier.Instance.notifyOnNewUserRegistration(user)
2019-12-06 15:59:12 +01:00
Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel })
return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
2017-09-06 16:35:40 +02:00
}
2019-03-19 10:35:15 +01:00
async function unblockUser (req: express.Request, res: express.Response) {
const user = res.locals.user
2018-08-08 14:58:21 +02:00
await changeUserBlock(res, user, false)
2019-12-06 15:59:12 +01:00
Hooks.runAction('action:api.user.unblocked', { user })
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-08-08 14:58:21 +02:00
}
async function blockUser (req: express.Request, res: express.Response) {
2019-03-19 10:35:15 +01:00
const user = res.locals.user
2018-08-08 17:36:10 +02:00
const reason = req.body.reason
2018-08-08 14:58:21 +02:00
2018-08-08 17:36:10 +02:00
await changeUserBlock(res, user, true, reason)
2018-08-08 14:58:21 +02:00
2019-12-06 15:59:12 +01:00
Hooks.runAction('action:api.user.blocked', { user })
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-08-08 14:58:21 +02:00
}
function getUser (req: express.Request, res: express.Response) {
2019-04-15 10:49:46 +02:00
return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
2017-09-05 21:29:39 +02:00
}
async function autocompleteUsers (req: express.Request, res: express.Response) {
2018-09-04 10:22:10 +02:00
const resultList = await UserModel.autoComplete(req.query.search as string)
Users can change ownership of their video [#510] (#888) * [#510] Create a new route to get the list of user names To be able to transfer ownership to a user, we need to be able to select him from the list of users. Because the list could be too big, we add a autocomplete feature. This commit does the following: * Add a API endpoint to get a list of user names by searching its name * [#510] The user can choose the next owner of the video To be able to transfer ownership to a user, we need the owner to be able to select the user. The server can autocomplete the name of the user to give the ownership. We add a dialog for the user to actually select it. This commit does the following: * Create a modal for the owner to select the next one * Opens this modal with a button into the menu *more* * Make the dependency injection * [#510] When the user choose the next owner, create a request in database For the change of ownership to happen, we need to store the temporary requests. When the user make the request, save it to database. This commit does the following: * Create the model to persist change ownership requests * Add an API to manage ownership operations * Add a route to persist an ownership request * [#510] A user can fetch its ownership requests sent to him To be able to accept or refuse a change of ownership, the user must be able to fetch them. This commit does the following: * Add an API to list ownership for a user * Add the query to database model * [#510] A user can validate an ownership requests sent to him - server The user can accept or refuse any ownership request that was sent to him. This commit focus only on the server part. This commit does the following: * Add an API for the user to accept or refuse a video ownership * Add validators to ensure security access * Add a query to load a specific video change ownership request * [#510] A user can validate an ownership requests sent to him - web The user can accept or refuse any ownership request that was sent to him. This commit focus only on the web part. This commit does the following: * Add a page to list user ownership changes * Add actions to accept or refuse them * When accepting, show a modal requiring the channel to send the video * Correct lint - to squash * [#510] PR reviews - to squash This commit does the following: * Search parameter for user autocompletion is required from middleware directly * [#510] PR reviews - to squash with creation in database commit This commit does the following: * Add the status attribute in model * Set this attribute on instance creation * Use AccountModel method `loadLocalByName` * [#510] PR reviews - to squash with fetch ownership This commit does the following: * Add the scope `FULL` for database queries with includes * Add classic pagination middlewares * [#510] PR reviews - to squash with ownership validation - server This commit does the following: * Add a middleware to validate whether a user can validate an ownership * Change the ownership status instead of deleting the row * [#510] PR reviews - to squash with ownership validation - client This commit does the following: * Correct indentation of html files with two-spaces indentation * Use event emitter instead of function for accept event * Update the sort of ownership change table for a decreasing order by creation date * Add the status in ownership change table * Use classic method syntax * code style - to squash * Add new user right - to squash * Move the change to my-account instead of video-watch - to squash As requested in pull-request, move the action to change ownership into my videos page. The rest of the logic was not really changed. This commit does the following: - Move the modal into my video page - Create the generic component `button` to keep some styles and logic * [#510] Add tests for the new feature To avoid regression, we add tests for all api of ownership change. This commit does the following: - Create an end-to-end test for ownership change - Divide it to one test per request * [#510] Do not send twice the same request to avoid spam We can send several time the same request to change ownership. However, it will spam the user. To avoid this, we do not save a request already existing in database. This commit does the following: - Check whether the request exist in database - Add tests to verify this new condition * [#510] Change icons Change icons so they remains logic with the rest of the application. This commit does the following: - Add svg for missing icons - Add icons in `my-button` component - Use these new icons * [#510] Add control about the user quota The user should be able to accept a new video only if his quota allows it. This commit does the following: - Update the middleware to control the quota - Add tests verifying the control * Correct merge - Use new modal system - Move button to new directory `buttons` * PR reviews - to squash
2018-09-04 08:57:13 +02:00
return res.json(resultList)
}
async function listUsers (req: express.Request, res: express.Response) {
const resultList = await UserModel.listForApi({
start: req.query.start,
count: req.query.count,
sort: req.query.sort,
search: req.query.search,
blocked: req.query.blocked
})
2017-10-25 11:55:06 +02:00
2019-04-15 10:49:46 +02:00
return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
}
async function removeUser (req: express.Request, res: express.Response) {
2019-03-19 10:35:15 +01:00
const user = res.locals.user
2017-10-25 11:55:06 +02:00
2018-09-19 17:02:16 +02:00
auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
2021-02-18 14:44:12 +01:00
await sequelizeTypescript.transaction(async t => {
// Use a transaction to avoid inconsistencies with hooks (account/channel deletion & federation)
await user.destroy({ transaction: t })
})
2019-12-06 15:59:12 +01:00
Hooks.runAction('action:api.user.deleted', { user })
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
async function updateUser (req: express.Request, res: express.Response) {
2017-09-05 21:29:39 +02:00
const body: UserUpdate = req.body
2019-03-19 10:35:15 +01:00
const userToUpdate = res.locals.user
const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
2017-09-05 21:29:39 +02:00
2021-05-12 14:09:04 +02:00
const keysToUpdate: (keyof UserUpdate)[] = [
'password',
'email',
'emailVerified',
'videoQuota',
'videoQuotaDaily',
'role',
'adminFlags',
'pluginAuth'
]
for (const key of keysToUpdate) {
if (body[key] !== undefined) userToUpdate.set(key, body[key])
}
2017-09-05 21:29:39 +02:00
const user = await userToUpdate.save()
2017-10-25 11:55:06 +02:00
// Destroy user token to refresh rights
if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
2019-12-06 15:59:12 +01:00
Hooks.runAction('action:api.user.updated', { user })
// Don't need to send this update to followers, these attributes are not federated
2018-01-03 16:38:50 +01:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2017-09-05 21:29:39 +02:00
}
2019-03-19 10:35:15 +01:00
async function askResetUserPassword (req: express.Request, res: express.Response) {
const user = res.locals.user
2018-01-30 13:27:07 +01:00
const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
2019-04-11 11:33:44 +02:00
const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
2018-01-30 13:27:07 +01:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-01-30 13:27:07 +01:00
}
2019-03-19 10:35:15 +01:00
async function resetUserPassword (req: express.Request, res: express.Response) {
const user = res.locals.user
2018-01-30 13:27:07 +01:00
user.password = req.body.password
await user.save()
2020-08-12 09:15:31 +02:00
await Redis.Instance.removePasswordVerificationString(user.id)
2018-01-30 13:27:07 +01:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-01-30 13:27:07 +01:00
}
2019-06-11 11:54:33 +02:00
async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
2019-03-19 10:35:15 +01:00
const user = res.locals.user
await sendVerifyUserEmail(user)
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
2019-03-19 10:35:15 +01:00
async function verifyUserEmail (req: express.Request, res: express.Response) {
const user = res.locals.user
user.emailVerified = true
2019-06-11 11:54:33 +02:00
if (req.body.isPendingEmail === true) {
user.email = user.pendingEmail
user.pendingEmail = null
}
await user.save()
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
2019-08-15 11:53:26 +02:00
async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
2018-08-08 14:58:21 +02:00
const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
user.blocked = block
2018-08-08 17:36:10 +02:00
user.blockedReason = reason || null
2018-08-08 14:58:21 +02:00
await sequelizeTypescript.transaction(async t => {
await OAuthTokenModel.deleteUserToken(user.id, t)
2018-08-08 14:58:21 +02:00
await user.save({ transaction: t })
})
2018-08-08 17:36:10 +02:00
await Emailer.Instance.addUserBlockJob(user, block, reason)
auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
2018-08-08 14:58:21 +02:00
}