]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users/index.ts
Fix lazy static route with unknown avatars
[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'
5import { 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'
80e36cd9
AB
51
52const auditLogger = auditLoggerFactory('users')
65fcc311 53
60919831
C
54// FIXME: https://github.com/nfriedly/express-rate-limit/issues/138
55// @ts-ignore
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,
174 success
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
9bd26629
C
198 })
199
1f20622f 200 const { user, account } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
eb080476 201
993cef4b 202 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
38fa2065 203 logger.info('User %s with its channel and account created.', body.username)
f05a1c30 204
90d4bb81
C
205 return res.json({
206 user: {
207 id: user.id,
208 account: {
57cfff78 209 id: account.id
90d4bb81
C
210 }
211 }
212 }).end()
47e0652b
C
213}
214
90d4bb81 215async function registerUser (req: express.Request, res: express.Response) {
e590b4a5 216 const body: UserRegister = req.body
77a5501f 217
80e36cd9 218 const userToCreate = new UserModel({
77a5501f
C
219 username: body.username,
220 password: body.password,
221 email: body.email,
0883b324 222 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
7efe153b 223 autoPlayVideo: true,
954605a8 224 role: UserRole.USER,
bee0abff 225 videoQuota: CONFIG.USER.VIDEO_QUOTA,
d9eaee39
JM
226 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
227 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
77a5501f
C
228 })
229
1f20622f
C
230 const { user } = await createUserAccountAndChannelAndPlaylist({
231 userToCreate: userToCreate,
232 userDisplayName: body.displayName || undefined,
233 channelNames: body.channel
234 })
47e0652b 235
80e36cd9 236 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
47e0652b 237 logger.info('User %s with its channel and account registered.', body.username)
90d4bb81 238
d9eaee39
JM
239 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
240 await sendVerifyUserEmail(user)
241 }
242
f7cc67b4
C
243 Notifier.Instance.notifyOnNewUserRegistration(user)
244
90d4bb81 245 return res.type('json').status(204).end()
77a5501f
C
246}
247
dae86118
C
248async function unblockUser (req: express.Request, res: express.Response) {
249 const user = res.locals.user
e6921918
C
250
251 await changeUserBlock(res, user, false)
252
253 return res.status(204).end()
254}
255
b426edd4 256async function blockUser (req: express.Request, res: express.Response) {
dae86118 257 const user = res.locals.user
eacb25c4 258 const reason = req.body.reason
e6921918 259
eacb25c4 260 await changeUserBlock(res, user, true, reason)
e6921918
C
261
262 return res.status(204).end()
263}
264
b426edd4 265function getUser (req: express.Request, res: express.Response) {
1eddc9a7 266 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
8094a898
C
267}
268
b426edd4 269async function autocompleteUsers (req: express.Request, res: express.Response) {
5cf84858 270 const resultList = await UserModel.autoComplete(req.query.search as string)
74d63469
GR
271
272 return res.json(resultList)
273}
274
b426edd4 275async function listUsers (req: express.Request, res: express.Response) {
24b9417c 276 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort, req.query.search)
eb080476 277
1eddc9a7 278 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
9bd26629
C
279}
280
b426edd4 281async function removeUser (req: express.Request, res: express.Response) {
dae86118 282 const user = res.locals.user
eb080476
C
283
284 await user.destroy()
285
993cef4b 286 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
80e36cd9 287
eb080476 288 return res.sendStatus(204)
9bd26629
C
289}
290
b426edd4 291async function updateUser (req: express.Request, res: express.Response) {
8094a898 292 const body: UserUpdate = req.body
dae86118 293 const userToUpdate = res.locals.user
80e36cd9
AB
294 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
295 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
8094a898 296
b426edd4 297 if (body.password !== undefined) userToUpdate.password = body.password
80e36cd9 298 if (body.email !== undefined) userToUpdate.email = body.email
fc2ec87a 299 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
80e36cd9 300 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
bee0abff 301 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
80e36cd9 302 if (body.role !== undefined) userToUpdate.role = body.role
1eddc9a7 303 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
8094a898 304
80e36cd9 305 const user = await userToUpdate.save()
eb080476 306
f8b8c36b 307 // Destroy user token to refresh rights
b426edd4 308 if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
f8b8c36b 309
91411dba 310 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
80e36cd9 311
b426edd4 312 // Don't need to send this update to followers, these attributes are not federated
265ba139 313
eb080476 314 return res.sendStatus(204)
8094a898
C
315}
316
dae86118
C
317async function askResetUserPassword (req: express.Request, res: express.Response) {
318 const user = res.locals.user
ecb4e35f
C
319
320 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
6dd9de95 321 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
b426edd4 322 await Emailer.Instance.addPasswordResetEmailJob(user.email, url)
ecb4e35f
C
323
324 return res.status(204).end()
325}
326
dae86118
C
327async function resetUserPassword (req: express.Request, res: express.Response) {
328 const user = res.locals.user
ecb4e35f
C
329 user.password = req.body.password
330
331 await user.save()
332
333 return res.status(204).end()
334}
335
d1ab89de 336async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
dae86118 337 const user = res.locals.user
d9eaee39
JM
338
339 await sendVerifyUserEmail(user)
340
341 return res.status(204).end()
342}
343
dae86118
C
344async function verifyUserEmail (req: express.Request, res: express.Response) {
345 const user = res.locals.user
d9eaee39
JM
346 user.emailVerified = true
347
d1ab89de
C
348 if (req.body.isPendingEmail === true) {
349 user.email = user.pendingEmail
350 user.pendingEmail = null
351 }
352
d9eaee39
JM
353 await user.save()
354
355 return res.status(204).end()
356}
357
dae86118 358function success (req: express.Request, res: express.Response) {
9457bf88
C
359 res.end()
360}
e6921918 361
eacb25c4 362async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) {
e6921918
C
363 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
364
365 user.blocked = block
eacb25c4 366 user.blockedReason = reason || null
e6921918
C
367
368 await sequelizeTypescript.transaction(async t => {
f201a749 369 await deleteUserToken(user.id, t)
e6921918
C
370
371 await user.save({ transaction: t })
372 })
373
eacb25c4
C
374 await Emailer.Instance.addUserBlockJob(user, block, reason)
375
91411dba 376 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
e6921918 377}