Add self-hosted auth, admin API, and owner web dashboard

- Replace Clerk with self-hosted JWT auth (register/login/verify, bcrypt
  passwords, Gmail OTP with console fallback)
- Add lib/db.ts pg pool + transaction helpers; seed script migrates legacy
  Clerk-era schema (drop clerk_id, enforce UUID ids and unique email)
- Add owner-gated admin API: stats, users, drivers CRUD, rides
- Add dashboard/ Vite React owner dashboard (login, overview, users,
  fleet, rides) with dev-server proxy to avoid Expo CORS middleware
- Add scripts/set-owner.mjs for role management
This commit is contained in:
Krikorios
2026-08-23 16:38:41 +03:00
parent fbe92c9d16
commit a0b297285a
75 changed files with 5158 additions and 2837 deletions
+79
View File
@@ -0,0 +1,79 @@
import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";
export async function OPTIONS() {
return preflight();
}
export async function GET(request: Request) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const rows = await sql`
SELECT
d.*,
(SELECT COUNT(*)::int FROM rides r WHERE r.driver_id = d.id) AS total_rides,
COALESCE((
SELECT SUM(r.fare_price)::int FROM rides r
WHERE r.driver_id = d.id AND r.payment_status = 'paid'
), 0) AS revenue
FROM drivers d
ORDER BY d.id
`;
return withCors(Response.json({ data: rows }));
} catch (error) {
console.error("[ADMIN_DRIVERS]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
type DriverBody = {
first_name?: string;
last_name?: string;
profile_image_url?: string;
car_image_url?: string;
car_seats?: number;
rating?: number;
};
export async function POST(request: Request) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const body = (await request.json()) as DriverBody;
if (!body.first_name?.trim() || !body.last_name?.trim()) {
return withCors(
Response.json(
{ error: "first_name and last_name are required." },
{ status: 400 },
),
);
}
const [driver] = await sql`
INSERT INTO drivers
(first_name, last_name, profile_image_url, car_image_url, car_seats, rating)
VALUES
(${body.first_name.trim()},
${body.last_name.trim()},
${body.profile_image_url ?? null},
${body.car_image_url ?? null},
${body.car_seats ?? 4},
${body.rating ?? 4.5})
RETURNING *
`;
return withCors(Response.json({ data: driver }, { status: 201 }));
} catch (error) {
console.error("[ADMIN_DRIVER_CREATE]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
+86
View File
@@ -0,0 +1,86 @@
import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";
export async function OPTIONS() {
return preflight();
}
type DriverBody = {
first_name?: string;
last_name?: string;
profile_image_url?: string;
car_image_url?: string;
car_seats?: number;
rating?: number;
};
export async function PATCH(request: Request, { id }: { id: string }) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const body = (await request.json()) as DriverBody;
const rows = await sql`
UPDATE drivers SET
first_name = COALESCE(${body.first_name ?? null}, first_name),
last_name = COALESCE(${body.last_name ?? null}, last_name),
profile_image_url = COALESCE(${body.profile_image_url ?? null}, profile_image_url),
car_image_url = COALESCE(${body.car_image_url ?? null}, car_image_url),
car_seats = COALESCE(${body.car_seats ?? null}, car_seats),
rating = COALESCE(${body.rating ?? null}, rating)
WHERE id = ${id}
RETURNING *
`;
if (!rows[0]) {
return withCors(
Response.json({ error: "Driver not found." }, { status: 404 }),
);
}
return withCors(Response.json({ data: rows[0] }));
} catch (error) {
console.error("[ADMIN_DRIVER_PATCH]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
export async function DELETE(request: Request, { id }: { id: string }) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const used = await sql<{ n: number }>`
SELECT COUNT(*)::int AS n FROM rides WHERE driver_id = ${id}
`;
if (used[0].n > 0) {
return withCors(
Response.json(
{ error: "Driver has recorded rides and cannot be deleted." },
{ status: 409 },
),
);
}
const rows = await sql`
DELETE FROM drivers WHERE id = ${id} RETURNING id
`;
if (!rows[0]) {
return withCors(
Response.json({ error: "Driver not found." }, { status: 404 }),
);
}
return withCors(Response.json({ data: rows[0] }));
} catch (error) {
console.error("[ADMIN_DRIVER_DELETE]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
+70
View File
@@ -0,0 +1,70 @@
import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";
export async function OPTIONS() {
return preflight();
}
export async function GET(request: Request) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const url = new URL(request.url);
const status = url.searchParams.get("status")?.trim().toLowerCase() ?? "";
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
`;
return withCors(Response.json({ data: rows }));
} catch (error) {
console.error("[ADMIN_RIDES]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
+66
View File
@@ -0,0 +1,66 @@
import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";
export async function OPTIONS() {
return preflight();
}
export async function GET(request: Request) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const [totals] = await sql<{
users: number;
drivers: number;
rides: number;
revenue: 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
`;
const trend = await sql<{ day: string; rides: number; revenue: number }>`
SELECT
TO_CHAR(DAY, 'YYYY-MM-DD') AS day,
COUNT(r.ride_id)::int AS rides,
COALESCE(SUM(r.fare_price) FILTER (WHERE r.payment_status = 'paid'), 0)::int AS revenue
FROM generate_series(
CURRENT_DATE - INTERVAL '13 days',
CURRENT_DATE,
INTERVAL '1 day'
) AS DAY
LEFT JOIN rides r ON r.created_at >= DAY AND r.created_at < DAY + INTERVAL '1 day'
GROUP BY DAY
ORDER BY DAY
`;
const topDrivers = await sql<{
driver_id: number;
name: string;
rides: number;
revenue: number;
}>`
SELECT
d.id AS driver_id,
d.first_name || ' ' || d.last_name AS name,
COUNT(r.ride_id)::int AS rides,
COALESCE(SUM(r.fare_price) FILTER (WHERE r.payment_status = 'paid'), 0)::int AS revenue
FROM drivers d
LEFT JOIN rides r ON r.driver_id = d.id
GROUP BY d.id, d.first_name, d.last_name
ORDER BY revenue DESC, rides DESC
LIMIT 5
`;
return withCors(Response.json({ data: { totals, trend, topDrivers } }));
} catch (error) {
console.error("[ADMIN_STATS]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
+68
View File
@@ -0,0 +1,68 @@
import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";
export async function OPTIONS() {
return preflight();
}
export async function GET(request: Request) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const url = new URL(request.url);
const search = url.searchParams.get("q")?.trim().toLowerCase() ?? "";
const rows = search
? await sql<{
id: string;
name: string;
email: string;
role: string | null;
email_verified: boolean;
created_at: string;
rides: number;
}>`
SELECT
u.id,
u.name,
u.email,
u.role,
u.email_verified,
u.created_at,
(SELECT COUNT(*)::int FROM rides r WHERE r.user_id = u.id) AS rides
FROM users u
WHERE (LOWER(u.email) LIKE ${`%${search}%`} OR LOWER(u.name) LIKE ${`%${search}%`})
ORDER BY u.created_at DESC
LIMIT 500
`
: await sql<{
id: string;
name: string;
email: string;
role: string | null;
email_verified: boolean;
created_at: string;
rides: number;
}>`
SELECT
u.id,
u.name,
u.email,
u.role,
u.email_verified,
u.created_at,
(SELECT COUNT(*)::int FROM rides r WHERE r.user_id = u.id) AS rides
FROM users u
ORDER BY u.created_at DESC
LIMIT 500
`;
return withCors(Response.json({ data: rows }));
} catch (error) {
console.error("[ADMIN_USERS]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
+60
View File
@@ -0,0 +1,60 @@
import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";
type Body = {
role?: string | null;
email_verified?: boolean;
};
export async function OPTIONS() {
return preflight();
}
export async function PATCH(request: Request, { id }: { id: string }) {
const auth = await requireOwner(request);
if ("error" in auth) return withCors(auth.error);
try {
const body = (await request.json()) as Body;
if (body.role !== undefined) {
const allowed = ["rider", "driver", "owner", null];
if (!allowed.includes(body.role)) {
return withCors(
Response.json(
{ error: "Role must be rider, driver, owner or null." },
{ status: 400 },
),
);
}
if (id === auth.userId && body.role !== "owner") {
return withCors(
Response.json(
{ error: "You cannot remove your own owner role." },
{ status: 400 },
),
);
}
}
const rows = await sql<{ id: string; role: string | null; email_verified: boolean }>`
UPDATE users SET
role = COALESCE(${body.role ?? null}, role),
email_verified = COALESCE(${body.email_verified ?? null}, email_verified)
WHERE id = ${id}
RETURNING id, role, email_verified
`;
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_PATCH]: ", error);
return withCors(
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}
+90
View File
@@ -0,0 +1,90 @@
import { sql } from "@/lib/db";
import { issueSession, toProfile } from "@/lib/users";
const TOKENINFO_URL = "https://oauth2.googleapis.com/tokeninfo?id_token=";
type GoogleTokenInfo = {
aud?: string;
sub?: string;
email?: string;
email_verified?: string | boolean;
name?: string;
exp?: string;
error_description?: string;
};
export async function POST(req: Request) {
const { idToken } = await req.json();
if (!idToken || typeof idToken !== "string") {
return Response.json({ error: "Missing idToken." }, { status: 400 });
}
const audience = process.env.GOOGLE_OAUTH_CLIENT_ID ?? process.env.EXPO_PUBLIC_GOOGLE_AUTH_WEB_CLIENT_ID;
if (!audience) {
return Response.json(
{ error: "Server is missing GOOGLE_OAUTH_CLIENT_ID." },
{ status: 500 },
);
}
try {
const response = await fetch(`${TOKENINFO_URL}${idToken}`);
if (!response.ok) {
return Response.json(
{ error: "Invalid Google token." },
{ status: 401 },
);
}
const info = (await response.json()) as GoogleTokenInfo;
if (
info.aud !== audience ||
!info.sub ||
!info.email ||
(info.email_verified !== true && info.email_verified !== "true") ||
(info.exp && Number(info.exp) * 1000 < Date.now())
) {
return Response.json(
{ error: "Google token failed validation." },
{ status: 401 },
);
}
const name = info.name?.trim() || info.email.split("@")[0];
const rows = await sql<{
id: string;
name: string;
email: string;
role: string | null;
}>`
INSERT INTO users (name, email, google_sub, email_verified)
VALUES (${name}, ${info.email.toLowerCase()}, ${info.sub}, TRUE)
ON CONFLICT (email) DO UPDATE SET
google_sub = EXCLUDED.google_sub,
email_verified = TRUE,
name = CASE WHEN users.name = split_part(users.email, '@', 1)
THEN EXCLUDED.name ELSE users.name END
RETURNING id, name, email, role
`;
const user = rows[0];
if (!user) {
return Response.json({ error: "Could not create user." }, { status: 500 });
}
const session = issueSession(user);
return Response.json({
data: { token: session.token, user: toProfile(user) },
});
} catch (error) {
console.error("[GOOGLE_AUTH]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
+56
View File
@@ -0,0 +1,56 @@
import { createHash } from "crypto";
import { sql } from "@/lib/db";
import { verifyPassword } from "@/lib/password";
import { issueSession, toProfile } from "@/lib/users";
export async function POST(req: Request) {
const { email, password } = await req.json();
if (!email?.trim() || !password) {
return Response.json(
{ error: "Email and password are required." },
{ status: 400 },
);
}
try {
const rows = await sql<{
id: string;
name: string;
email: string;
role: string | null;
password_hash: string | null;
email_verified: boolean;
}>`
SELECT id, name, email, role, password_hash, email_verified
FROM users
WHERE email = ${email.trim().toLowerCase()}
`;
const user = rows[0];
if (!user || !user.password_hash || !verifyPassword(password, user.password_hash)) {
return Response.json(
{ error: "Invalid email or password." },
{ status: 401 },
);
}
if (!user.email_verified) {
return Response.json(
{ error: "Please verify your email first." },
{ status: 403 },
);
}
const session = issueSession(user);
return Response.json({
data: { token: session.token, user: toProfile(user) },
});
} catch (error) {
console.error("[LOGIN]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
+87
View File
@@ -0,0 +1,87 @@
import { createHash, randomInt } from "crypto";
import { sql } from "@/lib/db";
import { hashPassword } from "@/lib/password";
import { sendEmail } from "@/lib/mailer";
const normalizePhone = (raw: string): string => {
const cleaned = raw.replace(/[^\d+]/g, "");
if (cleaned.startsWith("+")) return cleaned;
return `+961${cleaned.replace(/^0+/, "")}`;
};
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();
if (!name?.trim() || !email?.trim() || !password) {
return Response.json(
{ error: "Name, email and password are required." },
{ status: 400 },
);
}
if (typeof password !== "string" || password.length < 8) {
return Response.json(
{ error: "Password must be at least 8 characters." },
{ status: 400 },
);
}
try {
const existing = await sql<{ id: string; email_verified: boolean }>`
SELECT id, email_verified FROM users WHERE email = ${email.trim().toLowerCase()}
`;
if (existing[0]?.email_verified) {
return Response.json(
{ error: "An account with this email already exists. Please sign in." },
{ status: 409 },
);
}
// 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)
VALUES (
${name.trim()},
${email.trim().toLowerCase()},
${phone ? normalizePhone(phone) : null},
${hashPassword(password)},
FALSE
)
ON CONFLICT (email) DO UPDATE SET
name = EXCLUDED.name,
phone = COALESCE(EXCLUDED.phone, users.phone),
password_hash = EXCLUDED.password_hash
`;
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
await sql`
INSERT INTO email_verification_codes (email, code_hash, expires_at)
VALUES (
${email.trim().toLowerCase()},
${hashCode(email.trim().toLowerCase(), code)},
CURRENT_TIMESTAMP + INTERVAL '15 minutes'
)
ON CONFLICT (email) DO UPDATE SET
code_hash = EXCLUDED.code_hash,
expires_at = EXCLUDED.expires_at,
attempts = 0
`;
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 });
} catch (error) {
console.error("[REGISTER]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
+64
View File
@@ -0,0 +1,64 @@
import { createHash } from "crypto";
import { sql } from "@/lib/db";
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 } = await req.json();
if (!email?.trim() || !/^\d{6}$/.test(code ?? "")) {
return Response.json(
{ error: "Email and a 6-digit code are required." },
{ status: 400 },
);
}
const normalized = email.trim().toLowerCase();
try {
const rows = await sql<{
id: string;
name: string;
email: string;
role: string | null;
}>`
UPDATE users SET email_verified = TRUE
WHERE email = ${normalized}
AND EXISTS (
SELECT 1 FROM email_verification_codes
WHERE email = ${normalized}
AND code_hash = ${hashCode(normalized, code)}
AND expires_at > CURRENT_TIMESTAMP
)
RETURNING id, name, email, role
`;
const user = rows[0];
if (!user) {
await sql`
UPDATE email_verification_codes SET attempts = attempts + 1
WHERE email = ${normalized}
`;
return Response.json(
{ error: "Invalid or expired verification code." },
{ status: 400 },
);
}
await sql`DELETE FROM email_verification_codes WHERE email = ${normalized}`;
const session = issueSession(user);
return Response.json({
data: { token: session.token, user: toProfile(user) },
});
} catch (error) {
console.error("[VERIFY]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
+1 -3
View File
@@ -1,9 +1,7 @@
import { neon } from "@neondatabase/serverless";
import { sql } from "@/lib/db";
export async function GET() {
try {
const sql = neon(process.env.DATABASE_URL!);
const response = await sql`SELECT * FROM drivers`;
return Response.json({ data: response });
+6 -6
View File
@@ -1,11 +1,11 @@
import { neon } from "@neondatabase/serverless";
import { requireAuth } from "@/lib/jwt";
import { sql } from "@/lib/db";
export async function GET(request: Request, { id }: { id: string }) {
if (!id)
return Response.json({ error: "Missing required fields" }, { status: 400 });
const auth = requireAuth(request);
if ("error" in auth) return auth.error;
try {
const sql = neon(`${process.env.DATABASE_URL}`);
const response = await sql`
SELECT
rides.ride_id,
@@ -19,7 +19,7 @@ export async function GET(request: Request, { id }: { id: string }) {
rides.fare_price,
rides.payment_status,
rides.created_at,
'driver', json_build_object(
json_build_object(
'driver_id', drivers.id,
'first_name', drivers.first_name,
'last_name', drivers.last_name,
@@ -33,7 +33,7 @@ export async function GET(request: Request, { id }: { id: string }) {
INNER JOIN
drivers ON rides.driver_id = drivers.id
WHERE
rides.user_id = ${id}
rides.user_id = ${auth.userId}
ORDER BY
rides.created_at DESC;
`;
+7 -7
View File
@@ -1,6 +1,10 @@
import { neon } from "@neondatabase/serverless";
import { requireAuth } from "@/lib/jwt";
import { sql } from "@/lib/db";
export async function POST(request: Request) {
const auth = requireAuth(request);
if ("error" in auth) return auth.error;
try {
const body = await request.json();
const {
@@ -14,7 +18,6 @@ export async function POST(request: Request) {
fare_price,
payment_status,
driver_id,
user_id,
} = body;
if (
@@ -27,8 +30,7 @@ export async function POST(request: Request) {
!ride_time ||
!fare_price ||
!payment_status ||
!driver_id ||
!user_id
!driver_id
) {
return Response.json(
{ error: "Missing required fields" },
@@ -36,8 +38,6 @@ export async function POST(request: Request) {
);
}
const sql = neon(`${process.env.DATABASE_URL}`);
const response = await sql`
INSERT INTO rides (
origin_address,
@@ -62,7 +62,7 @@ export async function POST(request: Request) {
${fare_price},
${payment_status},
${driver_id},
${user_id}
${auth.userId}
)
RETURNING *;
`;
+14 -53
View File
@@ -1,16 +1,13 @@
import { neon } from "@neondatabase/serverless";
import { requireAuth } from "@/lib/jwt";
import { sql } from "@/lib/db";
export async function GET(req: Request) {
const sql = neon(process.env.DATABASE_URL!);
const clerkId = new URL(req.url).searchParams.get("clerkId");
if (!clerkId) {
return Response.json({ error: "Missing clerkId" }, { status: 400 });
}
const auth = requireAuth(req);
if ("error" in auth) return auth.error;
try {
const response = await sql`
SELECT id, name, email, role FROM users WHERE clerk_id = ${clerkId}
SELECT id, name, email, phone, role FROM users WHERE id = ${auth.userId}
`;
return Response.json({ data: response[0] ?? null });
@@ -21,57 +18,21 @@ export async function GET(req: Request) {
}
}
export async function POST(req: Request) {
const sql = neon(process.env.DATABASE_URL!);
const { name, email, clerkId } = await req.json();
if (!name || !email || !clerkId) {
return Response.json(
{
error: "Missing required fields!",
},
{
status: 404,
},
);
}
try {
const response = await sql`
INSERT INTO users (
name,
email,
clerk_id
)
VALUES (
${name},
${email},
${clerkId}
)
`;
return new Response(JSON.stringify({ data: response }));
} catch (error) {
console.log(error);
return Response.json({ error }, { status: 500 });
}
}
export async function PATCH(req: Request) {
const sql = neon(process.env.DATABASE_URL!);
const { clerkId, role } = await req.json();
const auth = requireAuth(req);
if ("error" in auth) return auth.error;
if (!clerkId || !["rider", "driver"].includes(role)) {
return Response.json(
{ error: "Missing clerkId or invalid role." },
{ status: 400 },
);
const { role } = await req.json();
if (!["rider", "driver"].includes(role)) {
return Response.json({ error: "Invalid role." }, { status: 400 });
}
try {
const response = await sql`
UPDATE users SET role = ${role} WHERE clerk_id = ${clerkId} RETURNING id, role
UPDATE users SET role = ${role}
WHERE id = ${auth.userId}
RETURNING id, role
`;
if (response.length === 0) {