aboutsummaryrefslogtreecommitdiffstats
path: root/pages/api/verify.js
blob: 89bd4cd9c81dcb444c62f7b4af9a078a713a5a93 (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
import dbConnect from 'configs/dbConnect'
import sendMail from 'configs/sendMail'
import User from 'models/User'
import withSession from 'hocs/withSession'
import { subject, text, html } from 'helpers/email'

export default withSession(async (req, res) => {
  await dbConnect()

  switch (req.method) {
    case 'GET':
      try {
        const { email, language: l } = req.session.get('user')
        if (!email) { throw new Error('Something went wrong') }

        const key = await User.getVerificationKey(email)
        if (!key) { throw new Error('Something went wrong') }

        const response = await sendMail(email, subject(l), text(l, key), html(l, key))
        if (!response?.accepted?.length) { throw new Error('Something went wrong') }

        res.status(204).send()
      } catch (error) {
        res.status(400).send()
      }
      break
    case 'POST':
      try {
        if (req.body.key) {
          const user = await User.verifyUser(req.body._id, req.body.key)
          req.session.set('user', user)
          await req.session.save()
          res.status(200).json(user)
        }
      } catch (error) {
        res.status(400).send()
      }
      break
    default:
      res.status(400).send()
      break
  }
})