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:
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user