aboutsummaryrefslogtreecommitdiffstats
path: root/pages/api/login.js
blob: 283f1854c591e2ac4c331b0d491565478380e472 (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 withSession from 'hocs/withSession'
import dbConnect from 'configs/dbConnect'
import User from 'models/User'
import log from 'helpers/log'

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

  switch (method) {
    case 'POST':
      try {
        const { email, password } = JSON.parse(req.body)
        const { _id, isVerified, noteList, theme, language } = await User.findByCredentials(email, password)
        if (!email) { throw new Error('Something went wrong') }

        const user = { _id, email, isVerified, isLoggedIn: true, noteList, theme, language }
        req.session.set('user', user)
        await req.session.save()
        log({ email, action: 'login' })
        res.status(201).json(user)
      } catch (error) {
        log({
          email: JSON.parse(req.body)?.email,
          action: 'login',
          error,
        })
        res.status(400).json({ isLoggedIn: false })
      }
      break
    default:
      res.status(400).send({ isLoggedIn: false })
      break
  }
})