aboutsummaryrefslogtreecommitdiffstats
path: root/pages/api/password.js
blob: 871c9e6bd99c66fc84eed8e21345a7bbf04c265f (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 'configs/dbConnect'
import withSession from 'hocs/withSession'
import sendMail from 'configs/sendMail'
import mailData from 'helpers/email'
import User from 'models/User'

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

  switch (req.method) {
    case 'POST':
      try {
        const data = JSON.parse(req.body)
        if (data._id && data.currentPassword && data.newPassword) {
          const user = await User.savePassword(data)
          req.session.set('user', user)
          await req.session.save()

          sendMail({to: user.email, ...mailData('p', user.language)})

          res.status(200).json(user)
        }
      } catch (error) {
        if (error?.message === 'Wrong password') {
          res.status(401).send({ error: 'Wrong password' })
        } else {
          res.status(400).send({ error })
        }
      }
      break
    default:
      res.status(400).send({ error })
      break
  }
})