aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/users/email-verification.ts
blob: 230aaa9af76f3a34b0779f7853f8bb29e4203146 (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
import express from 'express'
import { HttpStatusCode } from '@shared/models'
import { CONFIG } from '../../../initializers/config'
import { sendVerifyRegistrationEmail, sendVerifyUserEmail } from '../../../lib/user'
import { asyncMiddleware, buildRateLimiter } from '../../../middlewares'
import {
  registrationVerifyEmailValidator,
  usersAskSendVerifyEmailValidator,
  usersVerifyEmailValidator
} from '../../../middlewares/validators'

const askSendEmailLimiter = buildRateLimiter({
  windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
  max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
})

const emailVerificationRouter = express.Router()

emailVerificationRouter.post([ '/ask-send-verify-email', '/registrations/ask-send-verify-email' ],
  askSendEmailLimiter,
  asyncMiddleware(usersAskSendVerifyEmailValidator),
  asyncMiddleware(reSendVerifyUserEmail)
)

emailVerificationRouter.post('/:id/verify-email',
  asyncMiddleware(usersVerifyEmailValidator),
  asyncMiddleware(verifyUserEmail)
)

emailVerificationRouter.post('/registrations/:registrationId/verify-email',
  asyncMiddleware(registrationVerifyEmailValidator),
  asyncMiddleware(verifyRegistrationEmail)
)

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

export {
  emailVerificationRouter
}

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

  if (user) await sendVerifyUserEmail(user)
  else if (registration) await sendVerifyRegistrationEmail(registration)

  return res.status(HttpStatusCode.NO_CONTENT_204).end()
}

async function verifyUserEmail (req: express.Request, res: express.Response) {
  const user = res.locals.user
  user.emailVerified = true

  if (req.body.isPendingEmail === true) {
    user.email = user.pendingEmail
    user.pendingEmail = null
  }

  await user.save()

  return res.status(HttpStatusCode.NO_CONTENT_204).end()
}

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

  await registration.save()

  return res.status(HttpStatusCode.NO_CONTENT_204).end()
}