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

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

  switch (req.method) {
    case 'GET':
      try {
        const {email} = 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, text(key), html(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) {
        console.log(error)
        res.status(400).send()
      }
      break
    default:
      res.status(400).send()
      break
  }
})