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

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

  switch (req.method) {
    case 'POST':
      try {
        const noteList = await NoteList.create({})

        const {_id, email, verificationKey: key} = await User.create({...req.body, noteList})
        if (!email) { throw new Error('Something went wrong') }

        sendMail(req.body.email, subject, text(key), html(key))

        const user = {_id, email, noteList, isVerified: false, isLoggedIn: true}
        req.session.set('user', user)
        await req.session.save()
        res.status(201).json(user)
      } catch (error) {
        console.log(error)
        res.status(400).json({isLoggedIn: false})
      }
      break
    default:
      res.status(400).json({isLoggedIn: false})
      break
  }
})