Fix SMTP delivery, add password reset and user deletion
SMTP: - Add connection/greeting/socket timeouts so a stalled Gmail connection no longer hangs sign-up - Wrap sendMail in try/catch and fall back to logging the code - Derive secure from port (465 implicit TLS vs 587 STARTTLS) - Strip whitespace from the Gmail app password - Document SMTP_HOST/SMTP_PORT in .env.example and environment.d.ts Password reset (new): - POST /(api)/auth/forgot-password emails a 6-digit code and does not reveal whether the address is registered - POST /(api)/auth/reset-password validates the code, sets the new password, verifies the email, and signs the user in - password_reset_codes table added to seed-db.mjs - "Forgot password?" flow on the mobile sign-in screen User deletion (new): - DELETE /(api)/admin/users/[id], owner-only, blocks self-deletion - Delete button with confirmation on the dashboard Users page Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
a0b297285a
commit
eceb6b45d5
@@ -1,5 +1,28 @@
|
||||
import { requireOwner, withCors, preflight } from "@/lib/admin";
|
||||
import { sql } from "@/lib/db";
|
||||
import { query, type SqlValue } from "@/lib/db";
|
||||
|
||||
const PAGE_SIZE = 25;
|
||||
|
||||
const SELECT_RIDES = `
|
||||
SELECT
|
||||
r.ride_id,
|
||||
r.origin_address,
|
||||
r.destination_address,
|
||||
r.ride_time,
|
||||
r.fare_price,
|
||||
r.payment_status,
|
||||
r.created_at,
|
||||
u.id AS user_id,
|
||||
u.email AS user_email,
|
||||
json_build_object(
|
||||
'driver_id', d.id,
|
||||
'name', d.first_name || ' ' || d.last_name,
|
||||
'rating', d.rating
|
||||
) AS driver
|
||||
FROM rides r
|
||||
INNER JOIN drivers d ON d.id = r.driver_id
|
||||
INNER JOIN users u ON u.id = r.user_id
|
||||
`;
|
||||
|
||||
export async function OPTIONS() {
|
||||
return preflight();
|
||||
@@ -12,55 +35,52 @@ export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url);
|
||||
const status = url.searchParams.get("status")?.trim().toLowerCase() ?? "";
|
||||
const q = url.searchParams.get("q")?.trim() ?? "";
|
||||
const page = Math.max(1, Number(url.searchParams.get("page")) || 1);
|
||||
|
||||
const rows = status
|
||||
? await sql`
|
||||
SELECT
|
||||
r.ride_id,
|
||||
r.origin_address,
|
||||
r.destination_address,
|
||||
r.ride_time,
|
||||
r.fare_price,
|
||||
r.payment_status,
|
||||
r.created_at,
|
||||
u.id AS user_id,
|
||||
u.email AS user_email,
|
||||
json_build_object(
|
||||
'driver_id', d.id,
|
||||
'name', d.first_name || ' ' || d.last_name,
|
||||
'rating', d.rating
|
||||
) AS driver
|
||||
FROM rides r
|
||||
INNER JOIN drivers d ON d.id = r.driver_id
|
||||
INNER JOIN users u ON u.id = r.user_id
|
||||
WHERE LOWER(r.payment_status) = ${status}
|
||||
ORDER BY r.created_at DESC
|
||||
LIMIT 500
|
||||
`
|
||||
: await sql`
|
||||
SELECT
|
||||
r.ride_id,
|
||||
r.origin_address,
|
||||
r.destination_address,
|
||||
r.ride_time,
|
||||
r.fare_price,
|
||||
r.payment_status,
|
||||
r.created_at,
|
||||
u.id AS user_id,
|
||||
u.email AS user_email,
|
||||
json_build_object(
|
||||
'driver_id', d.id,
|
||||
'name', d.first_name || ' ' || d.last_name,
|
||||
'rating', d.rating
|
||||
) AS driver
|
||||
FROM rides r
|
||||
INNER JOIN drivers d ON d.id = r.driver_id
|
||||
INNER JOIN users u ON u.id = r.user_id
|
||||
ORDER BY r.created_at DESC
|
||||
LIMIT 500
|
||||
`;
|
||||
const conds: string[] = [];
|
||||
const params: SqlValue[] = [];
|
||||
|
||||
return withCors(Response.json({ data: rows }));
|
||||
if (status) {
|
||||
params.push(status);
|
||||
conds.push(`LOWER(r.payment_status) = $${params.length}`);
|
||||
}
|
||||
|
||||
if (q) {
|
||||
params.push(`%${q}%`);
|
||||
const n = params.length;
|
||||
conds.push(
|
||||
`(u.email ILIKE $${n} OR (d.first_name || ' ' || d.last_name) ILIKE $${n} OR ` +
|
||||
`r.origin_address ILIKE $${n} OR r.destination_address ILIKE $${n})`,
|
||||
);
|
||||
}
|
||||
|
||||
const where = conds.length ? ` WHERE ${conds.join(" AND ")}` : "";
|
||||
|
||||
const [{ count }] = await query<{ count: number }>(
|
||||
`SELECT COUNT(*)::int AS count
|
||||
FROM rides r
|
||||
INNER JOIN drivers d ON d.id = r.driver_id
|
||||
INNER JOIN users u ON u.id = r.user_id${where}`,
|
||||
params,
|
||||
);
|
||||
|
||||
const rows = await query(
|
||||
`${SELECT_RIDES}${where}
|
||||
ORDER BY r.created_at DESC
|
||||
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
|
||||
[...params, PAGE_SIZE, (page - 1) * PAGE_SIZE],
|
||||
);
|
||||
|
||||
return withCors(
|
||||
Response.json({
|
||||
data: rows,
|
||||
total: count,
|
||||
page,
|
||||
pageSize: PAGE_SIZE,
|
||||
pages: Math.max(1, Math.ceil(count / PAGE_SIZE)),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[ADMIN_RIDES]: ", error);
|
||||
return withCors(
|
||||
|
||||
@@ -15,12 +15,22 @@ export async function GET(request: Request) {
|
||||
drivers: number;
|
||||
rides: number;
|
||||
revenue: number;
|
||||
rides_today: number;
|
||||
avg_fare: number;
|
||||
pending_count: number;
|
||||
pending_revenue: number;
|
||||
new_users_7d: number;
|
||||
}>`
|
||||
SELECT
|
||||
(SELECT COUNT(*)::int FROM users) AS users,
|
||||
(SELECT COUNT(*)::int FROM drivers) AS drivers,
|
||||
(SELECT COUNT(*)::int FROM rides) AS rides,
|
||||
(SELECT COALESCE(SUM(fare_price), 0)::int FROM rides WHERE payment_status = 'paid') AS revenue
|
||||
(SELECT COALESCE(SUM(fare_price), 0)::int FROM rides WHERE payment_status = 'paid') AS revenue,
|
||||
(SELECT COUNT(*)::int FROM rides WHERE created_at >= CURRENT_DATE) AS rides_today,
|
||||
(SELECT COALESCE(ROUND(AVG(fare_price)), 0)::int FROM rides WHERE payment_status = 'paid') AS avg_fare,
|
||||
(SELECT COUNT(*)::int FROM rides WHERE LOWER(payment_status) <> 'paid') AS pending_count,
|
||||
(SELECT COALESCE(SUM(fare_price), 0)::int FROM rides WHERE LOWER(payment_status) <> 'paid') AS pending_revenue,
|
||||
(SELECT COUNT(*)::int FROM users WHERE created_at >= CURRENT_DATE - INTERVAL '7 days') AS new_users_7d
|
||||
`;
|
||||
|
||||
const trend = await sql<{ day: string; rides: number; revenue: number }>`
|
||||
|
||||
@@ -58,3 +58,37 @@ export async function PATCH(request: Request, { id }: { id: string }) {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, { id }: { id: string }) {
|
||||
const auth = await requireOwner(request);
|
||||
if ("error" in auth) return withCors(auth.error);
|
||||
|
||||
if (id === auth.userId) {
|
||||
return withCors(
|
||||
Response.json(
|
||||
{ error: "You cannot delete your own account." },
|
||||
{ status: 400 },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// rides.user_id is ON DELETE CASCADE, so a rider's rides go with them.
|
||||
const rows = await sql<{ id: string }>`
|
||||
DELETE FROM users WHERE id = ${id} RETURNING id
|
||||
`;
|
||||
|
||||
if (!rows[0]) {
|
||||
return withCors(
|
||||
Response.json({ error: "User not found." }, { status: 404 }),
|
||||
);
|
||||
}
|
||||
|
||||
return withCors(Response.json({ data: rows[0] }));
|
||||
} catch (error) {
|
||||
console.error("[ADMIN_USER_DELETE]: ", error);
|
||||
return withCors(
|
||||
Response.json({ error: "Internal Server Error" }, { status: 500 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createHash, randomInt } from "crypto";
|
||||
|
||||
import { sql } from "@/lib/db";
|
||||
import { sendEmail } from "@/lib/mailer";
|
||||
|
||||
const hashCode = (email: string, code: string): string =>
|
||||
createHash("sha256").update(`${email}:${code}`).digest("hex");
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { email } = await req.json();
|
||||
|
||||
if (!email?.trim()) {
|
||||
return Response.json({ error: "Email is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const normalized = email.trim().toLowerCase();
|
||||
|
||||
try {
|
||||
const users = await sql<{ id: string }>`
|
||||
SELECT id FROM users WHERE email = ${normalized}
|
||||
`;
|
||||
|
||||
// Don't reveal whether the address is registered: always answer the same.
|
||||
if (!users[0]) {
|
||||
return Response.json({ data: { sent: false } });
|
||||
}
|
||||
|
||||
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
|
||||
|
||||
await sql`
|
||||
INSERT INTO password_reset_codes (email, code_hash, expires_at)
|
||||
VALUES (
|
||||
${normalized},
|
||||
${hashCode(normalized, code)},
|
||||
CURRENT_TIMESTAMP + INTERVAL '15 minutes'
|
||||
)
|
||||
ON CONFLICT (email) DO UPDATE SET
|
||||
code_hash = EXCLUDED.code_hash,
|
||||
expires_at = EXCLUDED.expires_at,
|
||||
attempts = 0
|
||||
`;
|
||||
|
||||
const delivered = await sendEmail(
|
||||
normalized,
|
||||
"Reset your Waseel password",
|
||||
`We received a request to reset your Waseel password.\n\nYour reset code is: ${code}\n\nIt expires in 15 minutes. If you didn't ask for this, you can ignore this email.`,
|
||||
);
|
||||
|
||||
return Response.json({
|
||||
data: {
|
||||
sent: delivered,
|
||||
// Without SMTP configured there is nothing to receive, so surface the
|
||||
// code to keep the reset flow usable on a self-hosted box.
|
||||
...(delivered ? {} : { devCode: code }),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[FORGOT_PASSWORD]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ const hashCode = (email: string, code: string): string =>
|
||||
createHash("sha256").update(`${email}:${code}`).digest("hex");
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { name, email, phone, password } = await req.json();
|
||||
const { name, email, phone, password, role } = await req.json();
|
||||
|
||||
if (!name?.trim() || !email?.trim() || !password) {
|
||||
return Response.json(
|
||||
@@ -23,6 +23,8 @@ export async function POST(req: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
const normalizedRole = role === "driver" ? "driver" : "rider";
|
||||
|
||||
if (typeof password !== "string" || password.length < 8) {
|
||||
return Response.json(
|
||||
{ error: "Password must be at least 8 characters." },
|
||||
@@ -44,18 +46,20 @@ export async function POST(req: Request) {
|
||||
|
||||
// Unverified rows may be re-registered (e.g. the first mail never arrived).
|
||||
await sql`
|
||||
INSERT INTO users (name, email, phone, password_hash, email_verified)
|
||||
INSERT INTO users (name, email, phone, password_hash, email_verified, role)
|
||||
VALUES (
|
||||
${name.trim()},
|
||||
${email.trim().toLowerCase()},
|
||||
${phone ? normalizePhone(phone) : null},
|
||||
${hashPassword(password)},
|
||||
FALSE
|
||||
FALSE,
|
||||
${normalizedRole}
|
||||
)
|
||||
ON CONFLICT (email) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
phone = COALESCE(EXCLUDED.phone, users.phone),
|
||||
password_hash = EXCLUDED.password_hash
|
||||
password_hash = EXCLUDED.password_hash,
|
||||
role = EXCLUDED.role
|
||||
`;
|
||||
|
||||
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
|
||||
@@ -73,13 +77,23 @@ export async function POST(req: Request) {
|
||||
attempts = 0
|
||||
`;
|
||||
|
||||
await sendEmail(
|
||||
const delivered = await sendEmail(
|
||||
email.trim().toLowerCase(),
|
||||
"Your Waseel verification code",
|
||||
`Welcome to Waseel!\n\nYour verification code is: ${code}\n\nIt expires in 15 minutes.`,
|
||||
);
|
||||
|
||||
return Response.json({ data: { sent: true } }, { status: 201 });
|
||||
return Response.json(
|
||||
{
|
||||
data: {
|
||||
sent: delivered,
|
||||
// Without SMTP/Gmail configured there is nothing to receive, so
|
||||
// surface the code to keep self-hosted sign-up usable.
|
||||
...(delivered ? {} : { devCode: code }),
|
||||
},
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[REGISTER]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { createHash } from "crypto";
|
||||
|
||||
import { sql } from "@/lib/db";
|
||||
import { hashPassword } from "@/lib/password";
|
||||
import { issueSession, toProfile } from "@/lib/users";
|
||||
|
||||
const hashCode = (email: string, code: string): string =>
|
||||
createHash("sha256").update(`${email}:${code}`).digest("hex");
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { email, code, password } = await req.json();
|
||||
|
||||
if (!email?.trim() || !/^\d{6}$/.test(code ?? "")) {
|
||||
return Response.json(
|
||||
{ error: "Email and a 6-digit code are required." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof password !== "string" || password.length < 8) {
|
||||
return Response.json(
|
||||
{ error: "Password must be at least 8 characters." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const normalized = email.trim().toLowerCase();
|
||||
|
||||
try {
|
||||
const valid = await sql<{ email: string }>`
|
||||
SELECT email FROM password_reset_codes
|
||||
WHERE email = ${normalized}
|
||||
AND code_hash = ${hashCode(normalized, code)}
|
||||
AND expires_at > CURRENT_TIMESTAMP
|
||||
`;
|
||||
|
||||
if (!valid[0]) {
|
||||
await sql`
|
||||
UPDATE password_reset_codes SET attempts = attempts + 1
|
||||
WHERE email = ${normalized}
|
||||
`;
|
||||
|
||||
return Response.json(
|
||||
{ error: "Invalid or expired reset code." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// A successful reset also proves control of the mailbox, so verify it too.
|
||||
const rows = await sql<{
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string | null;
|
||||
}>`
|
||||
UPDATE users
|
||||
SET password_hash = ${hashPassword(password)}, email_verified = TRUE
|
||||
WHERE email = ${normalized}
|
||||
RETURNING id, name, email, role
|
||||
`;
|
||||
|
||||
const user = rows[0];
|
||||
|
||||
if (!user) {
|
||||
return Response.json({ error: "User not found." }, { status: 404 });
|
||||
}
|
||||
|
||||
await sql`DELETE FROM password_reset_codes WHERE email = ${normalized}`;
|
||||
|
||||
const session = issueSession(user);
|
||||
|
||||
return Response.json({
|
||||
data: { token: session.token, user: toProfile(user) },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[RESET_PASSWORD]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user