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