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