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