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