]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users/index.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
490b595a 2import * as RateLimit from 'express-rate-limit'
d03cd8bb
C
3import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared'
4import { logger } from '../../../helpers/logger'
45f1bd72 5import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
c1340a6a 6import { WEBSERVER } from '../../../initializers/constants'
d03cd8bb
C
7import { Emailer } from '../../../lib/emailer'
8import { Redis } from '../../../lib/redis'
d1ab89de 9import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
65fcc311 10import {
f076daa7 11 asyncMiddleware,
90d4bb81 12 asyncRetryTransactionMiddleware,
f076daa7
C
13 authenticate,
14 ensureUserHasRight,
15 ensureUserRegistrationAllowed,
ff2c1fe8 16 ensureUserRegistrationAllowedForIP,
f076daa7
C
17 paginationValidator,
18 setDefaultPagination,
19 setDefaultSort,
20 token,
74d63469 21 userAutocompleteValidator,
f076daa7
C
22 usersAddValidator,
23 usersGetValidator,
24 usersRegisterValidator,
25 usersRemoveValidator,
26 usersSortValidator,
d03cd8bb
C
27 usersUpdateValidator
28} from '../../../middlewares'
d9eaee39 29import {
993cef4b
C
30 usersAskResetPasswordValidator,
31 usersAskSendVerifyEmailValidator,
32 usersBlockingValidator,
33 usersResetPasswordValidator,
a95a4cc8
C
34 usersVerifyEmailValidator,
35 ensureCanManageUser
d9eaee39 36} from '../../../middlewares/validators'
d03cd8bb 37import { UserModel } from '../../../models/account/user'
993cef4b 38import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
d03cd8bb 39import { meRouter } from './me'
f201a749 40import { deleteUserToken } from '../../../lib/oauth-model'
7ad9b984 41import { myBlocklistRouter } from './my-blocklist'
f0a39880 42import { myVideoPlaylistsRouter } from './my-video-playlists'
8b9a525a 43import { myVideosHistoryRouter } from './my-history'
cef534ed 44import { myNotificationsRouter } from './my-notifications'
f7cc67b4 45import { Notifier } from '../../../lib/notifier'
cf405589 46import { mySubscriptionsRouter } from './my-subscriptions'
6dd9de95 47import { CONFIG } from '../../../initializers/config'
74dc3bca 48import { sequelizeTypescript } from '../../../initializers/database'
1eddc9a7 49import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
e590b4a5 50import { UserRegister } from '../../../../shared/models/users/user-register.model'
453e83ea 51import { MUser, MUserAccountDefault } from '@server/typings/models'
6f3fe96f 52import { Hooks } from '@server/lib/plugins/hooks'
80e36cd9
AB
53
54const auditLogger = auditLoggerFactory('users')
65fcc311 55
60919831 56const loginRateLimiter = RateLimit({
c1340a6a
C
57 windowMs: CONFIG.RATES_LIMIT.LOGIN.WINDOW_MS,
58 max: CONFIG.RATES_LIMIT.LOGIN.MAX
59})
60
61// @ts-ignore
62const signupRateLimiter = RateLimit({
63 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
64 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
65 skipFailedRequests: true
490b595a 66})
c5911fd3 67
60919831 68// @ts-ignore
288fe385 69const askSendEmailLimiter = new RateLimit({
c1340a6a
C
70 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
71 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
288fe385
C
72})
73
65fcc311 74const usersRouter = express.Router()
cef534ed 75usersRouter.use('/', myNotificationsRouter)
cf405589 76usersRouter.use('/', mySubscriptionsRouter)
7ad9b984 77usersRouter.use('/', myBlocklistRouter)
8b9a525a 78usersRouter.use('/', myVideosHistoryRouter)
f0a39880 79usersRouter.use('/', myVideoPlaylistsRouter)
06a05d5f 80usersRouter.use('/', meRouter)
9bd26629 81
74d63469
GR
82usersRouter.get('/autocomplete',
83 userAutocompleteValidator,
84 asyncMiddleware(autocompleteUsers)
85)
86
65fcc311 87usersRouter.get('/',
86d13ec2
C
88 authenticate,
89 ensureUserHasRight(UserRight.MANAGE_USERS),
65fcc311
C
90 paginationValidator,
91 usersSortValidator,
1174a847 92 setDefaultSort,
f05a1c30 93 setDefaultPagination,
eb080476 94 asyncMiddleware(listUsers)
5c39adb7
C
95)
96
e6921918
C
97usersRouter.post('/:id/block',
98 authenticate,
99 ensureUserHasRight(UserRight.MANAGE_USERS),
100 asyncMiddleware(usersBlockingValidator),
a95a4cc8 101 ensureCanManageUser,
e6921918
C
102 asyncMiddleware(blockUser)
103)
104usersRouter.post('/:id/unblock',
105 authenticate,
106 ensureUserHasRight(UserRight.MANAGE_USERS),
107 asyncMiddleware(usersBlockingValidator),
a95a4cc8 108 ensureCanManageUser,
e6921918
C
109 asyncMiddleware(unblockUser)
110)
111
8094a898 112usersRouter.get('/:id',
94ff4c23
C
113 authenticate,
114 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 115 asyncMiddleware(usersGetValidator),
8094a898
C
116 getUser
117)
118
65fcc311
C
119usersRouter.post('/',
120 authenticate,
954605a8 121 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 122 asyncMiddleware(usersAddValidator),
90d4bb81 123 asyncRetryTransactionMiddleware(createUser)
9bd26629
C
124)
125
65fcc311 126usersRouter.post('/register',
c1340a6a 127 signupRateLimiter,
a2431b7d 128 asyncMiddleware(ensureUserRegistrationAllowed),
ff2c1fe8 129 ensureUserRegistrationAllowedForIP,
a2431b7d 130 asyncMiddleware(usersRegisterValidator),
90d4bb81 131 asyncRetryTransactionMiddleware(registerUser)
2c2e9092
C
132)
133
65fcc311
C
134usersRouter.put('/:id',
135 authenticate,
954605a8 136 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 137 asyncMiddleware(usersUpdateValidator),
a95a4cc8 138 ensureCanManageUser,
eb080476 139 asyncMiddleware(updateUser)
9bd26629
C
140)
141
65fcc311
C
142usersRouter.delete('/:id',
143 authenticate,
954605a8 144 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 145 asyncMiddleware(usersRemoveValidator),
a95a4cc8 146 ensureCanManageUser,
eb080476 147 asyncMiddleware(removeUser)
9bd26629 148)
6606150c 149
ecb4e35f
C
150usersRouter.post('/ask-reset-password',
151 asyncMiddleware(usersAskResetPasswordValidator),
152 asyncMiddleware(askResetUserPassword)
153)
154
155usersRouter.post('/:id/reset-password',
156 asyncMiddleware(usersResetPasswordValidator),
157 asyncMiddleware(resetUserPassword)
158)
159
d9eaee39 160usersRouter.post('/ask-send-verify-email',
288fe385 161 askSendEmailLimiter,
d9eaee39 162 asyncMiddleware(usersAskSendVerifyEmailValidator),
d1ab89de 163 asyncMiddleware(reSendVerifyUserEmail)
d9eaee39
JM
164)
165
166usersRouter.post('/:id/verify-email',
167 asyncMiddleware(usersVerifyEmailValidator),
168 asyncMiddleware(verifyUserEmail)
169)
170
490b595a
C
171usersRouter.post('/token',
172 loginRateLimiter,
173 token,
6f3fe96f 174 tokenSuccess
490b595a 175)
9bd26629 176// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
9457bf88
C
177
178// ---------------------------------------------------------------------------
179
65fcc311
C
180export {
181 usersRouter
182}
9457bf88
C
183
184// ---------------------------------------------------------------------------
185
90d4bb81 186async function createUser (req: express.Request, res: express.Response) {
4771e000 187 const body: UserCreate = req.body
f05a1c30 188 const userToCreate = new UserModel({
4771e000
C
189 username: body.username,
190 password: body.password,
191 email: body.email,
0883b324 192 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
7efe153b 193 autoPlayVideo: true,
954605a8 194 role: body.role,
bee0abff 195 videoQuota: body.videoQuota,
1eddc9a7
C
196 videoQuotaDaily: body.videoQuotaDaily,
197 adminFlags: body.adminFlags || UserAdminFlag.NONE
1ca9f7c3 198 }) as MUser
9bd26629 199
45f1bd72
JL
200 // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
201 const createPassword = userToCreate.password === ''
202 if (createPassword) {
203 userToCreate.password = await generateRandomString(20)
204 }
205
6f3fe96f 206 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
eb080476 207
993cef4b 208 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
38fa2065 209 logger.info('User %s with its channel and account created.', body.username)
f05a1c30 210
45f1bd72
JL
211 if (createPassword) {
212 // this will send an email for newly created users, so then can set their first password.
213 logger.info('Sending to user %s a create password email', body.username)
214 const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
215 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
216 await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
217 }
218
6f3fe96f
C
219 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
220
90d4bb81
C
221 return res.json({
222 user: {
223 id: user.id,
224 account: {
57cfff78 225 id: account.id
90d4bb81
C
226 }
227 }
228 }).end()
47e0652b
C
229}
230
90d4bb81 231async function registerUser (req: express.Request, res: express.Response) {
e590b4a5 232 const body: UserRegister = req.body
77a5501f 233
80e36cd9 234 const userToCreate = new UserModel({
77a5501f
C
235 username: body.username,
236 password: body.password,
237 email: body.email,
0883b324 238 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
7efe153b 239 autoPlayVideo: true,
954605a8 240 role: UserRole.USER,
bee0abff 241 videoQuota: CONFIG.USER.VIDEO_QUOTA,
d9eaee39
JM
242 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
243 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
77a5501f
C
244 })
245
6f3fe96f 246 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
1f20622f
C
247 userToCreate: userToCreate,
248 userDisplayName: body.displayName || undefined,
249 channelNames: body.channel
250 })
47e0652b 251
80e36cd9 252 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
47e0652b 253 logger.info('User %s with its channel and account registered.', body.username)
90d4bb81 254
d9eaee39
JM
255 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
256 await sendVerifyUserEmail(user)
257 }
258
f7cc67b4
C
259 Notifier.Instance.notifyOnNewUserRegistration(user)
260
6f3fe96f
C
261 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel })
262
90d4bb81 263 return res.type('json').status(204).end()
77a5501f
C
264}
265
dae86118
C
266async function unblockUser (req: express.Request, res: express.Response) {
267 const user = res.locals.user
e6921918
C
268
269 await changeUserBlock(res, user, false)
270
6f3fe96f
C
271 Hooks.runAction('action:api.user.unblocked', { user })
272
e6921918
C
273 return res.status(204).end()
274}
275
b426edd4 276async function blockUser (req: express.Request, res: express.Response) {
dae86118 277 const user = res.locals.user
eacb25c4 278 const reason = req.body.reason
e6921918 279
eacb25c4 280 await changeUserBlock(res, user, true, reason)
e6921918 281
6f3fe96f
C
282 Hooks.runAction('action:api.user.blocked', { user })
283
e6921918
C
284 return res.status(204).end()
285}
286
b426edd4 287function getUser (req: express.Request, res: express.Response) {
1eddc9a7 288 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
8094a898
C
289}
290
b426edd4 291async function autocompleteUsers (req: express.Request, res: express.Response) {
5cf84858 292 const resultList = await UserModel.autoComplete(req.query.search as string)
74d63469
GR
293
294 return res.json(resultList)
295}
296
b426edd4 297async function listUsers (req: express.Request, res: express.Response) {
24b9417c 298 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort, req.query.search)
eb080476 299
1eddc9a7 300 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
9bd26629
C
301}
302
b426edd4 303async function removeUser (req: express.Request, res: express.Response) {
dae86118 304 const user = res.locals.user
eb080476
C
305
306 await user.destroy()
307
993cef4b 308 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
80e36cd9 309
6f3fe96f
C
310 Hooks.runAction('action:api.user.deleted', { user })
311
eb080476 312 return res.sendStatus(204)
9bd26629
C
313}
314
b426edd4 315async function updateUser (req: express.Request, res: express.Response) {
8094a898 316 const body: UserUpdate = req.body
dae86118 317 const userToUpdate = res.locals.user
80e36cd9
AB
318 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
319 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
8094a898 320
b426edd4 321 if (body.password !== undefined) userToUpdate.password = body.password
80e36cd9 322 if (body.email !== undefined) userToUpdate.email = body.email
fc2ec87a 323 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
80e36cd9 324 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
bee0abff 325 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
80e36cd9 326 if (body.role !== undefined) userToUpdate.role = body.role
1eddc9a7 327 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
8094a898 328
80e36cd9 329 const user = await userToUpdate.save()
eb080476 330
f8b8c36b 331 // Destroy user token to refresh rights
b426edd4 332 if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
f8b8c36b 333
91411dba 334 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
80e36cd9 335
6f3fe96f
C
336 Hooks.runAction('action:api.user.updated', { user })
337
b426edd4 338 // Don't need to send this update to followers, these attributes are not federated
265ba139 339
eb080476 340 return res.sendStatus(204)
8094a898
C
341}
342
dae86118
C
343async function askResetUserPassword (req: express.Request, res: express.Response) {
344 const user = res.locals.user
ecb4e35f
C
345
346 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
6dd9de95 347 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
b426edd4 348 await Emailer.Instance.addPasswordResetEmailJob(user.email, url)
ecb4e35f
C
349
350 return res.status(204).end()
351}
352
dae86118
C
353async function resetUserPassword (req: express.Request, res: express.Response) {
354 const user = res.locals.user
ecb4e35f
C
355 user.password = req.body.password
356
357 await user.save()
358
359 return res.status(204).end()
360}
361
d1ab89de 362async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
dae86118 363 const user = res.locals.user
d9eaee39
JM
364
365 await sendVerifyUserEmail(user)
366
367 return res.status(204).end()
368}
369
dae86118
C
370async function verifyUserEmail (req: express.Request, res: express.Response) {
371 const user = res.locals.user
d9eaee39
JM
372 user.emailVerified = true
373
d1ab89de
C
374 if (req.body.isPendingEmail === true) {
375 user.email = user.pendingEmail
376 user.pendingEmail = null
377 }
378
d9eaee39
JM
379 await user.save()
380
381 return res.status(204).end()
382}
383
6f3fe96f
C
384function tokenSuccess (req: express.Request) {
385 const username = req.body.username
386
387 Hooks.runAction('action:api.user.oauth2-got-token', { username, ip: req.ip })
9457bf88 388}
e6921918 389
453e83ea 390async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
e6921918
C
391 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
392
393 user.blocked = block
eacb25c4 394 user.blockedReason = reason || null
e6921918
C
395
396 await sequelizeTypescript.transaction(async t => {
f201a749 397 await deleteUserToken(user.id, t)
e6921918
C
398
399 await user.save({ transaction: t })
400 })
401
eacb25c4
C
402 await Emailer.Instance.addUserBlockJob(user, block, reason)
403
91411dba 404 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
e6921918 405}