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
+69 -8
View File
@@ -1,7 +1,7 @@
// Creates and seeds the Waseel database tables on Neon.
// Creates and seeds the Waseel database tables (local/self-hosted PostgreSQL).
// Usage: node scripts/seed-db.mjs (reads DATABASE_URL from .env)
import { neon } from "@neondatabase/serverless";
import pg from "pg";
import { readFileSync } from "fs";
const env = readFileSync(new URL("../.env", import.meta.url), "utf8");
@@ -19,19 +19,78 @@ if (!databaseUrl) {
process.exit(1);
}
const sql = neon(databaseUrl);
const pool = new pg.Pool({ connectionString: databaseUrl });
const sql = async (strings, ...values) => {
const text = strings.reduce(
(acc, chunk, i) => acc + chunk + (i < values.length ? `$${i + 1}` : ""),
"",
);
const result = await pool.query(text, values);
return result.rows;
};
// Migrate databases created during the Clerk era (clerk_id column, no UNIQUE email).
const clerkCol = await sql`
SELECT 1 FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'clerk_id'
`;
if (clerkCol.length > 0) {
await sql`ALTER TABLE users DROP COLUMN clerk_id`;
console.log("Dropped legacy clerk_id column from users.");
}
// Rebuild legacy tables where users.id / rides.user_id are not UUID.
const idType = await sql`
SELECT data_type FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'id'
`;
if (idType.length > 0 && idType[0]?.data_type !== "uuid") {
console.log("Detected legacy non-UUID users schema, rebuilding users/rides...");
await sql`DROP TABLE IF EXISTS rides`;
await sql`DROP TABLE IF EXISTS users CASCADE`;
console.log("Legacy users/rides tables dropped (test data only).");
}
await sql`CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
clerk_id VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
phone VARCHAR(20),
password_hash TEXT,
google_sub TEXT UNIQUE,
email_verified BOOLEAN NOT NULL DEFAULT FALSE,
role VARCHAR(20),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;
// For databases created before roles existed.
// For databases created before self-hosted auth existed.
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS role VARCHAR(20)`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS phone VARCHAR(20)`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS password_hash TEXT`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS google_sub TEXT`;
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT FALSE`;
// email must be UNIQUE for ON CONFLICT (email) upserts in register+api.ts.
const emailUnique = await sql`
SELECT 1 FROM pg_constraint
WHERE conrelid = 'users'::regclass AND contype = 'u'
AND conkey @> ARRAY[
(SELECT attnum::smallint FROM pg_attribute
WHERE attrelid = 'users'::regclass AND attname = 'email')
]
`;
if (emailUnique.length === 0) {
await sql`ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email)`;
console.log("Added unique constraint on users.email.");
}
await sql`CREATE TABLE IF NOT EXISTS email_verification_codes (
email VARCHAR(255) PRIMARY KEY,
code_hash TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
expires_at TIMESTAMP NOT NULL
)`;
await sql`CREATE TABLE IF NOT EXISTS drivers (
id SERIAL PRIMARY KEY,
@@ -55,7 +114,7 @@ await sql`CREATE TABLE IF NOT EXISTS rides (
fare_price INTEGER NOT NULL,
payment_status VARCHAR(50) NOT NULL,
driver_id INTEGER NOT NULL REFERENCES drivers(id),
user_id VARCHAR(255) NOT NULL,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;
@@ -74,3 +133,5 @@ if (count[0].n === 0) {
}
console.log("Database ready.");
await pool.end();
+44
View File
@@ -0,0 +1,44 @@
// Promotes (or demotes) a user's role. Usage:
// node scripts/set-owner.mjs owner@example.com owner
// node scripts/set-owner.mjs owner@example.com rider
import pg from "pg";
import { readFileSync } from "fs";
const [email, role = "owner"] = process.argv.slice(2);
if (!email) {
console.error("Usage: node scripts/set-owner.mjs <email> [role]");
console.error("Roles: owner | driver | rider");
process.exit(1);
}
const env = readFileSync(new URL("../.env", import.meta.url), "utf8");
const databaseUrl = env
.split("\n")
.find((l) => l.startsWith("DATABASE_URL="))
?.split("=")
.slice(1)
.join("=")
.trim()
.replace(/^"|"$/g, "");
const pool = new pg.Pool({ connectionString: databaseUrl });
try {
const { rows } = await pool.query(
`UPDATE users SET email_verified = TRUE, role = $2 WHERE email = $1 RETURNING id, email, role`,
[email.toLowerCase(), role],
);
if (!rows[0]) {
console.error(`No user found with email ${email}`);
process.exit(1);
}
console.log(
`Updated ${rows[0].email}: role=${rows[0].role}, email_verified=true`,
);
} finally {
await pool.end();
}