aboutsummaryrefslogtreecommitdiff
path: root/src/app/api/me/password/route.ts
blob: 24c7370535026384c1561989e473f208c81837fd (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
import { z } from 'zod';
import { checkPassword, hashPassword } from '@/lib/password';
import { parseRequest } from '@/lib/request';
import { badRequest, json } from '@/lib/response';
import { getUser, updateUser } from '@/queries/prisma/user';

export async function POST(request: Request) {
  const schema = z.object({
    currentPassword: z.string(),
    newPassword: z.string().min(8),
  });

  const { auth, body, error } = await parseRequest(request, schema);

  if (error) {
    return error();
  }

  const userId = auth.user.id;
  const { currentPassword, newPassword } = body;

  const user = await getUser(userId, { includePassword: true });

  if (!checkPassword(currentPassword, user.password)) {
    return badRequest({ message: 'Current password is incorrect' });
  }

  const password = hashPassword(newPassword);

  const updated = await updateUser(userId, { password });

  return json(updated);
}