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