-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathroute.ts
More file actions
88 lines (77 loc) · 2.24 KB
/
Copy pathroute.ts
File metadata and controls
88 lines (77 loc) · 2.24 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withSession } from "@/lib/auth";
import { hashPassword, validatePassword } from "@/lib/auth/password";
import { prisma } from "@/lib/prisma";
import { updatePasswordSchema } from "@/lib/zod/schemas/auth";
import { sendEmail } from "@dub/email";
import PasswordUpdated from "@dub/email/templates/password-updated";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// PATCH /api/user/password - updates the user's password
export const PATCH = withSession(async ({ req, session }) => {
const { currentPassword, newPassword } = updatePasswordSchema.parse(
await parseRequestBody(req),
);
const { passwordHash } = await prisma.user.findUniqueOrThrow({
where: {
id: session.user.id,
},
select: {
passwordHash: true,
},
});
if (!passwordHash) {
throw new DubApiError({
code: "bad_request",
message: "You don't have a password set. Please set a password first.",
});
}
const passwordMatch = await validatePassword({
password: currentPassword,
passwordHash,
});
if (!passwordMatch) {
throw new DubApiError({
code: "unauthorized",
message: "The password you entered is incorrect.",
});
}
const newPasswordHash = await hashPassword(newPassword);
await prisma.$transaction([
prisma.user.update({
where: {
id: session.user.id,
},
data: {
passwordHash: newPasswordHash,
},
}),
// Dual write: keep Better Auth credential Account.password in sync
prisma.account.updateMany({
where: {
userId: session.user.id,
providerId: "credential",
},
data: {
password: newPasswordHash,
},
}),
prisma.passwordResetToken.deleteMany({
where: {
identifier: session.user.email,
},
}),
]);
// Send the email to inform the user that their password has been updated
waitUntil(
sendEmail({
subject: "Your Dub account password has been updated",
to: session.user.email,
react: PasswordUpdated({
email: session.user.email,
}),
}),
);
return NextResponse.json({ ok: true });
});