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

399 lines
12 KiB
TypeScript
Raw Normal View History

2021-08-27 07:32:44 -05:00
import express from 'express'
2020-07-24 08:05:51 -05:00
import { tokensRouter } from '@server/controllers/api/users/token'
import { Hooks } from '@server/lib/plugins/hooks'
import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
import { MUserAccountDefault } from '@server/types/models'
import { pick } from '@shared/core-utils'
import { HttpStatusCode, UserCreate, UserCreateResult, UserRegister, UserRight, UserUpdate } from '@shared/models'
2020-07-24 08:05:51 -05:00
import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
2018-08-16 04:26:22 -05:00
import { logger } from '../../../helpers/logger'
import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
2020-07-24 08:05:51 -05:00
import { CONFIG } from '../../../initializers/config'
import { WEBSERVER } from '../../../initializers/constants'
2020-07-24 08:05:51 -05:00
import { sequelizeTypescript } from '../../../initializers/database'
2018-08-16 04:26:22 -05:00
import { Emailer } from '../../../lib/emailer'
2020-07-24 08:05:51 -05:00
import { Notifier } from '../../../lib/notifier'
2018-08-16 04:26:22 -05:00
import { Redis } from '../../../lib/redis'
import { buildUser, createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
2017-05-15 15:22:03 -05:00
import {
adminUsersSortValidator,
2018-01-30 08:16:24 -06:00
asyncMiddleware,
2018-06-13 07:27:40 -05:00
asyncRetryTransactionMiddleware,
2018-01-30 08:16:24 -06:00
authenticate,
buildRateLimiter,
2018-01-30 08:16:24 -06:00
ensureUserHasRight,
ensureUserRegistrationAllowed,
ensureUserRegistrationAllowedForIP,
2018-01-30 08:16:24 -06: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 01:57:13 -05:00
userAutocompleteValidator,
2018-01-30 08:16:24 -06:00
usersAddValidator,
usersGetValidator,
2020-07-24 08:05:51 -05:00
usersListValidator,
2018-01-30 08:16:24 -06:00
usersRegisterValidator,
usersRemoveValidator,
2018-08-16 04:26:22 -05:00
usersUpdateValidator
} from '../../../middlewares'
import {
2022-09-07 10:18:29 -05:00
ensureCanModerateUser,
2018-09-19 10:02:16 -05:00
usersAskResetPasswordValidator,
usersAskSendVerifyEmailValidator,
usersBlockingValidator,
usersResetPasswordValidator,
usersVerifyEmailValidator
} from '../../../middlewares/validators'
2021-05-11 04:15:29 -05:00
import { UserModel } from '../../../models/user/user'
2018-08-16 04:26:22 -05:00
import { meRouter } from './me'
2020-07-24 08:05:51 -05:00
import { myAbusesRouter } from './my-abuses'
import { myBlocklistRouter } from './my-blocklist'
import { myVideosHistoryRouter } from './my-history'
2018-12-26 03:36:24 -06:00
import { myNotificationsRouter } from './my-notifications'
import { mySubscriptionsRouter } from './my-subscriptions'
2020-07-24 08:05:51 -05:00
import { myVideoPlaylistsRouter } from './my-video-playlists'
const auditLogger = auditLoggerFactory('users')
2017-05-15 15:22:03 -05:00
const signupRateLimiter = buildRateLimiter({
windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
skipFailedRequests: true
2018-03-29 03:58:24 -05:00
})
2017-12-29 12:10:13 -06:00
const askSendEmailLimiter = buildRateLimiter({
windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
})
2017-05-15 15:22:03 -05:00
const usersRouter = express.Router()
usersRouter.use('/', tokensRouter)
2018-12-26 03:36:24 -06:00
usersRouter.use('/', myNotificationsRouter)
usersRouter.use('/', mySubscriptionsRouter)
usersRouter.use('/', myBlocklistRouter)
usersRouter.use('/', myVideosHistoryRouter)
2019-03-07 10:06:00 -06:00
usersRouter.use('/', myVideoPlaylistsRouter)
2020-07-24 08:05:51 -05: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 01:57:13 -05:00
usersRouter.get('/autocomplete',
userAutocompleteValidator,
asyncMiddleware(autocompleteUsers)
)
2017-05-15 15:22:03 -05:00
usersRouter.get('/',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-05-15 15:22:03 -05:00
paginationValidator,
adminUsersSortValidator,
2018-01-17 03:50:33 -06:00
setDefaultSort,
setDefaultPagination,
usersListValidator,
2017-10-25 04:55:06 -05:00
asyncMiddleware(listUsers)
2016-08-16 15:31:45 -05:00
)
2018-08-08 07:58:21 -05:00
usersRouter.post('/:id/block',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
asyncMiddleware(usersBlockingValidator),
2022-09-07 10:18:29 -05:00
ensureCanModerateUser,
2018-08-08 07:58:21 -05:00
asyncMiddleware(blockUser)
)
usersRouter.post('/:id/unblock',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
asyncMiddleware(usersBlockingValidator),
2022-09-07 10:18:29 -05:00
ensureCanModerateUser,
2018-08-08 07:58:21 -05:00
asyncMiddleware(unblockUser)
)
2017-09-05 14:29:39 -05:00
usersRouter.get('/:id',
2018-04-16 03:48:17 -05:00
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 10:30:46 -06:00
asyncMiddleware(usersGetValidator),
2017-09-05 14:29:39 -05:00
getUser
)
2017-05-15 15:22:03 -05:00
usersRouter.post('/',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 10:30:46 -06:00
asyncMiddleware(usersAddValidator),
2018-06-13 07:27:40 -05:00
asyncRetryTransactionMiddleware(createUser)
)
2017-05-15 15:22:03 -05:00
usersRouter.post('/register',
signupRateLimiter,
2017-11-27 10:30:46 -06:00
asyncMiddleware(ensureUserRegistrationAllowed),
ensureUserRegistrationAllowedForIP,
2017-11-27 10:30:46 -06:00
asyncMiddleware(usersRegisterValidator),
2018-06-13 07:27:40 -05:00
asyncRetryTransactionMiddleware(registerUser)
)
2017-05-15 15:22:03 -05:00
usersRouter.put('/:id',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 10:30:46 -06:00
asyncMiddleware(usersUpdateValidator),
2022-09-07 10:18:29 -05:00
ensureCanModerateUser,
2017-10-25 04:55:06 -05:00
asyncMiddleware(updateUser)
)
2017-05-15 15:22:03 -05:00
usersRouter.delete('/:id',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
2017-11-27 10:30:46 -06:00
asyncMiddleware(usersRemoveValidator),
2022-09-07 10:18:29 -05:00
ensureCanModerateUser,
2017-10-25 04:55:06 -05:00
asyncMiddleware(removeUser)
)
2016-08-05 09:09:39 -05:00
2018-01-30 06:27:07 -06: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 04:54:33 -05:00
asyncMiddleware(reSendVerifyUserEmail)
)
usersRouter.post('/:id/verify-email',
asyncMiddleware(usersVerifyEmailValidator),
asyncMiddleware(verifyUserEmail)
)
2016-03-21 05:56:33 -05:00
// ---------------------------------------------------------------------------
2017-05-15 15:22:03 -05:00
export {
usersRouter
}
2016-03-21 05:56:33 -05:00
// ---------------------------------------------------------------------------
2018-06-13 07:27:40 -05:00
async function createUser (req: express.Request, res: express.Response) {
const body: UserCreate = req.body
const userToCreate = buildUser({
...pick(body, [ 'username', 'password', 'email', 'role', 'videoQuota', 'videoQuotaDaily', 'adminFlags' ]),
emailVerified: null
})
// 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 04:55:06 -05:00
2018-09-19 10:02:16 -05:00
auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
2017-11-10 07:48:08 -06: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
2021-12-24 03:14:47 -06:00
Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
}
Hooks.runAction('action:api.user.created', { body, user, account, videoChannel, req, res })
2019-12-06 08:59:12 -06:00
2020-07-02 07:23:50 -05:00
return res.json({
2018-06-13 07:27:40 -05:00
user: {
id: user.id,
account: {
2019-05-31 07:02:26 -05:00
id: account.id
2018-06-13 07:27:40 -05:00
}
2021-07-13 07:23:01 -05:00
} as UserCreateResult
})
2017-11-16 11:40:50 -06:00
}
2018-06-13 07:27:40 -05:00
async function registerUser (req: express.Request, res: express.Response) {
const body: UserRegister = req.body
2017-09-06 09:35:40 -05:00
const userToCreate = buildUser({
...pick(body, [ 'username', 'password', 'email' ]),
emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
2017-09-06 09:35:40 -05:00
})
2019-12-06 08:59:12 -06:00
const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
2022-07-13 04:58:01 -05:00
userToCreate,
userDisplayName: body.displayName || undefined,
channelNames: body.channel
})
2017-11-16 11:40:50 -06:00
auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
2017-11-16 11:40:50 -06:00
logger.info('User %s with its channel and account registered.', body.username)
2018-06-13 07:27:40 -05:00
if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
await sendVerifyUserEmail(user)
}
Notifier.Instance.notifyOnNewUserRegistration(user)
Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res })
2019-12-06 08:59:12 -06:00
return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
2017-09-06 09:35:40 -05:00
}
2019-03-19 04:35:15 -05:00
async function unblockUser (req: express.Request, res: express.Response) {
const user = res.locals.user
2018-08-08 07:58:21 -05:00
await changeUserBlock(res, user, false)
Hooks.runAction('action:api.user.unblocked', { user, req, res })
2019-12-06 08:59:12 -06:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-08-08 07:58:21 -05:00
}
async function blockUser (req: express.Request, res: express.Response) {
2019-03-19 04:35:15 -05:00
const user = res.locals.user
2018-08-08 10:36:10 -05:00
const reason = req.body.reason
2018-08-08 07:58:21 -05:00
2018-08-08 10:36:10 -05:00
await changeUserBlock(res, user, true, reason)
2018-08-08 07:58:21 -05:00
Hooks.runAction('action:api.user.blocked', { user, req, res })
2019-12-06 08:59:12 -06:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-08-08 07:58:21 -05:00
}
function getUser (req: express.Request, res: express.Response) {
2019-04-15 03:49:46 -05:00
return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
2017-09-05 14:29:39 -05:00
}
async function autocompleteUsers (req: express.Request, res: express.Response) {
2018-09-04 03:22:10 -05: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 01:57:13 -05:00
return res.json(resultList)
}
async function listUsers (req: express.Request, res: express.Response) {
const resultList = await UserModel.listForAdminApi({
start: req.query.start,
count: req.query.count,
sort: req.query.sort,
search: req.query.search,
blocked: req.query.blocked
})
2017-10-25 04:55:06 -05:00
2019-04-15 03:49:46 -05:00
return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
}
async function removeUser (req: express.Request, res: express.Response) {
2019-03-19 04:35:15 -05:00
const user = res.locals.user
2017-10-25 04:55:06 -05:00
2018-09-19 10:02:16 -05:00
auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
2021-02-18 07:44:12 -06:00
await sequelizeTypescript.transaction(async t => {
// Use a transaction to avoid inconsistencies with hooks (account/channel deletion & federation)
await user.destroy({ transaction: t })
})
Hooks.runAction('action:api.user.deleted', { user, req, res })
2019-12-06 08:59:12 -06:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
async function updateUser (req: express.Request, res: express.Response) {
2017-09-05 14:29:39 -05:00
const body: UserUpdate = req.body
2019-03-19 04:35:15 -05:00
const userToUpdate = res.locals.user
const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
2017-09-05 14:29:39 -05:00
2021-05-12 07:09:04 -05: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 14:29:39 -05:00
const user = await userToUpdate.save()
2017-10-25 04:55:06 -05: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)
Hooks.runAction('action:api.user.updated', { user, req, res })
2019-12-06 08:59:12 -06:00
// Don't need to send this update to followers, these attributes are not federated
2018-01-03 09:38:50 -06:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2017-09-05 14:29:39 -05:00
}
2019-03-19 04:35:15 -05:00
async function askResetUserPassword (req: express.Request, res: express.Response) {
const user = res.locals.user
2018-01-30 06:27:07 -06:00
const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
2019-04-11 04:33:44 -05:00
const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
2018-01-30 06:27:07 -06:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-01-30 06:27:07 -06:00
}
2019-03-19 04:35:15 -05:00
async function resetUserPassword (req: express.Request, res: express.Response) {
const user = res.locals.user
2018-01-30 06:27:07 -06:00
user.password = req.body.password
await user.save()
2020-08-12 02:15:31 -05:00
await Redis.Instance.removePasswordVerificationString(user.id)
2018-01-30 06:27:07 -06:00
return res.status(HttpStatusCode.NO_CONTENT_204).end()
2018-01-30 06:27:07 -06:00
}
2019-06-11 04:54:33 -05:00
async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
2019-03-19 04:35:15 -05:00
const user = res.locals.user
await sendVerifyUserEmail(user)
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
2019-03-19 04:35:15 -05:00
async function verifyUserEmail (req: express.Request, res: express.Response) {
const user = res.locals.user
user.emailVerified = true
2019-06-11 04:54:33 -05: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 04:53:26 -05:00
async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
2018-08-08 07:58:21 -05:00
const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
user.blocked = block
2018-08-08 10:36:10 -05:00
user.blockedReason = reason || null
2018-08-08 07:58:21 -05:00
await sequelizeTypescript.transaction(async t => {
await OAuthTokenModel.deleteUserToken(user.id, t)
2018-08-08 07:58:21 -05:00
await user.save({ transaction: t })
})
2018-08-08 10:36:10 -05:00
await Emailer.Instance.addUserBlockJob(user, block, reason)
auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
2018-08-08 07:58:21 -05:00
}