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

395 lines
12 KiB
TypeScript
Raw Normal View History

2017-06-05 14:53:49 -05:00
import * as express from 'express'
2018-03-29 03:58:24 -05:00
import * as RateLimit from 'express-rate-limit'
2018-08-16 04:26:22 -05:00
import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared'
import { logger } from '../../../helpers/logger'
import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
import { WEBSERVER } from '../../../initializers/constants'
2018-08-16 04:26:22 -05:00
import { Emailer } from '../../../lib/emailer'
import { Redis } from '../../../lib/redis'
2019-06-11 04:54:33 -05:00
import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
2017-05-15 15:22:03 -05:00
import {
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,
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,
usersListValidator,
2018-01-30 08:16:24 -06:00
usersAddValidator,
usersGetValidator,
usersRegisterValidator,
usersRemoveValidator,
usersSortValidator,
2018-08-16 04:26:22 -05:00
usersUpdateValidator
} from '../../../middlewares'
import {
ensureCanManageUser,
2018-09-19 10:02:16 -05:00
usersAskResetPasswordValidator,
usersAskSendVerifyEmailValidator,
usersBlockingValidator,
usersResetPasswordValidator,
usersVerifyEmailValidator
} from '../../../middlewares/validators'
2018-08-16 04:26:22 -05:00
import { UserModel } from '../../../models/account/user'
2018-09-19 10:02:16 -05:00
import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
2018-08-16 04:26:22 -05:00
import { meRouter } from './me'
2018-09-20 04:31:48 -05:00
import { deleteUserToken } from '../../../lib/oauth-model'
import { myBlocklistRouter } from './my-blocklist'
2019-03-07 10:06:00 -06:00
import { myVideoPlaylistsRouter } from './my-video-playlists'
import { myVideosHistoryRouter } from './my-history'
2018-12-26 03:36:24 -06:00
import { myNotificationsRouter } from './my-notifications'
import { Notifier } from '../../../lib/notifier'
import { mySubscriptionsRouter } from './my-subscriptions'
2019-04-11 04:33:44 -05:00
import { CONFIG } from '../../../initializers/config'
import { sequelizeTypescript } from '../../../initializers/database'
2019-04-15 03:49:46 -05:00
import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
import { UserRegister } from '../../../../shared/models/users/user-register.model'
2020-06-18 03:45:25 -05:00
import { MUser, MUserAccountDefault } from '@server/types/models'
2019-12-06 08:59:12 -06:00
import { Hooks } from '@server/lib/plugins/hooks'
import { tokensRouter } from '@server/controllers/api/users/token'
const auditLogger = auditLoggerFactory('users')
2017-05-15 15:22:03 -05:00
const signupRateLimiter = RateLimit({
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
2020-06-17 03:55:40 -05:00
const askSendEmailLimiter = RateLimit({
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)
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,
usersSortValidator,
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),
2019-07-30 02:59:19 -05:00
ensureCanManageUser,
2018-08-08 07:58:21 -05:00
asyncMiddleware(blockUser)
)
usersRouter.post('/:id/unblock',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
asyncMiddleware(usersBlockingValidator),
2019-07-30 02:59:19 -05:00
ensureCanManageUser,
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),
2019-07-30 02:59:19 -05:00
ensureCanManageUser,
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),
2019-07-30 02:59:19 -05:00
ensureCanManageUser,
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 = 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 03:49:46 -05:00
videoQuotaDaily: body.videoQuotaDaily,
adminFlags: body.adminFlags || UserAdminFlag.NONE
2019-08-20 12:05:31 -05: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)
}
2019-12-06 08:59:12 -06:00
const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
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
await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
}
2019-12-06 08:59:12 -06:00
Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
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
}
}
}).end()
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 = new UserModel({
2017-09-06 09:35:40 -05: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 09:35:40 -05:00
})
2019-12-06 08:59:12 -06:00
const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
userToCreate: 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)
2019-12-06 08:59:12 -06:00
Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel })
2018-06-13 07:27:40 -05:00
return res.type('json').status(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)
2019-12-06 08:59:12 -06:00
Hooks.runAction('action:api.user.unblocked', { user })
2018-08-08 07:58:21 -05:00
return res.status(204).end()
}
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
2019-12-06 08:59:12 -06:00
Hooks.runAction('action:api.user.blocked', { user })
2018-08-08 07:58:21 -05:00
return res.status(204).end()
}
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.listForApi({
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
await user.destroy()
2018-09-19 10:02:16 -05:00
auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
2019-12-06 08:59:12 -06:00
Hooks.runAction('action:api.user.deleted', { user })
2017-10-25 04:55:06 -05:00
return res.sendStatus(204)
}
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
if (body.password !== undefined) userToUpdate.password = body.password
if (body.email !== undefined) userToUpdate.email = body.email
if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
if (body.role !== undefined) userToUpdate.role = body.role
2019-04-15 03:49:46 -05:00
if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
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 deleteUserToken(userToUpdate.id)
auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
2019-12-06 08:59:12 -06: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 09:38:50 -06:00
2017-10-25 04:55:06 -05:00
return res.sendStatus(204)
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(204).end()
}
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()
return res.status(204).end()
}
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(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(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 => {
2018-09-20 04:31:48 -05:00
await 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
}