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