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