aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/users/registrations.ts
blob: 5e213d6cced6d91c3bd59b90e0827fa6efbb907a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import express from 'express'
import { Emailer } from '@server/lib/emailer'
import { Hooks } from '@server/lib/plugins/hooks'
import { UserRegistrationModel } from '@server/models/user/user-registration'
import { pick } from '@shared/core-utils'
import {
  HttpStatusCode,
  UserRegister,
  UserRegistrationRequest,
  UserRegistrationState,
  UserRegistrationUpdateState,
  UserRight
} from '@shared/models'
import { auditLoggerFactory, UserAuditView } from '../../../helpers/audit-logger'
import { logger } from '../../../helpers/logger'
import { CONFIG } from '../../../initializers/config'
import { Notifier } from '../../../lib/notifier'
import { buildUser, createUserAccountAndChannelAndPlaylist, sendVerifyRegistrationEmail, sendVerifyUserEmail } from '../../../lib/user'
import {
  acceptOrRejectRegistrationValidator,
  asyncMiddleware,
  asyncRetryTransactionMiddleware,
  authenticate,
  buildRateLimiter,
  ensureUserHasRight,
  ensureUserRegistrationAllowedFactory,
  ensureUserRegistrationAllowedForIP,
  getRegistrationValidator,
  listRegistrationsValidator,
  paginationValidator,
  setDefaultPagination,
  setDefaultSort,
  userRegistrationsSortValidator,
  usersDirectRegistrationValidator,
  usersRequestRegistrationValidator
} from '../../../middlewares'

const auditLogger = auditLoggerFactory('users')

const registrationRateLimiter = buildRateLimiter({
  windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
  max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
  skipFailedRequests: true
})

const registrationsRouter = express.Router()

registrationsRouter.post('/registrations/request',
  registrationRateLimiter,
  asyncMiddleware(ensureUserRegistrationAllowedFactory('request-registration')),
  ensureUserRegistrationAllowedForIP,
  asyncMiddleware(usersRequestRegistrationValidator),
  asyncRetryTransactionMiddleware(requestRegistration)
)

registrationsRouter.post('/registrations/:registrationId/accept',
  authenticate,
  ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS),
  asyncMiddleware(acceptOrRejectRegistrationValidator),
  asyncRetryTransactionMiddleware(acceptRegistration)
)
registrationsRouter.post('/registrations/:registrationId/reject',
  authenticate,
  ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS),
  asyncMiddleware(acceptOrRejectRegistrationValidator),
  asyncRetryTransactionMiddleware(rejectRegistration)
)

registrationsRouter.delete('/registrations/:registrationId',
  authenticate,
  ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS),
  asyncMiddleware(getRegistrationValidator),
  asyncRetryTransactionMiddleware(deleteRegistration)
)

registrationsRouter.get('/registrations',
  authenticate,
  ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS),
  paginationValidator,
  userRegistrationsSortValidator,
  setDefaultSort,
  setDefaultPagination,
  listRegistrationsValidator,
  asyncMiddleware(listRegistrations)
)

registrationsRouter.post('/register',
  registrationRateLimiter,
  asyncMiddleware(ensureUserRegistrationAllowedFactory('direct-registration')),
  ensureUserRegistrationAllowedForIP,
  asyncMiddleware(usersDirectRegistrationValidator),
  asyncRetryTransactionMiddleware(registerUser)
)

// ---------------------------------------------------------------------------

export {
  registrationsRouter
}

// ---------------------------------------------------------------------------

async function requestRegistration (req: express.Request, res: express.Response) {
  const body: UserRegistrationRequest = req.body

  const registration = new UserRegistrationModel({
    ...pick(body, [ 'username', 'password', 'email', 'registrationReason' ]),

    accountDisplayName: body.displayName,
    channelDisplayName: body.channel?.displayName,
    channelHandle: body.channel?.name,

    state: UserRegistrationState.PENDING,

    emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
  })

  await registration.save()

  if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
    await sendVerifyRegistrationEmail(registration)
  }

  Notifier.Instance.notifyOnNewRegistrationRequest(registration)

  Hooks.runAction('action:api.user.requested-registration', { body, registration, req, res })

  return res.json(registration.toFormattedJSON())
}

// ---------------------------------------------------------------------------

async function acceptRegistration (req: express.Request, res: express.Response) {
  const registration = res.locals.userRegistration
  const body: UserRegistrationUpdateState = req.body

  const userToCreate = buildUser({
    username: registration.username,
    password: registration.password,
    email: registration.email,
    emailVerified: registration.emailVerified
  })
  // We already encrypted password in registration model
  userToCreate.skipPasswordEncryption = true

  // TODO: handle conflicts if someone else created a channel handle/user handle/user email between registration and approval

  const { user } = await createUserAccountAndChannelAndPlaylist({
    userToCreate,
    userDisplayName: registration.accountDisplayName,
    channelNames: registration.channelHandle && registration.channelDisplayName
      ? {
        name: registration.channelHandle,
        displayName: registration.channelDisplayName
      }
      : undefined
  })

  registration.userId = user.id
  registration.state = UserRegistrationState.ACCEPTED
  registration.moderationResponse = body.moderationResponse

  await registration.save()

  logger.info('Registration of %s accepted', registration.username)

  if (body.preventEmailDelivery !== true) {
    Emailer.Instance.addUserRegistrationRequestProcessedJob(registration)
  }

  return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}

async function rejectRegistration (req: express.Request, res: express.Response) {
  const registration = res.locals.userRegistration
  const body: UserRegistrationUpdateState = req.body

  registration.state = UserRegistrationState.REJECTED
  registration.moderationResponse = body.moderationResponse

  await registration.save()

  if (body.preventEmailDelivery !== true) {
    Emailer.Instance.addUserRegistrationRequestProcessedJob(registration)
  }

  logger.info('Registration of %s rejected', registration.username)

  return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}

// ---------------------------------------------------------------------------

async function deleteRegistration (req: express.Request, res: express.Response) {
  const registration = res.locals.userRegistration

  await registration.destroy()

  logger.info('Registration of %s deleted', registration.username)

  return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}

// ---------------------------------------------------------------------------

async function listRegistrations (req: express.Request, res: express.Response) {
  const resultList = await UserRegistrationModel.listForApi({
    start: req.query.start,
    count: req.query.count,
    sort: req.query.sort,
    search: req.query.search
  })

  return res.json({
    total: resultList.total,
    data: resultList.data.map(d => d.toFormattedJSON())
  })
}

// ---------------------------------------------------------------------------

async function registerUser (req: express.Request, res: express.Response) {
  const body: UserRegister = req.body

  const userToCreate = buildUser({
    ...pick(body, [ 'username', 'password', 'email' ]),

    emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
  })

  const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
    userToCreate,
    userDisplayName: body.displayName || undefined,
    channelNames: body.channel
  })

  auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
  logger.info('User %s with its channel and account registered.', body.username)

  if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
    await sendVerifyUserEmail(user)
  }

  Notifier.Instance.notifyOnNewDirectRegistration(user)

  Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res })

  return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}