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