]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/api/users/index.ts
Correctly fix subtitles import
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users / index.ts
... / ...
CommitLineData
1import * as express from 'express'
2import * as RateLimit from 'express-rate-limit'
3import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared'
4import { logger } from '../../../helpers/logger'
5import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
6import { WEBSERVER } from '../../../initializers/constants'
7import { Emailer } from '../../../lib/emailer'
8import { Redis } from '../../../lib/redis'
9import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
10import {
11 asyncMiddleware,
12 asyncRetryTransactionMiddleware,
13 authenticate,
14 ensureUserHasRight,
15 ensureUserRegistrationAllowed,
16 ensureUserRegistrationAllowedForIP,
17 paginationValidator,
18 setDefaultPagination,
19 setDefaultSort,
20 userAutocompleteValidator,
21 usersAddValidator,
22 usersGetValidator,
23 usersRegisterValidator,
24 usersRemoveValidator,
25 usersSortValidator,
26 usersUpdateValidator
27} from '../../../middlewares'
28import {
29 ensureCanManageUser,
30 usersAskResetPasswordValidator,
31 usersAskSendVerifyEmailValidator,
32 usersBlockingValidator,
33 usersResetPasswordValidator,
34 usersVerifyEmailValidator
35} from '../../../middlewares/validators'
36import { UserModel } from '../../../models/account/user'
37import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
38import { meRouter } from './me'
39import { deleteUserToken } from '../../../lib/oauth-model'
40import { myBlocklistRouter } from './my-blocklist'
41import { myVideoPlaylistsRouter } from './my-video-playlists'
42import { myVideosHistoryRouter } from './my-history'
43import { myNotificationsRouter } from './my-notifications'
44import { Notifier } from '../../../lib/notifier'
45import { mySubscriptionsRouter } from './my-subscriptions'
46import { CONFIG } from '../../../initializers/config'
47import { sequelizeTypescript } from '../../../initializers/database'
48import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
49import { UserRegister } from '../../../../shared/models/users/user-register.model'
50import { MUser, MUserAccountDefault } from '@server/typings/models'
51import { Hooks } from '@server/lib/plugins/hooks'
52import { tokensRouter } from '@server/controllers/api/users/token'
53
54const auditLogger = auditLoggerFactory('users')
55
56// @ts-ignore
57const signupRateLimiter = RateLimit({
58 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
59 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
60 skipFailedRequests: true
61})
62
63// @ts-ignore
64const askSendEmailLimiter = new RateLimit({
65 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
66 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
67})
68
69const usersRouter = express.Router()
70usersRouter.use('/', tokensRouter)
71usersRouter.use('/', myNotificationsRouter)
72usersRouter.use('/', mySubscriptionsRouter)
73usersRouter.use('/', myBlocklistRouter)
74usersRouter.use('/', myVideosHistoryRouter)
75usersRouter.use('/', myVideoPlaylistsRouter)
76usersRouter.use('/', meRouter)
77
78usersRouter.get('/autocomplete',
79 userAutocompleteValidator,
80 asyncMiddleware(autocompleteUsers)
81)
82
83usersRouter.get('/',
84 authenticate,
85 ensureUserHasRight(UserRight.MANAGE_USERS),
86 paginationValidator,
87 usersSortValidator,
88 setDefaultSort,
89 setDefaultPagination,
90 asyncMiddleware(listUsers)
91)
92
93usersRouter.post('/:id/block',
94 authenticate,
95 ensureUserHasRight(UserRight.MANAGE_USERS),
96 asyncMiddleware(usersBlockingValidator),
97 ensureCanManageUser,
98 asyncMiddleware(blockUser)
99)
100usersRouter.post('/:id/unblock',
101 authenticate,
102 ensureUserHasRight(UserRight.MANAGE_USERS),
103 asyncMiddleware(usersBlockingValidator),
104 ensureCanManageUser,
105 asyncMiddleware(unblockUser)
106)
107
108usersRouter.get('/:id',
109 authenticate,
110 ensureUserHasRight(UserRight.MANAGE_USERS),
111 asyncMiddleware(usersGetValidator),
112 getUser
113)
114
115usersRouter.post('/',
116 authenticate,
117 ensureUserHasRight(UserRight.MANAGE_USERS),
118 asyncMiddleware(usersAddValidator),
119 asyncRetryTransactionMiddleware(createUser)
120)
121
122usersRouter.post('/register',
123 signupRateLimiter,
124 asyncMiddleware(ensureUserRegistrationAllowed),
125 ensureUserRegistrationAllowedForIP,
126 asyncMiddleware(usersRegisterValidator),
127 asyncRetryTransactionMiddleware(registerUser)
128)
129
130usersRouter.put('/:id',
131 authenticate,
132 ensureUserHasRight(UserRight.MANAGE_USERS),
133 asyncMiddleware(usersUpdateValidator),
134 ensureCanManageUser,
135 asyncMiddleware(updateUser)
136)
137
138usersRouter.delete('/:id',
139 authenticate,
140 ensureUserHasRight(UserRight.MANAGE_USERS),
141 asyncMiddleware(usersRemoveValidator),
142 ensureCanManageUser,
143 asyncMiddleware(removeUser)
144)
145
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
156usersRouter.post('/ask-send-verify-email',
157 askSendEmailLimiter,
158 asyncMiddleware(usersAskSendVerifyEmailValidator),
159 asyncMiddleware(reSendVerifyUserEmail)
160)
161
162usersRouter.post('/:id/verify-email',
163 asyncMiddleware(usersVerifyEmailValidator),
164 asyncMiddleware(verifyUserEmail)
165)
166
167// ---------------------------------------------------------------------------
168
169export {
170 usersRouter
171}
172
173// ---------------------------------------------------------------------------
174
175async function createUser (req: express.Request, res: express.Response) {
176 const body: UserCreate = req.body
177 const userToCreate = new UserModel({
178 username: body.username,
179 password: body.password,
180 email: body.email,
181 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
182 autoPlayVideo: true,
183 role: body.role,
184 videoQuota: body.videoQuota,
185 videoQuotaDaily: body.videoQuotaDaily,
186 adminFlags: body.adminFlags || UserAdminFlag.NONE
187 }) as MUser
188
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
195 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
196
197 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
198 logger.info('User %s with its channel and account created.', body.username)
199
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
208 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
209
210 return res.json({
211 user: {
212 id: user.id,
213 account: {
214 id: account.id
215 }
216 }
217 }).end()
218}
219
220async function registerUser (req: express.Request, res: express.Response) {
221 const body: UserRegister = req.body
222
223 const userToCreate = new UserModel({
224 username: body.username,
225 password: body.password,
226 email: body.email,
227 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
228 autoPlayVideo: true,
229 role: UserRole.USER,
230 videoQuota: CONFIG.USER.VIDEO_QUOTA,
231 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
232 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
233 })
234
235 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
236 userToCreate: userToCreate,
237 userDisplayName: body.displayName || undefined,
238 channelNames: body.channel
239 })
240
241 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
242 logger.info('User %s with its channel and account registered.', body.username)
243
244 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
245 await sendVerifyUserEmail(user)
246 }
247
248 Notifier.Instance.notifyOnNewUserRegistration(user)
249
250 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel })
251
252 return res.type('json').status(204).end()
253}
254
255async function unblockUser (req: express.Request, res: express.Response) {
256 const user = res.locals.user
257
258 await changeUserBlock(res, user, false)
259
260 Hooks.runAction('action:api.user.unblocked', { user })
261
262 return res.status(204).end()
263}
264
265async function blockUser (req: express.Request, res: express.Response) {
266 const user = res.locals.user
267 const reason = req.body.reason
268
269 await changeUserBlock(res, user, true, reason)
270
271 Hooks.runAction('action:api.user.blocked', { user })
272
273 return res.status(204).end()
274}
275
276function getUser (req: express.Request, res: express.Response) {
277 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
278}
279
280async function autocompleteUsers (req: express.Request, res: express.Response) {
281 const resultList = await UserModel.autoComplete(req.query.search as string)
282
283 return res.json(resultList)
284}
285
286async function listUsers (req: express.Request, res: express.Response) {
287 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort, req.query.search)
288
289 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
290}
291
292async function removeUser (req: express.Request, res: express.Response) {
293 const user = res.locals.user
294
295 await user.destroy()
296
297 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
298
299 Hooks.runAction('action:api.user.deleted', { user })
300
301 return res.sendStatus(204)
302}
303
304async function updateUser (req: express.Request, res: express.Response) {
305 const body: UserUpdate = req.body
306 const userToUpdate = res.locals.user
307 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
308 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
309
310 if (body.password !== undefined) userToUpdate.password = body.password
311 if (body.email !== undefined) userToUpdate.email = body.email
312 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
313 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
314 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
315 if (body.role !== undefined) userToUpdate.role = body.role
316 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
317
318 const user = await userToUpdate.save()
319
320 // Destroy user token to refresh rights
321 if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
322
323 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
324
325 Hooks.runAction('action:api.user.updated', { user })
326
327 // Don't need to send this update to followers, these attributes are not federated
328
329 return res.sendStatus(204)
330}
331
332async function askResetUserPassword (req: express.Request, res: express.Response) {
333 const user = res.locals.user
334
335 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
336 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
337 await Emailer.Instance.addPasswordResetEmailJob(user.email, url)
338
339 return res.status(204).end()
340}
341
342async function resetUserPassword (req: express.Request, res: express.Response) {
343 const user = res.locals.user
344 user.password = req.body.password
345
346 await user.save()
347
348 return res.status(204).end()
349}
350
351async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
352 const user = res.locals.user
353
354 await sendVerifyUserEmail(user)
355
356 return res.status(204).end()
357}
358
359async function verifyUserEmail (req: express.Request, res: express.Response) {
360 const user = res.locals.user
361 user.emailVerified = true
362
363 if (req.body.isPendingEmail === true) {
364 user.email = user.pendingEmail
365 user.pendingEmail = null
366 }
367
368 await user.save()
369
370 return res.status(204).end()
371}
372
373async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
374 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
375
376 user.blocked = block
377 user.blockedReason = reason || null
378
379 await sequelizeTypescript.transaction(async t => {
380 await deleteUserToken(user.id, t)
381
382 await user.save({ transaction: t })
383 })
384
385 await Emailer.Instance.addUserBlockJob(user, block, reason)
386
387 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
388}