Spaces:
Sleeping
Sleeping
Andrew
commited on
Commit
·
94a9d15
1
Parent(s):
12ba18c
feat(auth): Add password recovery route
Browse files
src/routes/login/recover/+server.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { json } from "@sveltejs/kit";
|
| 2 |
+
import { z } from "zod";
|
| 3 |
+
import { collections } from "$lib/server/database";
|
| 4 |
+
import { verifyPassword, hashPassword, generateRecoveryKey } from "$lib/server/passwords";
|
| 5 |
+
|
| 6 |
+
function escapeRegExp(string: string) {
|
| 7 |
+
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
export async function POST({ request }) {
|
| 11 |
+
const body = await request.json();
|
| 12 |
+
const { username, recoveryKey, newPassword } = z
|
| 13 |
+
.object({
|
| 14 |
+
username: z.string().min(1).trim(),
|
| 15 |
+
recoveryKey: z.string().min(1),
|
| 16 |
+
newPassword: z.string().min(8),
|
| 17 |
+
})
|
| 18 |
+
.parse(body);
|
| 19 |
+
|
| 20 |
+
const user = await collections.users.findOne({
|
| 21 |
+
username: { $regex: new RegExp(`^${escapeRegExp(username)}$`, "i") },
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
if (!user || !user.recoveryKeyHash) {
|
| 25 |
+
return json({ message: "Invalid username or recovery key" }, { status: 401 });
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
let isValid = false;
|
| 29 |
+
try {
|
| 30 |
+
isValid = await verifyPassword(recoveryKey, user.recoveryKeyHash);
|
| 31 |
+
} catch (e) {
|
| 32 |
+
console.error("Error verifying recovery key:", e);
|
| 33 |
+
return json({ message: "Invalid username or recovery key" }, { status: 401 });
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
if (!isValid) {
|
| 37 |
+
return json({ message: "Invalid username or recovery key" }, { status: 401 });
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
const passwordHash = await hashPassword(newPassword);
|
| 41 |
+
|
| 42 |
+
// Rotate the recovery key after successful use
|
| 43 |
+
const newRecoveryKey = generateRecoveryKey();
|
| 44 |
+
const newRecoveryKeyHash = await hashPassword(newRecoveryKey);
|
| 45 |
+
|
| 46 |
+
await collections.users.updateOne(
|
| 47 |
+
{ _id: user._id },
|
| 48 |
+
{ $set: { passwordHash, recoveryKeyHash: newRecoveryKeyHash, updatedAt: new Date() } }
|
| 49 |
+
);
|
| 50 |
+
|
| 51 |
+
return json({
|
| 52 |
+
message: "Password updated successfully. A new recovery key has been generated.",
|
| 53 |
+
newRecoveryKey,
|
| 54 |
+
});
|
| 55 |
+
}
|