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:
+15
-4
@@ -1,14 +1,25 @@
|
||||
# .env
|
||||
|
||||
# clerk publishable key
|
||||
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_KEY_HERE
|
||||
# jwt secret for self-hosted auth sessions (generate with: openssl rand -hex 32)
|
||||
AUTH_JWT_SECRET=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
|
||||
# postgres db url (neon db)
|
||||
DATABASE_URL="postgresql://username:password@hostname:port/uber-clone?sslmode=require"
|
||||
# postgres db url (self-hosted, e.g. postgresql://user:password@localhost:5432/waseel)
|
||||
DATABASE_URL="postgresql://username:password@hostname:port/waseel"
|
||||
|
||||
# expo api server url (you can set it to any random url for development)
|
||||
EXPO_PUBLIC_SERVER_URL="https://example.com/"
|
||||
|
||||
# google oauth client ids (from Google Cloud console, type "Web/iOS/Android")
|
||||
EXPO_PUBLIC_GOOGLE_AUTH_WEB_CLIENT_ID=XXXXXXXX.apps.googleusercontent.com
|
||||
EXPO_PUBLIC_GOOGLE_AUTH_IOS_CLIENT_ID=XXXXXXXX.apps.googleusercontent.com
|
||||
EXPO_PUBLIC_GOOGLE_AUTH_ANDROID_CLIENT_ID=XXXXXXXX.apps.googleusercontent.com
|
||||
|
||||
# gmail api (oauth refresh token with gmail.send scope; leave blank to log codes to server console)
|
||||
GMAIL_CLIENT_ID=
|
||||
GMAIL_CLIENT_SECRET=
|
||||
GMAIL_REFRESH_TOKEN=
|
||||
GMAIL_FROM="Waseel <you@gmail.com>"
|
||||
|
||||
# geoapify api key
|
||||
EXPO_PUBLIC_GEOAPIFY_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
|
||||
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -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;
|
||||
`;
|
||||
|
||||
@@ -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
@@ -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) {
|
||||
|
||||
+19
-17
@@ -1,4 +1,3 @@
|
||||
import { useSignIn } from "@clerk/clerk-expo";
|
||||
import { Link, useRouter } from "expo-router";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Alert, Image, ScrollView, Text, View } from "react-native";
|
||||
@@ -7,42 +6,45 @@ import { CustomButton } from "@/components/custom-button";
|
||||
import { InputField } from "@/components/input-field";
|
||||
import { OAuth } from "@/components/oauth";
|
||||
import { icons, images } from "@/constants";
|
||||
import { fetchAPI } from "@/lib/fetch";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
const SignIn = () => {
|
||||
const router = useRouter();
|
||||
const { signIn, setActive, isLoaded } = useSignIn();
|
||||
const { isLoaded, setSession } = useSession();
|
||||
const [form, setForm] = useState({
|
||||
email: "",
|
||||
password: "",
|
||||
});
|
||||
|
||||
const onSignInPress = useCallback(async () => {
|
||||
if (!isLoaded) return;
|
||||
|
||||
try {
|
||||
const signInAttempt = await signIn.create({
|
||||
identifier: form.email,
|
||||
const response = await fetchAPI("/(api)/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email: form.email,
|
||||
password: form.password,
|
||||
}),
|
||||
});
|
||||
|
||||
if (signInAttempt.status === "complete") {
|
||||
await setActive({ session: signInAttempt.createdSessionId });
|
||||
await setSession(response.data);
|
||||
router.replace("/");
|
||||
} else {
|
||||
Alert.alert("Error", "Invalid email or password.");
|
||||
setForm((prevForm) => ({
|
||||
...prevForm,
|
||||
password: "",
|
||||
}));
|
||||
}
|
||||
} catch (err: any) {
|
||||
Alert.alert("Error", err?.errors[0]?.longMessage);
|
||||
const status = String(err?.message ?? "");
|
||||
const message = status.includes("403")
|
||||
? "Please verify your email first."
|
||||
: status.includes("401")
|
||||
? "Invalid email or password."
|
||||
: "Could not sign in. Please try again.";
|
||||
|
||||
Alert.alert("Error", message);
|
||||
setForm((prevForm) => ({
|
||||
...prevForm,
|
||||
password: "",
|
||||
}));
|
||||
}
|
||||
}, [isLoaded, signIn, form.email, form.password, setActive, router]);
|
||||
}, [isLoaded, form.email, form.password, setSession, router]);
|
||||
|
||||
return (
|
||||
<ScrollView className="flex-1 bg-white">
|
||||
|
||||
+48
-32
@@ -1,4 +1,3 @@
|
||||
import { useSignUp } from "@clerk/clerk-expo";
|
||||
import { Link, router } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Alert, Image, ScrollView, Text, View } from "react-native";
|
||||
@@ -9,13 +8,15 @@ import { InputField } from "@/components/input-field";
|
||||
import { OAuth } from "@/components/oauth";
|
||||
import { icons, images } from "@/constants";
|
||||
import { fetchAPI } from "@/lib/fetch";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
const SignUp = () => {
|
||||
const { isLoaded, signUp, setActive } = useSignUp();
|
||||
const { setSession } = useSession();
|
||||
|
||||
const [form, setForm] = useState({
|
||||
name: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
password: "",
|
||||
});
|
||||
|
||||
@@ -26,18 +27,34 @@ const SignUp = () => {
|
||||
});
|
||||
|
||||
const onSignUpPress = async () => {
|
||||
if (!isLoaded) return;
|
||||
if (!form.name.trim() || !form.email.trim() || !form.password) {
|
||||
Alert.alert(
|
||||
"Missing information",
|
||||
"Please fill in your name, email and password.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.phone.trim() && !/^[0-9\s\-()+.]+$/.test(form.phone)) {
|
||||
Alert.alert(
|
||||
"Invalid phone number",
|
||||
"Enter a valid Lebanese number, e.g. 70 123 456.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await signUp.create({
|
||||
firstName: form.name,
|
||||
lastName: "",
|
||||
emailAddress: form.email,
|
||||
await fetchAPI("/(api)/auth/register", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: form.name,
|
||||
email: form.email,
|
||||
phone: form.phone.trim(),
|
||||
password: form.password,
|
||||
}),
|
||||
});
|
||||
|
||||
await signUp.prepareEmailAddressVerification({ strategy: "email_code" });
|
||||
|
||||
setVerification((prevVerification) => ({
|
||||
...prevVerification,
|
||||
state: "pending",
|
||||
@@ -52,44 +69,29 @@ const SignUp = () => {
|
||||
...prevForm,
|
||||
password: "",
|
||||
}));
|
||||
Alert.alert("Error", err?.errors[0]?.longMessage);
|
||||
Alert.alert("Error", err?.message ?? "Could not create your account.");
|
||||
}
|
||||
};
|
||||
|
||||
const onPressVerify = async () => {
|
||||
if (!isLoaded) return;
|
||||
|
||||
try {
|
||||
const completeSignUp = await signUp.attemptEmailAddressVerification({
|
||||
code: verification.code,
|
||||
});
|
||||
|
||||
if (completeSignUp.status === "complete") {
|
||||
await fetchAPI("/(api)/user", {
|
||||
const response = await fetchAPI("/(api)/auth/verify", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: form.name,
|
||||
email: form.email,
|
||||
clerkId: completeSignUp.createdUserId,
|
||||
}),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: form.email, code: verification.code }),
|
||||
});
|
||||
|
||||
await setActive({ session: completeSignUp.createdSessionId });
|
||||
await setSession(response.data);
|
||||
setVerification((prevVerification) => ({
|
||||
...prevVerification,
|
||||
state: "success",
|
||||
}));
|
||||
} else {
|
||||
setVerification((prevVerification) => ({
|
||||
...prevVerification,
|
||||
error: "Verification failed.",
|
||||
state: "failed",
|
||||
}));
|
||||
}
|
||||
} catch (err: any) {
|
||||
setVerification((prevVerification) => ({
|
||||
...prevVerification,
|
||||
error: err?.errors[0]?.longMessage,
|
||||
error: err?.message?.includes("400")
|
||||
? "Invalid or expired verification code."
|
||||
: err?.message ?? "Verification failed.",
|
||||
state: "failed",
|
||||
}));
|
||||
}
|
||||
@@ -140,6 +142,20 @@ const SignUp = () => {
|
||||
keyboardType="email-address"
|
||||
/>
|
||||
|
||||
<InputField
|
||||
label="Phone (optional)"
|
||||
placeholder="70 123 456"
|
||||
icon={icons.chat}
|
||||
value={form.phone}
|
||||
onChangeText={(value) =>
|
||||
setForm((prevForm) => ({
|
||||
...prevForm,
|
||||
phone: value,
|
||||
}))
|
||||
}
|
||||
keyboardType="phone-pad"
|
||||
/>
|
||||
|
||||
<InputField
|
||||
label="Password"
|
||||
placeholder="••••••••"
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useAuth, useUser } from "@clerk/clerk-expo";
|
||||
import * as Location from "expo-location";
|
||||
import { Link, router } from "expo-router";
|
||||
import { router } from "expo-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
@@ -15,16 +14,15 @@ import { SafeAreaView } from "react-native-safe-area-context";
|
||||
import { GoogleTextInput } from "@/components/google-text-input";
|
||||
import { Map } from "@/components/map";
|
||||
import { RideCard } from "@/components/ride-card";
|
||||
import { LINKS } from "@/config";
|
||||
import { icons, images } from "@/constants";
|
||||
import { useSession } from "@/lib/session";
|
||||
import { useLocationStore } from "@/store";
|
||||
import { useFetch } from "@/lib/fetch";
|
||||
import type { Ride } from "@/types/type";
|
||||
|
||||
const Home = () => {
|
||||
const { setUserLocation, setDestinationLocation } = useLocationStore();
|
||||
const { signOut } = useAuth();
|
||||
const { user } = useUser();
|
||||
const { signOut, user } = useSession();
|
||||
const { data: recentRides, loading } = useFetch<Ride[]>(
|
||||
`/(api)/ride/${user?.id}`,
|
||||
);
|
||||
@@ -119,23 +117,10 @@ const Home = () => {
|
||||
numberOfLines={1}
|
||||
>
|
||||
Welcome{" "}
|
||||
{user?.firstName || user?.emailAddresses[0].emailAddress} 👋
|
||||
{user?.name || user?.email} 👋
|
||||
</Text>
|
||||
|
||||
<View className="flex flex-row items-center gap-x-1">
|
||||
<Link
|
||||
href={LINKS.sourceCode}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="justify-center items-center w-10 h-10"
|
||||
>
|
||||
<Image
|
||||
source={icons.github}
|
||||
className="w-6 h-6"
|
||||
alt="GitHub"
|
||||
/>
|
||||
</Link>
|
||||
|
||||
<TouchableOpacity
|
||||
onPress={handleSignOut}
|
||||
className="justify-center items-center w-10 h-10 rounded-full bg-white"
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useUser } from "@clerk/clerk-expo";
|
||||
import { Image, ScrollView, Text, View } from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
|
||||
import { InputField } from "@/components/input-field";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
const Profile = () => {
|
||||
const { user } = useUser();
|
||||
const { user } = useSession();
|
||||
|
||||
return (
|
||||
<SafeAreaView className="flex-1">
|
||||
@@ -17,9 +17,7 @@ const Profile = () => {
|
||||
|
||||
<View className="flex items-center justify-center my-5">
|
||||
<Image
|
||||
source={{
|
||||
uri: user?.externalAccounts[0]?.imageUrl ?? user?.imageUrl,
|
||||
}}
|
||||
source={{ uri: user?.avatarUrl ?? undefined }}
|
||||
alt="Your Avatar"
|
||||
style={{ width: 110, height: 110, borderRadius: 110 / 2 }}
|
||||
className=" rounded-full h-[110px] w-[110px] border-[3px] border-white shadow-sm shadow-neutral-300"
|
||||
@@ -30,7 +28,7 @@ const Profile = () => {
|
||||
<View className="flex flex-col items-start justify-start w-full">
|
||||
<InputField
|
||||
label="First name"
|
||||
placeholder={user?.firstName ?? "Your First name"}
|
||||
placeholder={user?.name.split(" ")[0] ?? "Your First name"}
|
||||
containerStyles="w-full mb-4"
|
||||
inputStyles="p-3.5"
|
||||
editable={false}
|
||||
@@ -38,7 +36,7 @@ const Profile = () => {
|
||||
|
||||
<InputField
|
||||
label="Last name"
|
||||
placeholder={user?.lastName ?? "Your Last name"}
|
||||
placeholder={user?.name.split(" ").slice(1).join(" ") ?? "Your Last name"}
|
||||
containerStyles="w-full mb-4"
|
||||
inputStyles="p-3.5"
|
||||
editable={false}
|
||||
@@ -46,9 +44,7 @@ const Profile = () => {
|
||||
|
||||
<InputField
|
||||
label="Email"
|
||||
placeholder={
|
||||
user?.primaryEmailAddress?.emailAddress ?? "Your Email address"
|
||||
}
|
||||
placeholder={user?.email ?? "Your Email address"}
|
||||
containerStyles="w-full mb-4"
|
||||
inputStyles="p-3.5"
|
||||
editable={false}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useUser } from "@clerk/clerk-expo";
|
||||
import { ActivityIndicator, FlatList, Image, Text, View } from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
|
||||
import { RideCard } from "@/components/ride-card";
|
||||
import { images } from "@/constants";
|
||||
import { useFetch } from "@/lib/fetch";
|
||||
import { useSession } from "@/lib/session";
|
||||
import type { Ride } from "@/types/type";
|
||||
|
||||
const Rides = () => {
|
||||
const { user } = useUser();
|
||||
const { user } = useSession();
|
||||
const { data: recentRides, loading } = useFetch<Ride[]>(
|
||||
`/(api)/ride/${user?.id}`,
|
||||
);
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { useUser } from "@clerk/clerk-expo";
|
||||
import { router } from "expo-router";
|
||||
import { Image, Text, View } from "react-native";
|
||||
|
||||
import { CustomButton } from "@/components/custom-button";
|
||||
import { Payment } from "@/components/payment";
|
||||
import { RideLayout } from "@/components/ride-layout";
|
||||
import { icons } from "@/constants";
|
||||
import { formatLBP } from "@/lib/pricing";
|
||||
import { useSession } from "@/lib/session";
|
||||
import { formatTime } from "@/lib/utils";
|
||||
import { useDriverStore, useLocationStore } from "@/store";
|
||||
|
||||
const BookRide = () => {
|
||||
const { user } = useUser();
|
||||
const { user } = useSession();
|
||||
const { userAddress, destinationAddress } = useLocationStore();
|
||||
const { drivers, selectedDriver } = useDriverStore();
|
||||
|
||||
@@ -16,6 +19,24 @@ const BookRide = () => {
|
||||
(driver) => +driver.id === selectedDriver,
|
||||
)[0];
|
||||
|
||||
if (!driverDetails) {
|
||||
return (
|
||||
<RideLayout title="Book Ride">
|
||||
<View className="flex-1 items-center justify-center">
|
||||
<Text className="text-base text-general-200 font-JakartaMedium text-center">
|
||||
No driver selected.{"\n"}Please go back and choose a driver first.
|
||||
</Text>
|
||||
|
||||
<CustomButton
|
||||
title="Choose a Driver"
|
||||
onPress={() => router.replace("/(root)/confirm-ride")}
|
||||
className="mt-6"
|
||||
/>
|
||||
</View>
|
||||
</RideLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<RideLayout title="Book Ride">
|
||||
<>
|
||||
@@ -54,9 +75,15 @@ const BookRide = () => {
|
||||
<View className="flex flex-row items-center justify-between w-full border-b border-white py-3">
|
||||
<Text className="text-lg font-JakartaRegular">Ride Price</Text>
|
||||
|
||||
<View className="flex flex-col items-end">
|
||||
<Text className="text-lg font-JakartaRegular text-[#0CC25F]">
|
||||
${driverDetails?.price}
|
||||
</Text>
|
||||
|
||||
<Text className="text-xs font-JakartaRegular text-general-200">
|
||||
≈ {formatLBP(parseFloat(driverDetails?.price ?? "0"))}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="flex flex-row items-center justify-between w-full border-b border-white py-3">
|
||||
@@ -95,8 +122,8 @@ const BookRide = () => {
|
||||
</View>
|
||||
|
||||
<Payment
|
||||
fullName={user?.fullName ?? ""}
|
||||
email={user?.emailAddresses[0].emailAddress ?? ""}
|
||||
fullName={user?.name ?? ""}
|
||||
email={user?.email ?? ""}
|
||||
amount={driverDetails?.price ?? "0"}
|
||||
driverId={driverDetails?.id}
|
||||
rideTime={driverDetails?.time ?? 0}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { router } from "expo-router";
|
||||
import { FlatList, View } from "react-native";
|
||||
import { FlatList, Text, View } from "react-native";
|
||||
|
||||
import { CustomButton } from "@/components/custom-button";
|
||||
import { DriverCard } from "@/components/driver-card";
|
||||
@@ -20,11 +20,19 @@ const ConfirmRide = () => {
|
||||
setSelected={() => setSelectedDriver(item.id)}
|
||||
/>
|
||||
)}
|
||||
ListEmptyComponent={() => (
|
||||
<Text className="text-center text-general-200 font-JakartaMedium mt-10">
|
||||
No drivers available on this route right now.{"\n"}Please try
|
||||
another destination.
|
||||
</Text>
|
||||
)}
|
||||
ListFooterComponent={() => (
|
||||
<View className="mx-5 mt-10">
|
||||
<CustomButton
|
||||
title="Select Ride"
|
||||
onPress={() => router.push("/(root)/book-ride")}
|
||||
disabled={selectedDriver === null}
|
||||
className={selectedDriver === null ? "opacity-50" : ""}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import { useClerk, useUser } from "@clerk/clerk-expo";
|
||||
import { Image, Text, View } from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
|
||||
import { CustomButton } from "@/components/custom-button";
|
||||
import { images } from "@/constants";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
// Placeholder driver home. The driver experience (going online, accepting
|
||||
// rides) is not built yet — drivers are registered here and managed in the
|
||||
// database for now.
|
||||
const DriverHome = () => {
|
||||
const { user } = useUser();
|
||||
const { signOut } = useClerk();
|
||||
const { signOut, user } = useSession();
|
||||
|
||||
return (
|
||||
<SafeAreaView className="flex-1 bg-white justify-center items-center px-7">
|
||||
@@ -21,12 +20,12 @@ const DriverHome = () => {
|
||||
/>
|
||||
|
||||
<Text className="text-2xl font-JakartaBold text-center">
|
||||
You're registered as a driver, {user?.firstName || "there"}!
|
||||
You're registered as a driver, {user?.name || "there"}!
|
||||
</Text>
|
||||
|
||||
<Text className="text-base text-general-200 font-Jakarta text-center mt-3">
|
||||
Driver mode is coming soon. We'll contact you at{" "}
|
||||
{user?.emailAddresses[0]?.emailAddress} once your account is activated.
|
||||
{user?.email} once your account is activated.
|
||||
</Text>
|
||||
|
||||
<CustomButton
|
||||
|
||||
@@ -10,10 +10,20 @@ const FindRide = () => {
|
||||
const {
|
||||
userAddress,
|
||||
destinationAddress,
|
||||
userLatitude,
|
||||
userLongitude,
|
||||
destinationLatitude,
|
||||
destinationLongitude,
|
||||
setDestinationLocation,
|
||||
setUserLocation,
|
||||
} = useLocationStore();
|
||||
|
||||
const canFind =
|
||||
!!userLatitude &&
|
||||
!!userLongitude &&
|
||||
!!destinationLatitude &&
|
||||
!!destinationLongitude;
|
||||
|
||||
return (
|
||||
<RideLayout title="Ride" snapPoints={["85%"]}>
|
||||
<View className="my-3">
|
||||
@@ -43,7 +53,8 @@ const FindRide = () => {
|
||||
<CustomButton
|
||||
title="Find now"
|
||||
onPress={() => router.push("/(root)/confirm-ride")}
|
||||
className="mt-5"
|
||||
disabled={!canFind}
|
||||
className={`mt-5 ${!canFind ? "opacity-50" : ""}`}
|
||||
/>
|
||||
</RideLayout>
|
||||
);
|
||||
|
||||
+6
-4
@@ -1,17 +1,17 @@
|
||||
import { useUser } from "@clerk/clerk-expo";
|
||||
import { router } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Alert, Text, TouchableOpacity, View } from "react-native";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
|
||||
import { fetchAPI } from "@/lib/fetch";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
const RoleSelection = () => {
|
||||
const { user } = useUser();
|
||||
const { setUserRole } = useSession();
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const chooseRole = async (role: "rider" | "driver") => {
|
||||
if (!user?.id || saving) return;
|
||||
if (saving) return;
|
||||
|
||||
setSaving(true);
|
||||
|
||||
@@ -19,11 +19,13 @@ const RoleSelection = () => {
|
||||
const { error } = await fetchAPI("/(api)/user", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ clerkId: user.id, role }),
|
||||
body: JSON.stringify({ role }),
|
||||
});
|
||||
|
||||
if (error) throw new Error(error);
|
||||
|
||||
setUserRole(role);
|
||||
|
||||
router.replace(
|
||||
role === "driver" ? "/(root)/driver-home" : "/(root)/(tabs)/home",
|
||||
);
|
||||
|
||||
+3
-10
@@ -1,4 +1,3 @@
|
||||
import { ClerkProvider, ClerkLoaded } from "@clerk/clerk-expo";
|
||||
import { useFonts } from "expo-font";
|
||||
import { Stack } from "expo-router";
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
@@ -7,7 +6,7 @@ import { useEffect } from "react";
|
||||
import { LogBox } from "react-native";
|
||||
import "react-native-reanimated";
|
||||
|
||||
import { tokenCache } from "@/lib/auth";
|
||||
import { SessionProvider } from "@/lib/session";
|
||||
|
||||
// Prevent the splash screen from auto-hiding before asset loading is complete.
|
||||
SplashScreen.preventAutoHideAsync();
|
||||
@@ -35,13 +34,8 @@ const RootLayout = () => {
|
||||
return null;
|
||||
}
|
||||
|
||||
const publishableKey = process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY!;
|
||||
|
||||
if (!publishableKey) throw new Error("Missing Clerk Publishable Key.");
|
||||
|
||||
return (
|
||||
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
|
||||
<ClerkLoaded>
|
||||
<SessionProvider>
|
||||
<Stack>
|
||||
<Stack.Screen name="index" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="(root)" options={{ headerShown: false }} />
|
||||
@@ -49,8 +43,7 @@ const RootLayout = () => {
|
||||
</Stack>
|
||||
|
||||
<StatusBar style="dark" />
|
||||
</ClerkLoaded>
|
||||
</ClerkProvider>
|
||||
</SessionProvider>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
+19
-5
@@ -1,21 +1,35 @@
|
||||
import { useAuth } from "@clerk/clerk-expo";
|
||||
import { Redirect } from "expo-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { ActivityIndicator, View } from "react-native";
|
||||
|
||||
import { fetchAPI } from "@/lib/fetch";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
const App = () => {
|
||||
const { isSignedIn, userId } = useAuth();
|
||||
const { isLoaded, isSignedIn, user } = useSession();
|
||||
const [role, setRole] = useState<string | null | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSignedIn || !userId) return;
|
||||
if (!isSignedIn) return;
|
||||
|
||||
fetchAPI(`/(api)/user?clerkId=${userId}`)
|
||||
// Prefer the role cached at sign-in; fall back to a fresh fetch.
|
||||
if (user?.role !== undefined && user?.role !== null) {
|
||||
setRole(user.role);
|
||||
return;
|
||||
}
|
||||
|
||||
fetchAPI("/(api)/user")
|
||||
.then((res) => setRole(res?.data?.role ?? null))
|
||||
.catch(() => setRole(null));
|
||||
}, [isSignedIn, userId]);
|
||||
}, [isSignedIn, user]);
|
||||
|
||||
if (!isLoaded) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-white">
|
||||
<ActivityIndicator size="large" color="#0286FF" />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isSignedIn) return <Redirect href="/(auth)/welcome" />;
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ export const DriverCard = ({
|
||||
|
||||
<View className="flex flex-row items-center space-x-1 ml-2">
|
||||
<Image source={icons.star} alt="Star" className="w-3.5 h-3.5" />
|
||||
<Text className="text-sm font-JakartaRegular">4</Text>
|
||||
<Text className="text-sm font-JakartaRegular">{item.rating}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ interface Suggestion {
|
||||
}
|
||||
|
||||
// Places API (New) — the legacy Places web service is unavailable to
|
||||
// newer Google Cloud projects.
|
||||
// newer Google Cloud projects. Results are restricted to Lebanon.
|
||||
const fetchSuggestions = async (input: string): Promise<Suggestion[]> => {
|
||||
const res = await fetch(
|
||||
"https://places.googleapis.com/v1/places:autocomplete",
|
||||
@@ -29,7 +29,11 @@ const fetchSuggestions = async (input: string): Promise<Suggestion[]> => {
|
||||
"Content-Type": "application/json",
|
||||
"X-Goog-Api-Key": googleApiKey,
|
||||
},
|
||||
body: JSON.stringify({ input, languageCode: "en" }),
|
||||
body: JSON.stringify({
|
||||
input,
|
||||
languageCode: "en",
|
||||
includedRegionCodes: ["lb"],
|
||||
}),
|
||||
},
|
||||
);
|
||||
const data = await res.json();
|
||||
|
||||
+2
-2
@@ -45,10 +45,10 @@ export const Map = () => {
|
||||
setMarkers(newMarkers);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [drivers]);
|
||||
}, [drivers, userLatitude, userLongitude]);
|
||||
|
||||
useEffect(() => {
|
||||
if (markers.length > 0 && destinationLatitude && destinationLatitude) {
|
||||
if (markers.length > 0 && destinationLatitude && destinationLongitude) {
|
||||
calculateDriverTimes({
|
||||
markers,
|
||||
userLatitude,
|
||||
|
||||
+31
-11
@@ -1,10 +1,11 @@
|
||||
import { useOAuth } from "@clerk/clerk-expo";
|
||||
import * as Google from "expo-auth-session/providers/google";
|
||||
import { router } from "expo-router";
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { Image, Text, View, Alert } from "react-native";
|
||||
|
||||
import { icons } from "@/constants";
|
||||
import { googleOAuth } from "@/lib/auth";
|
||||
import { googleAuth } from "@/lib/auth";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
import { CustomButton } from "./custom-button";
|
||||
|
||||
@@ -13,23 +14,41 @@ type OAuthProps = {
|
||||
};
|
||||
|
||||
export const OAuth = ({ title }: OAuthProps) => {
|
||||
const { startOAuthFlow } = useOAuth({ strategy: "oauth_google" });
|
||||
const { setSession } = useSession();
|
||||
|
||||
const handleGoogleOAuth = useCallback(async () => {
|
||||
try {
|
||||
const result = await googleOAuth(startOAuthFlow);
|
||||
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
|
||||
clientId: process.env.EXPO_PUBLIC_GOOGLE_AUTH_WEB_CLIENT_ID,
|
||||
iosClientId: process.env.EXPO_PUBLIC_GOOGLE_AUTH_IOS_CLIENT_ID,
|
||||
androidClientId: process.env.EXPO_PUBLIC_GOOGLE_AUTH_ANDROID_CLIENT_ID,
|
||||
});
|
||||
|
||||
if (result?.code === "session_exists" || result?.code === "success") {
|
||||
router.replace("/");
|
||||
useEffect(() => {
|
||||
if (response?.type !== "success") return;
|
||||
|
||||
const idToken = response.params?.id_token;
|
||||
|
||||
if (!idToken) {
|
||||
Alert.alert("Google sign-in failed", "No token returned. Try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
await setSession(await googleAuth(idToken));
|
||||
router.replace("/");
|
||||
} catch (err: any) {
|
||||
console.error("OAuth error", err);
|
||||
Alert.alert(
|
||||
"Google sign-in failed",
|
||||
err?.errors?.[0]?.longMessage || err?.message || "Please try again.",
|
||||
err?.message || "Please try again.",
|
||||
);
|
||||
}
|
||||
}, [startOAuthFlow]);
|
||||
})();
|
||||
}, [response, setSession]);
|
||||
|
||||
const handleGoogleOAuth = useCallback(() => {
|
||||
void promptAsync();
|
||||
}, [promptAsync]);
|
||||
|
||||
return (
|
||||
<View>
|
||||
@@ -55,6 +74,7 @@ export const OAuth = ({ title }: OAuthProps) => {
|
||||
bgVariant="outline"
|
||||
textVariant="primary"
|
||||
onPress={handleGoogleOAuth}
|
||||
disabled={!request}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
|
||||
+87
-13
@@ -1,17 +1,19 @@
|
||||
import { useAuth } from "@clerk/clerk-expo";
|
||||
import { router } from "expo-router";
|
||||
import * as WebBrowser from "expo-web-browser";
|
||||
import { useState } from "react";
|
||||
import { Alert, Image, Text, View } from "react-native";
|
||||
import { Alert, Image, Text, TouchableOpacity, View } from "react-native";
|
||||
import ReactNativeModal from "react-native-modal";
|
||||
|
||||
import { images } from "@/constants";
|
||||
import { fetchAPI } from "@/lib/fetch";
|
||||
import { formatLBP } from "@/lib/pricing";
|
||||
import { useLocationStore } from "@/store";
|
||||
import type { PaymentProps } from "@/types/type";
|
||||
|
||||
import { CustomButton } from "./custom-button";
|
||||
|
||||
type PaymentMethod = "cash" | "card";
|
||||
|
||||
export const Payment = ({
|
||||
fullName,
|
||||
email,
|
||||
@@ -27,11 +29,11 @@ export const Payment = ({
|
||||
destinationAddress,
|
||||
destinationLongitude,
|
||||
} = useLocationStore();
|
||||
const { userId } = useAuth();
|
||||
const [method, setMethod] = useState<PaymentMethod>("cash");
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [processing, setProcessing] = useState(false);
|
||||
|
||||
const recordRide = async () => {
|
||||
const recordRide = async (paymentStatus: string) => {
|
||||
await fetchAPI("/(api)/ride/create", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -45,15 +47,31 @@ export const Payment = ({
|
||||
destination_latitude: destinationLatitude,
|
||||
destination_longitude: destinationLongitude,
|
||||
ride_time: rideTime.toFixed(0),
|
||||
fare_price: parseInt(amount) * 100, // in cents
|
||||
payment_status: "paid",
|
||||
fare_price: Math.round(parseFloat(amount) * 100), // in cents
|
||||
payment_status: paymentStatus,
|
||||
driver_id: driverId,
|
||||
user_id: userId,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const payWithAreeba = async () => {
|
||||
// Cash is settled directly with the driver at drop-off.
|
||||
const payWithCash = async () => {
|
||||
setProcessing(true);
|
||||
try {
|
||||
await recordRide("cash");
|
||||
setSuccess(true);
|
||||
} catch (err) {
|
||||
console.log("[PAYMENT]: ", err);
|
||||
Alert.alert(
|
||||
"Error",
|
||||
"Something went wrong while booking your ride. Please try again.",
|
||||
);
|
||||
} finally {
|
||||
setProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const payWithCard = async () => {
|
||||
setProcessing(true);
|
||||
|
||||
try {
|
||||
@@ -99,7 +117,7 @@ export const Payment = ({
|
||||
});
|
||||
|
||||
if (verification.success) {
|
||||
await recordRide();
|
||||
await recordRide("paid");
|
||||
setSuccess(true);
|
||||
} else {
|
||||
Alert.alert(
|
||||
@@ -118,12 +136,66 @@ export const Payment = ({
|
||||
}
|
||||
};
|
||||
|
||||
const confirm = () =>
|
||||
method === "cash"
|
||||
? payWithCash()
|
||||
: Alert.alert("Pay by card", `Your card will be charged $${amount}.`, [
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{ text: "Continue", onPress: () => void payWithCard() },
|
||||
]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Text className="text-lg font-JakartaSemiBold mt-4 mb-2">
|
||||
Payment Method
|
||||
</Text>
|
||||
|
||||
<View className="flex flex-row gap-x-3">
|
||||
<TouchableOpacity
|
||||
onPress={() => setMethod("cash")}
|
||||
className={`flex-1 items-center py-3 rounded-xl border ${
|
||||
method === "cash"
|
||||
? "bg-general-600 border-primary-500"
|
||||
: "bg-white border-general-700"
|
||||
}`}
|
||||
>
|
||||
<Text
|
||||
className={`font-JakartaMedium ${
|
||||
method === "cash" ? "text-white" : "text-black"
|
||||
}`}
|
||||
>
|
||||
💵 Cash
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity
|
||||
onPress={() => setMethod("card")}
|
||||
className={`flex-1 items-center py-3 rounded-xl border ${
|
||||
method === "card"
|
||||
? "bg-general-600 border-primary-500"
|
||||
: "bg-white border-general-700"
|
||||
}`}
|
||||
>
|
||||
<Text
|
||||
className={`font-JakartaMedium ${
|
||||
method === "card" ? "text-white" : "text-black"
|
||||
}`}
|
||||
>
|
||||
💳 Card
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<CustomButton
|
||||
title={processing ? "Processing..." : "Confirm ride"}
|
||||
className="my-2"
|
||||
onPress={payWithAreeba}
|
||||
title={
|
||||
processing
|
||||
? "Processing..."
|
||||
: method === "cash"
|
||||
? "Book ride · Pay cash to driver"
|
||||
: "Confirm & Pay by Card"
|
||||
}
|
||||
className="my-2 mt-4"
|
||||
onPress={confirm}
|
||||
disabled={processing}
|
||||
/>
|
||||
|
||||
@@ -141,7 +213,9 @@ export const Payment = ({
|
||||
<Text className="text-base text-general-200 text-JakartaMedium text-center mt-3">
|
||||
Thank you for your booking.{"\n"} Your reservation has been placed.
|
||||
{"\n"}
|
||||
Please proceed with your trip.
|
||||
{method === "cash"
|
||||
? `Please have ${formatLBP(parseFloat(amount))} ready.`
|
||||
: null}
|
||||
</Text>
|
||||
|
||||
<CustomButton
|
||||
|
||||
@@ -82,15 +82,29 @@ export const RideCard = ({ ride }: { ride: Ride }) => {
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="flex flex-row items-center w-full justify-between mb-5">
|
||||
<Text className="font-JakartaMedium text-gray-500 text-xs">
|
||||
Fare
|
||||
</Text>
|
||||
|
||||
<Text className="font-JakartaMedium text-gray-500 text-xs">
|
||||
${(ride.fare_price / 100).toFixed(2)}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="flex flex-row items-center w-full justify-between mb-5">
|
||||
<Text className="font-JakartaMedium text-gray-500 text-xs">
|
||||
Payment Status
|
||||
</Text>
|
||||
|
||||
<Text
|
||||
className={`font-JakartaMedium capitalize text-gray-500 text-xs ${payment_status === "paid" ? "text-emerald-500" : "text-rose-500"}`}
|
||||
className={`font-JakartaMedium capitalize text-xs ${payment_status === "paid" ? "text-emerald-500" : "text-gray-500"}`}
|
||||
>
|
||||
{payment_status}
|
||||
{payment_status === "cash"
|
||||
? "Cash · Pay to driver"
|
||||
: payment_status === "paid"
|
||||
? "Paid by card"
|
||||
: payment_status}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export const LINKS = {
|
||||
sourceCode: "https://github.com/sanidhyy/uber-clone",
|
||||
} as const;
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Waseel Owner Dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1225
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "dashboard",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.4",
|
||||
"oxlint": "^1.75.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.2.0"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,64 @@
|
||||
import { useState } from "react";
|
||||
import "./index.css";
|
||||
import Login from "./Login";
|
||||
import Stats from "./pages/Stats";
|
||||
import Users from "./pages/Users";
|
||||
import Drivers from "./pages/Drivers";
|
||||
import Rides from "./pages/Rides";
|
||||
import { clearToken, getToken } from "./lib/api";
|
||||
|
||||
type Page = "stats" | "users" | "drivers" | "rides";
|
||||
|
||||
const NAV: { key: Page; label: string }[] = [
|
||||
{ key: "stats", label: "Overview" },
|
||||
{ key: "users", label: "Users" },
|
||||
{ key: "drivers", label: "Drivers & Fleet" },
|
||||
{ key: "rides", label: "Rides & Payments" },
|
||||
];
|
||||
|
||||
export default function App() {
|
||||
const [authed, setAuthed] = useState(Boolean(getToken()));
|
||||
const [page, setPage] = useState<Page>("stats");
|
||||
|
||||
if (!authed) {
|
||||
return <Login onDone={() => setAuthed(true)} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<nav className="sidebar">
|
||||
<h1>Waseel Owner</h1>
|
||||
{NAV.map((item) => (
|
||||
<a
|
||||
key={item.key}
|
||||
href="#"
|
||||
className={page === item.key ? "active" : ""}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setPage(item.key);
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</a>
|
||||
))}
|
||||
<a
|
||||
href="#"
|
||||
style={{ marginTop: "auto" }}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
clearToken();
|
||||
setAuthed(false);
|
||||
}}
|
||||
>
|
||||
Sign out
|
||||
</a>
|
||||
</nav>
|
||||
<main className="main">
|
||||
{page === "stats" && <Stats />}
|
||||
{page === "users" && <Users />}
|
||||
{page === "drivers" && <Drivers />}
|
||||
{page === "rides" && <Rides />}
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { api, setToken } from "./lib/api";
|
||||
|
||||
export default function Login({ onDone }: { onDone: () => void }) {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await api<{ data: { token: string; user: { role: string | null } } }>(
|
||||
"/auth/login",
|
||||
{ method: "POST", body: JSON.stringify({ email, password }) },
|
||||
);
|
||||
if (res.data.user.role !== "owner") {
|
||||
setError("This account does not have owner access.");
|
||||
return;
|
||||
}
|
||||
setToken(res.data.token);
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="login-wrap" onSubmit={submit}>
|
||||
<h2>Waseel Owner</h2>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<button disabled={busy}>{busy ? "Signing in…" : "Sign in"}</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,250 @@
|
||||
:root {
|
||||
--bg: #0f1117;
|
||||
--panel: #171a23;
|
||||
--border: #262b38;
|
||||
--text: #e8eaf0;
|
||||
--muted: #8a91a5;
|
||||
--accent: #4f7cff;
|
||||
--danger: #e5484d;
|
||||
--success: #30a46c;
|
||||
font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
#root {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 220px;
|
||||
background: var(--panel);
|
||||
border-right: 1px solid var(--border);
|
||||
padding: 20px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.sidebar h1 {
|
||||
font-size: 16px;
|
||||
margin: 0 8px 18px;
|
||||
}
|
||||
|
||||
.sidebar a {
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
padding: 9px 12px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.sidebar a.active,
|
||||
.sidebar a:hover {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
padding: 28px 32px;
|
||||
max-width: 1200px;
|
||||
}
|
||||
|
||||
.main h2 {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 14px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.card .label {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.card .value {
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
text-align: left;
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
th {
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.badge.owner { color: #b088ff; }
|
||||
.badge.driver { color: #4f7cff; }
|
||||
.badge.rider { color: #8a91a5; }
|
||||
.badge.paid { color: var(--success); border-color: var(--success); }
|
||||
.badge.unpaid { color: var(--danger); border-color: var(--danger); }
|
||||
|
||||
button,
|
||||
select,
|
||||
input {
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
background: var(--accent);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 8px 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
button.danger {
|
||||
background: transparent;
|
||||
border: 1px solid var(--danger);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 14px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--danger);
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.login-wrap {
|
||||
margin: auto;
|
||||
width: 340px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
padding: 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.login-wrap h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chart {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 6px;
|
||||
height: 160px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.chart .bar {
|
||||
flex: 1;
|
||||
background: var(--accent);
|
||||
border-radius: 4px 4px 0 0;
|
||||
min-height: 2px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.chart .bar span {
|
||||
position: absolute;
|
||||
bottom: -22px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
font-size: 10px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
padding: 24px;
|
||||
width: 420px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.modal input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
const API_URL =
|
||||
(import.meta.env.VITE_API_URL as string | undefined) ?? "";
|
||||
|
||||
let authToken: string | null = localStorage.getItem("owner_token");
|
||||
|
||||
export const setToken = (token: string) => {
|
||||
authToken = token;
|
||||
localStorage.setItem("owner_token", token);
|
||||
};
|
||||
|
||||
export const clearToken = () => {
|
||||
authToken = null;
|
||||
localStorage.removeItem("owner_token");
|
||||
};
|
||||
|
||||
export const getToken = () => authToken;
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export const api = async <T>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> => {
|
||||
const headers = new Headers(options.headers);
|
||||
if (!headers.has("Content-Type") && options.body) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
if (authToken) headers.set("Authorization", `Bearer ${authToken}`);
|
||||
|
||||
const res = await fetch(`${API_URL}${path}`, { ...options, headers });
|
||||
|
||||
if (res.status === 401) {
|
||||
clearToken();
|
||||
throw new ApiError("Session expired. Please sign in again.", 401);
|
||||
}
|
||||
|
||||
const body = await res.json().catch(() => ({}));
|
||||
|
||||
if (!res.ok) {
|
||||
throw new ApiError(body.error ?? `Request failed (${res.status})`, res.status);
|
||||
}
|
||||
|
||||
return body as T;
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { api } from "../lib/api";
|
||||
|
||||
type Driver = {
|
||||
id: number;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
profile_image_url: string | null;
|
||||
car_image_url: string | null;
|
||||
car_seats: number;
|
||||
rating: string;
|
||||
total_rides: number;
|
||||
revenue: number;
|
||||
};
|
||||
|
||||
const EMPTY = {
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
profile_image_url: "",
|
||||
car_image_url: "",
|
||||
car_seats: 4,
|
||||
rating: 4.5,
|
||||
};
|
||||
|
||||
export default function Drivers() {
|
||||
const [drivers, setDrivers] = useState<Driver[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<Driver | "new" | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const res = await api<{ data: Driver[] }>("/admin/drivers");
|
||||
setDrivers(res.data);
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const remove = async (id: number) => {
|
||||
if (!confirm("Delete this driver?")) return;
|
||||
try {
|
||||
await api(`/admin/drivers/${id}`, { method: "DELETE" });
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h2>Drivers & fleet</h2>
|
||||
<div className="toolbar">
|
||||
<button onClick={() => setEditing("new")}>Add driver</button>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Name</th>
|
||||
<th>Seats</th>
|
||||
<th>Rating</th>
|
||||
<th>Rides</th>
|
||||
<th>Revenue</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{drivers.map((d) => (
|
||||
<tr key={d.id}>
|
||||
<td>{d.id}</td>
|
||||
<td>
|
||||
{d.first_name} {d.last_name}
|
||||
</td>
|
||||
<td>{d.car_seats}</td>
|
||||
<td>{d.rating}</td>
|
||||
<td>{d.total_rides}</td>
|
||||
<td>{d.revenue.toLocaleString()}</td>
|
||||
<td>
|
||||
<div className="row-actions">
|
||||
<button className="secondary" onClick={() => setEditing(d)}>
|
||||
Edit
|
||||
</button>
|
||||
<button className="danger" onClick={() => remove(d.id)}>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{editing && (
|
||||
<DriverForm
|
||||
initial={editing === "new" ? null : editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => {
|
||||
setEditing(null);
|
||||
load();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DriverForm({
|
||||
initial,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
initial: Driver | null;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const [form, setForm] = useState(
|
||||
initial
|
||||
? {
|
||||
first_name: initial.first_name,
|
||||
last_name: initial.last_name,
|
||||
profile_image_url: initial.profile_image_url ?? "",
|
||||
car_image_url: initial.car_image_url ?? "",
|
||||
car_seats: initial.car_seats,
|
||||
rating: Number(initial.rating),
|
||||
}
|
||||
: { ...EMPTY },
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const set = (key: keyof typeof form) => (e: { target: { value: string } }) =>
|
||||
setForm((f) => ({
|
||||
...f,
|
||||
[key]:
|
||||
key === "car_seats" || key === "rating"
|
||||
? Number(e.target.value)
|
||||
: e.target.value,
|
||||
}));
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(initial ? `/admin/drivers/${initial.id}` : "/admin/drivers", {
|
||||
method: initial ? "PATCH" : "POST",
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
onSaved();
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<form className="modal" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
|
||||
<h3>{initial ? `Edit driver #${initial.id}` : "New driver"}</h3>
|
||||
<input placeholder="First name" value={form.first_name} onChange={set("first_name")} required />
|
||||
<input placeholder="Last name" value={form.last_name} onChange={set("last_name")} required />
|
||||
<input placeholder="Profile image URL" value={form.profile_image_url} onChange={set("profile_image_url")} />
|
||||
<input placeholder="Car image URL" value={form.car_image_url} onChange={set("car_image_url")} />
|
||||
<label>
|
||||
Seats{" "}
|
||||
<select value={form.car_seats} onChange={set("car_seats")}>
|
||||
{[2, 4, 6, 7].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="1"
|
||||
max="5"
|
||||
placeholder="Rating"
|
||||
value={form.rating}
|
||||
onChange={set("rating")}
|
||||
/>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<div className="row-actions">
|
||||
<button disabled={busy}>{busy ? "Saving…" : "Save"}</button>
|
||||
<button type="button" className="secondary" onClick={onClose}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "../lib/api";
|
||||
|
||||
type Ride = {
|
||||
ride_id: number;
|
||||
origin_address: string;
|
||||
destination_address: string;
|
||||
ride_time: number;
|
||||
fare_price: number;
|
||||
payment_status: string;
|
||||
created_at: string;
|
||||
user_email: string;
|
||||
driver: { driver_id: number; name: string; rating: number };
|
||||
};
|
||||
|
||||
export default function Rides() {
|
||||
const [rides, setRides] = useState<Ride[]>([]);
|
||||
const [status, setStatus] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async (status: string) => {
|
||||
try {
|
||||
const res = await api<{ data: Ride[] }>(
|
||||
`/admin/rides${status ? `?status=${encodeURIComponent(status)}` : ""}`,
|
||||
);
|
||||
setRides(res.data);
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load(status);
|
||||
}, [load, status]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h2>Rides & payments</h2>
|
||||
<div className="toolbar">
|
||||
<select value={status} onChange={(e) => setStatus(e.target.value)}>
|
||||
<option value="">All payments</option>
|
||||
<option value="paid">Paid</option>
|
||||
<option value="unpaid">Unpaid</option>
|
||||
</select>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Route</th>
|
||||
<th>User</th>
|
||||
<th>Driver</th>
|
||||
<th>Time (min)</th>
|
||||
<th>Fare</th>
|
||||
<th>Payment</th>
|
||||
<th>Date</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rides.map((r) => (
|
||||
<tr key={r.ride_id}>
|
||||
<td>{r.ride_id}</td>
|
||||
<td>
|
||||
{r.origin_address} → {r.destination_address}
|
||||
</td>
|
||||
<td>{r.user_email}</td>
|
||||
<td>{r.driver.name}</td>
|
||||
<td>{r.ride_time}</td>
|
||||
<td>{r.fare_price.toLocaleString()}</td>
|
||||
<td>
|
||||
<span
|
||||
className={`badge ${
|
||||
r.payment_status.toLowerCase() === "paid" ? "paid" : "unpaid"
|
||||
}`}
|
||||
>
|
||||
{r.payment_status}
|
||||
</span>
|
||||
</td>
|
||||
<td>{new Date(r.created_at).toLocaleString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api } from "../lib/api";
|
||||
|
||||
type Stats = {
|
||||
totals: { users: number; drivers: number; rides: number; revenue: number };
|
||||
trend: { day: string; rides: number; revenue: number }[];
|
||||
topDrivers: { driver_id: number; name: string; rides: number; revenue: number }[];
|
||||
};
|
||||
|
||||
export default function Stats() {
|
||||
const [stats, setStats] = useState<Stats | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api<{ data: Stats }>("/admin/stats")
|
||||
.then((r) => setStats(r.data))
|
||||
.catch((e) => setError(e.message));
|
||||
}, []);
|
||||
|
||||
if (error) return <div className="error">{error}</div>;
|
||||
if (!stats) return <div>Loading…</div>;
|
||||
|
||||
const maxRides = Math.max(1, ...stats.trend.map((d) => d.rides));
|
||||
|
||||
return (
|
||||
<>
|
||||
<h2>Overview</h2>
|
||||
<div className="cards">
|
||||
<div className="card">
|
||||
<div className="label">Users</div>
|
||||
<div className="value">{stats.totals.users}</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="label">Drivers</div>
|
||||
<div className="value">{stats.totals.drivers}</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="label">Rides</div>
|
||||
<div className="value">{stats.totals.rides}</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="label">Revenue (paid)</div>
|
||||
<div className="value">{stats.totals.revenue.toLocaleString()}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Rides — last 14 days</h2>
|
||||
<div className="chart" style={{ marginBottom: 40 }}>
|
||||
{stats.trend.map((d) => (
|
||||
<div
|
||||
key={d.day}
|
||||
className="bar"
|
||||
style={{ height: `${(d.rides / maxRides) * 100}%` }}
|
||||
title={`${d.day}: ${d.rides} rides`}
|
||||
>
|
||||
<span>{d.day.slice(5)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<h2>Top drivers</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Driver</th>
|
||||
<th>Rides</th>
|
||||
<th>Revenue</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{stats.topDrivers.map((d) => (
|
||||
<tr key={d.driver_id}>
|
||||
<td>{d.name}</td>
|
||||
<td>{d.rides}</td>
|
||||
<td>{d.revenue.toLocaleString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "../lib/api";
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string | null;
|
||||
email_verified: boolean;
|
||||
created_at: string;
|
||||
rides: number;
|
||||
};
|
||||
|
||||
const ROLES = ["rider", "driver", "owner"];
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [query, setQuery] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async (q: string) => {
|
||||
try {
|
||||
const res = await api<{ data: User[] }>(
|
||||
`/admin/users${q ? `?q=${encodeURIComponent(q)}` : ""}`,
|
||||
);
|
||||
setUsers(res.data);
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load("");
|
||||
}, [load]);
|
||||
|
||||
const setRole = async (id: string, role: string) => {
|
||||
try {
|
||||
await api(`/admin/users/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ role }),
|
||||
});
|
||||
await load(query);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleVerified = async (u: User) => {
|
||||
try {
|
||||
await api(`/admin/users/${u.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ email_verified: !u.email_verified }),
|
||||
});
|
||||
await load(query);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h2>Users</h2>
|
||||
<div className="toolbar">
|
||||
<input
|
||||
placeholder="Search name or email…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && load(query)}
|
||||
/>
|
||||
<button className="secondary" onClick={() => load(query)}>
|
||||
Search
|
||||
</button>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Email</th>
|
||||
<th>Role</th>
|
||||
<th>Verified</th>
|
||||
<th>Rides</th>
|
||||
<th>Joined</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => (
|
||||
<tr key={u.id}>
|
||||
<td>{u.name}</td>
|
||||
<td>{u.email}</td>
|
||||
<td>
|
||||
<select
|
||||
value={u.role ?? ""}
|
||||
onChange={(e) => setRole(u.id, e.target.value)}
|
||||
>
|
||||
<option value="">— none —</option>
|
||||
{ROLES.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`badge ${u.email_verified ? "paid" : "unpaid"}`}>
|
||||
{u.email_verified ? "yes" : "no"}
|
||||
</span>
|
||||
</td>
|
||||
<td>{u.rides}</td>
|
||||
<td>{new Date(u.created_at).toLocaleDateString()}</td>
|
||||
<td>
|
||||
<button className="secondary" onClick={() => toggleVerified(u)}>
|
||||
{u.email_verified ? "Unverify" : "Verify"}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { defineConfig, type ProxyOptions } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
const API_TARGET = process.env.API_PROXY_TARGET ?? 'http://localhost:8081'
|
||||
|
||||
// Proxy API calls through the dev server so the dashboard is same-origin.
|
||||
// Expo's dev-server CORS middleware rejects foreign Origin headers, so
|
||||
// the proxy strips them before forwarding.
|
||||
const proxy: Record<string, ProxyOptions> = {}
|
||||
for (const path of ['/auth', '/user', '/ride', '/driver', '/admin']) {
|
||||
proxy[path] = {
|
||||
target: API_TARGET,
|
||||
changeOrigin: true,
|
||||
configure: (p) => {
|
||||
p.on('proxyReq', (req) => {
|
||||
req.removeHeader('origin')
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: { proxy },
|
||||
})
|
||||
Vendored
+18
-3
@@ -4,12 +4,27 @@ export {};
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
interface ProcessEnv {
|
||||
// clerk publishable key
|
||||
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: string;
|
||||
// self-hosted auth
|
||||
AUTH_JWT_SECRET: string;
|
||||
GOOGLE_OAUTH_CLIENT_ID: string;
|
||||
|
||||
// postgres db url (neon db)
|
||||
// postgres db url (self-hosted)
|
||||
DATABASE_URL: string;
|
||||
|
||||
// expo api server url
|
||||
EXPO_PUBLIC_SERVER_URL: string;
|
||||
|
||||
// google oauth client ids
|
||||
EXPO_PUBLIC_GOOGLE_AUTH_WEB_CLIENT_ID: string;
|
||||
EXPO_PUBLIC_GOOGLE_AUTH_IOS_CLIENT_ID: string;
|
||||
EXPO_PUBLIC_GOOGLE_AUTH_ANDROID_CLIENT_ID: string;
|
||||
|
||||
// gmail api
|
||||
GMAIL_CLIENT_ID: string;
|
||||
GMAIL_CLIENT_SECRET: string;
|
||||
GMAIL_REFRESH_TOKEN: string;
|
||||
GMAIL_FROM: string;
|
||||
|
||||
// geoapify api key
|
||||
EXPO_PUBLIC_GEOAPIFY_API_KEY: string;
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { sql } from "@/lib/db";
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
|
||||
export const corsHeaders: Record<string, string> = {
|
||||
"Access-Control-Allow-Origin": process.env.ADMIN_CORS_ORIGIN ?? "*",
|
||||
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
};
|
||||
|
||||
export const withCors = (response: Response): Response => {
|
||||
for (const [key, value] of Object.entries(corsHeaders)) {
|
||||
response.headers.set(key, value);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
export const preflight = (): Response => withCors(new Response(null, { status: 204 }));
|
||||
|
||||
// Returns the authenticated owner or a ready-to-return error Response.
|
||||
export const requireOwner = async (
|
||||
req: Request,
|
||||
): Promise<{ userId: string; email: string } | { error: Response }> => {
|
||||
const auth = requireAuth(req);
|
||||
if ("error" in auth) return auth;
|
||||
|
||||
const rows = await sql<{ role: string | null }>`
|
||||
SELECT role FROM users WHERE id = ${auth.userId}
|
||||
`;
|
||||
|
||||
if (rows[0]?.role !== "owner") {
|
||||
return {
|
||||
error: Response.json({ error: "Forbidden." }, { status: 403 }),
|
||||
};
|
||||
}
|
||||
|
||||
return auth;
|
||||
};
|
||||
+13
-89
@@ -1,97 +1,21 @@
|
||||
import type {
|
||||
StartOAuthFlowParams,
|
||||
StartOAuthFlowReturnType,
|
||||
} from "@clerk/clerk-expo";
|
||||
import * as Linking from "expo-linking";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
|
||||
import { fetchAPI } from "./fetch";
|
||||
import type { SessionUser } from "./session";
|
||||
|
||||
export interface TokenCache {
|
||||
getToken: (key: string) => Promise<string | undefined | null>;
|
||||
saveToken: (key: string, token: string) => Promise<void>;
|
||||
clearToken?: (key: string) => void;
|
||||
}
|
||||
|
||||
export const tokenCache = {
|
||||
async getToken(key: string) {
|
||||
try {
|
||||
const item = await SecureStore.getItemAsync(key);
|
||||
|
||||
return item;
|
||||
} catch (error) {
|
||||
console.error("GET_TOKEN_CACHE: ", error);
|
||||
|
||||
await SecureStore.deleteItemAsync(key);
|
||||
|
||||
return null;
|
||||
}
|
||||
},
|
||||
async saveToken(key: string, value: string) {
|
||||
try {
|
||||
return SecureStore.setItemAsync(key, value);
|
||||
} catch (err) {
|
||||
console.error("SAVE_TOKEN_CACHE: ", err);
|
||||
|
||||
return;
|
||||
}
|
||||
},
|
||||
export type AuthResult = {
|
||||
token: string;
|
||||
user: SessionUser;
|
||||
};
|
||||
|
||||
type StartOAuthFlowType = (
|
||||
startOAuthFlowParams?: StartOAuthFlowParams,
|
||||
) => Promise<StartOAuthFlowReturnType>;
|
||||
|
||||
export const googleOAuth = async (startOAuthFlow: StartOAuthFlowType) => {
|
||||
try {
|
||||
// No explicit scheme: in Expo Go this resolves to exp://... so the
|
||||
// browser can redirect back into the app; in a standalone build it
|
||||
// automatically uses the app.json scheme ("waseel").
|
||||
const { createdSessionId, signUp, setActive } = await startOAuthFlow({
|
||||
redirectUrl: Linking.createURL("/(root)/(tabs)/home"),
|
||||
});
|
||||
|
||||
if (createdSessionId) {
|
||||
if (setActive) {
|
||||
await setActive!({ session: createdSessionId });
|
||||
|
||||
if (signUp && signUp.createdUserId) {
|
||||
await fetchAPI("/(api)/user", {
|
||||
// Exchanges a Google idToken (obtained via expo-auth-session on the client)
|
||||
// for a Waseel session issued by our own server.
|
||||
export const googleAuth = async (
|
||||
idToken: string,
|
||||
): Promise<AuthResult> => {
|
||||
const response = await fetchAPI("/(api)/auth/google", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: `${signUp.firstName} ${signUp.lastName}`,
|
||||
email: signUp.emailAddress,
|
||||
clerkId: signUp.createdUserId,
|
||||
}),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ idToken }),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
code: "success",
|
||||
message: "You are logged in.",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
code: "failed",
|
||||
message: "An error occured.",
|
||||
};
|
||||
} else {
|
||||
// Use signIn or signUp for next steps such as MFA
|
||||
}
|
||||
} catch (err) {
|
||||
console.log("[OAUTH]: ", err);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
code: (
|
||||
err as {
|
||||
code?: string;
|
||||
}
|
||||
)?.code,
|
||||
message: "Internal Server Error.",
|
||||
};
|
||||
}
|
||||
return response.data as AuthResult;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Pool, type QueryResultRow } from "pg";
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30_000,
|
||||
connectionTimeoutMillis: 10_000,
|
||||
});
|
||||
|
||||
type SqlValue = string | number | boolean | null | Date;
|
||||
|
||||
export async function sql<R extends QueryResultRow = QueryResultRow>(
|
||||
strings: TemplateStringsArray,
|
||||
...values: SqlValue[]
|
||||
): Promise<R[]> {
|
||||
const text = strings.reduce(
|
||||
(acc, chunk, i) =>
|
||||
acc + chunk + (i < values.length ? `$${i + 1}` : ""),
|
||||
"",
|
||||
);
|
||||
|
||||
const result = await pool.query<R>(text, values);
|
||||
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
export async function transaction<T>(
|
||||
callback: (
|
||||
tx: <R extends QueryResultRow = QueryResultRow>(
|
||||
strings: TemplateStringsArray,
|
||||
...values: SqlValue[]
|
||||
) => Promise<R[]>,
|
||||
) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const client = await pool.connect();
|
||||
|
||||
try {
|
||||
await client.query("BEGIN");
|
||||
|
||||
const tx = async <R extends QueryResultRow = QueryResultRow>(
|
||||
strings: TemplateStringsArray,
|
||||
...values: SqlValue[]
|
||||
) => {
|
||||
const text = strings.reduce(
|
||||
(acc, chunk, i) =>
|
||||
acc + chunk + (i < values.length ? `$${i + 1}` : ""),
|
||||
"",
|
||||
);
|
||||
|
||||
const result = await client.query<R>(text, values);
|
||||
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
const out = await callback(tx);
|
||||
|
||||
await client.query("COMMIT");
|
||||
|
||||
return out;
|
||||
} catch (error) {
|
||||
await client.query("ROLLBACK");
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
+19
-2
@@ -1,10 +1,27 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
|
||||
// Set by lib/session.tsx once a token is available; read synchronously here so
|
||||
// callers never have to await SecureStore before every request.
|
||||
let authToken: string | null = null;
|
||||
|
||||
export const setAuthToken = (token: string) => {
|
||||
authToken = token;
|
||||
};
|
||||
|
||||
export const clearAuthToken = () => {
|
||||
authToken = null;
|
||||
};
|
||||
|
||||
export const fetchAPI = async (url: string, options?: RequestInit) => {
|
||||
try {
|
||||
const response = await fetch(url, options);
|
||||
const headers = new Headers(options?.headers);
|
||||
if (authToken && !headers.has("Authorization")) {
|
||||
headers.set("Authorization", `Bearer ${authToken}`);
|
||||
}
|
||||
|
||||
const response = await fetch(url, { ...options, headers });
|
||||
if (!response.ok) {
|
||||
new Error(`HTTP error! status: ${response.status}`);
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { createHmac, timingSafeEqual } from "crypto";
|
||||
|
||||
const base64Url = (input: Buffer | string): string =>
|
||||
Buffer.from(input)
|
||||
.toString("base64")
|
||||
.replace(/=/g, "")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_");
|
||||
|
||||
const fromBase64Url = (input: string): Buffer =>
|
||||
Buffer.from(input.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
||||
|
||||
export type JwtPayload = {
|
||||
sub: string;
|
||||
email: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
const secret = (): string => {
|
||||
const value = process.env.AUTH_JWT_SECRET;
|
||||
if (!value) throw new Error("Missing AUTH_JWT_SECRET.");
|
||||
return value;
|
||||
};
|
||||
|
||||
export const signJwt = (
|
||||
payload: { sub: string; email: string },
|
||||
expiresInSeconds = 30 * 24 * 60 * 60,
|
||||
): string => {
|
||||
const iat = Math.floor(Date.now() / 1000);
|
||||
const body: JwtPayload = { ...payload, iat, exp: iat + expiresInSeconds };
|
||||
|
||||
const header = base64Url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
|
||||
const claims = base64Url(JSON.stringify(body));
|
||||
const signature = base64Url(
|
||||
createHmac("sha256", secret()).update(`${header}.${claims}`).digest(),
|
||||
);
|
||||
|
||||
return `${header}.${claims}.${signature}`;
|
||||
};
|
||||
|
||||
export const verifyJwt = (token: string): JwtPayload | null => {
|
||||
const parts = token.split(".");
|
||||
if (parts.length !== 3) return null;
|
||||
|
||||
const [header, claims, signature] = parts;
|
||||
|
||||
const expected = createHmac("sha256", secret())
|
||||
.update(`${header}.${claims}`)
|
||||
.digest();
|
||||
|
||||
const received = fromBase64Url(signature);
|
||||
|
||||
if (
|
||||
expected.length !== received.length ||
|
||||
!timingSafeEqual(expected, received)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(fromBase64Url(claims).toString()) as JwtPayload;
|
||||
|
||||
if (payload.exp * 1000 < Date.now()) return null;
|
||||
|
||||
return payload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Returns the authenticated principal or a ready-to-return error Response.
|
||||
export const requireAuth = (
|
||||
req: Request,
|
||||
): { userId: string; email: string } | { error: Response } => {
|
||||
const header = req.headers.get("authorization") ?? "";
|
||||
const token = header.startsWith("Bearer ") ? header.slice(7) : "";
|
||||
|
||||
const payload = token ? verifyJwt(token) : null;
|
||||
|
||||
if (!payload) {
|
||||
return {
|
||||
error: Response.json({ error: "Unauthorized." }, { status: 401 }),
|
||||
};
|
||||
}
|
||||
|
||||
return { userId: payload.sub, email: payload.email };
|
||||
};
|
||||
|
||||
export const decodeJwtExp = (token: string): number | null => {
|
||||
try {
|
||||
const claims = JSON.parse(
|
||||
fromBase64Url(token.split(".")[1]).toString(),
|
||||
) as JwtPayload;
|
||||
|
||||
return claims.exp ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,96 @@
|
||||
// Sends transactional email through the Gmail API using an OAuth2 refresh
|
||||
// token (no third-party email service needed on a self-hosted box).
|
||||
//
|
||||
// Setup (one-time):
|
||||
// 1. Google Cloud console -> enable Gmail API, create an OAuth client.
|
||||
// 2. Generate a refresh token with scope
|
||||
// https://www.googleapis.com/auth/gmail.send
|
||||
// 3. Set GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET, GMAIL_REFRESH_TOKEN, GMAIL_FROM.
|
||||
|
||||
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
||||
const SEND_URL = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send";
|
||||
|
||||
let cachedAccessToken: { token: string; expiresAt: number } | null = null;
|
||||
|
||||
const getAccessToken = async (): Promise<string | null> => {
|
||||
const clientId = process.env.GMAIL_CLIENT_ID;
|
||||
const clientSecret = process.env.GMAIL_CLIENT_SECRET;
|
||||
const refreshToken = process.env.GMAIL_REFRESH_TOKEN;
|
||||
|
||||
if (!clientId || !clientSecret || !refreshToken) return null;
|
||||
|
||||
if (cachedAccessToken && cachedAccessToken.expiresAt > Date.now() + 60_000) {
|
||||
return cachedAccessToken.token;
|
||||
}
|
||||
|
||||
const response = await fetch(TOKEN_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
refresh_token: refreshToken,
|
||||
grant_type: "refresh_token",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Gmail token exchange failed: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
};
|
||||
|
||||
cachedAccessToken = {
|
||||
token: data.access_token,
|
||||
expiresAt: Date.now() + data.expires_in * 1000,
|
||||
};
|
||||
|
||||
return cachedAccessToken.token;
|
||||
};
|
||||
|
||||
export const sendEmail = async (
|
||||
to: string,
|
||||
subject: string,
|
||||
text: string,
|
||||
): Promise<void> => {
|
||||
const accessToken = await getAccessToken();
|
||||
if (!accessToken) {
|
||||
// Not configured: fall back to the server log so development still works.
|
||||
console.log(`[MAIL to=${to}] ${subject}\n${text}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const from = process.env.GMAIL_FROM;
|
||||
if (!from) throw new Error("Missing GMAIL_FROM.");
|
||||
|
||||
const mime = [
|
||||
`From: ${from}`,
|
||||
`To: ${to}`,
|
||||
`Subject: ${subject}`,
|
||||
"Content-Type: text/plain; charset=UTF-8",
|
||||
"",
|
||||
text,
|
||||
].join("\r\n");
|
||||
|
||||
const response = await fetch(SEND_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
raw: Buffer.from(mime)
|
||||
.toString("base64")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, ""),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Gmail send failed: ${response.status}`);
|
||||
}
|
||||
};
|
||||
+24
-10
@@ -1,3 +1,4 @@
|
||||
import { calculateFare } from "@/lib/pricing";
|
||||
import type { Driver, MarkerData } from "@/types/type";
|
||||
|
||||
const directionsAPI = process.env.EXPO_PUBLIC_GOOGLE_API_KEY;
|
||||
@@ -37,11 +38,12 @@ export const calculateRegion = ({
|
||||
destinationLongitude?: number | null;
|
||||
}) => {
|
||||
if (!userLatitude || !userLongitude) {
|
||||
// Default to Beirut, Lebanon.
|
||||
return {
|
||||
latitude: 37.78825,
|
||||
longitude: -122.4324,
|
||||
latitudeDelta: 0.01,
|
||||
longitudeDelta: 0.01,
|
||||
latitude: 33.8938,
|
||||
longitude: 35.5018,
|
||||
latitudeDelta: 0.09,
|
||||
longitudeDelta: 0.09,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -100,20 +102,32 @@ export const calculateDriverTimes = async ({
|
||||
`https://maps.googleapis.com/maps/api/directions/json?origin=${marker.latitude},${marker.longitude}&destination=${userLatitude},${userLongitude}&key=${directionsAPI}`,
|
||||
);
|
||||
const dataToUser = await responseToUser.json();
|
||||
const timeToUser = dataToUser.routes[0].legs[0].duration.value; // Time in seconds
|
||||
|
||||
const responseToDestination = await fetch(
|
||||
`https://maps.googleapis.com/maps/api/directions/json?origin=${userLatitude},${userLongitude}&destination=${destinationLatitude},${destinationLongitude}&key=${directionsAPI}`,
|
||||
);
|
||||
const dataToDestination = await responseToDestination.json();
|
||||
|
||||
const timeToDestination =
|
||||
dataToDestination.routes[0].legs[0].duration.value; // Time in seconds
|
||||
// Google returns no routes when a leg is unreachable (ZERO_RESULTS).
|
||||
const legToUser = dataToUser.routes?.[0]?.legs?.[0];
|
||||
const legToDestination = dataToDestination.routes?.[0]?.legs?.[0];
|
||||
if (!legToUser || !legToDestination) {
|
||||
return { ...marker, time: 0, price: "0.00" };
|
||||
}
|
||||
|
||||
const totalTime = (timeToUser + timeToDestination) / 60; // Total time in minutes
|
||||
const price = (totalTime * 0.5).toFixed(2); // Calculate price based on time
|
||||
const timeToUser = legToUser.duration.value; // Pickup ETA in seconds
|
||||
const timeToDestination = legToDestination.duration.value; // Trip duration in seconds
|
||||
|
||||
return { ...marker, time: totalTime, price };
|
||||
// The rider pays for the trip leg only (distance + duration) —
|
||||
// never for the driver's approach.
|
||||
const price = calculateFare({
|
||||
distanceMeters: legToDestination.distance.value,
|
||||
durationSeconds: timeToDestination,
|
||||
});
|
||||
|
||||
const totalTripTime = (timeToUser + timeToDestination) / 60; // Minutes until drop-off
|
||||
|
||||
return { ...marker, time: totalTripTime, price };
|
||||
});
|
||||
|
||||
return await Promise.all(timesPromises);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from "crypto";
|
||||
|
||||
const KEY_LENGTH = 64;
|
||||
|
||||
export const hashPassword = (password: string): string => {
|
||||
const salt = randomBytes(16).toString("hex");
|
||||
const hash = scryptSync(password, salt, KEY_LENGTH).toString("hex");
|
||||
return `scrypt:${salt}:${hash}`;
|
||||
};
|
||||
|
||||
export const verifyPassword = (
|
||||
password: string,
|
||||
stored: string,
|
||||
): boolean => {
|
||||
const [scheme, salt, hash] = stored.split(":");
|
||||
if (scheme !== "scrypt" || !salt || !hash) return false;
|
||||
|
||||
const candidate = scryptSync(password, salt, KEY_LENGTH);
|
||||
const expected = Buffer.from(hash, "hex");
|
||||
|
||||
return (
|
||||
candidate.length === expected.length && timingSafeEqual(candidate, expected)
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
// Fare model tuned to the Lebanese market:
|
||||
// - Distance-based with a base fare (like CTaxi/local taxis), not time-only.
|
||||
// - Typical Beirut rides land in the $3–8 range riders expect.
|
||||
// - Prices are quoted in USD (the de facto ride-hailing currency) with an
|
||||
// L.B.P. equivalent shown for cash settlement.
|
||||
|
||||
export const FARE = {
|
||||
base: 1.5, // USD, flag drop
|
||||
perKm: 0.55, // USD per kilometer of the trip
|
||||
perMin: 0.15, // USD per minute of the trip
|
||||
minimum: 3.0, // USD minimum fare
|
||||
} as const;
|
||||
|
||||
// Parallel market rate used for the L.B.P. cash equivalent shown in-app.
|
||||
export const LBP_RATE = 89500;
|
||||
|
||||
export const calculateFare = ({
|
||||
distanceMeters,
|
||||
durationSeconds,
|
||||
}: {
|
||||
distanceMeters: number;
|
||||
durationSeconds: number;
|
||||
}): string => {
|
||||
const km = distanceMeters / 1000;
|
||||
const minutes = durationSeconds / 60;
|
||||
|
||||
const fare = FARE.base + km * FARE.perKm + minutes * FARE.perMin;
|
||||
|
||||
return Math.max(fare, FARE.minimum).toFixed(2);
|
||||
};
|
||||
|
||||
// Rounds to the nearest 1,000 L.B.P. — the smallest practical cash note.
|
||||
export const formatLBP = (usd: number): string =>
|
||||
`${(Math.round((usd * LBP_RATE) / 1000) * 1000).toLocaleString("en-US")} L.B.P.`;
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
|
||||
import { setAuthToken, clearAuthToken } from "./fetch";
|
||||
|
||||
const TOKEN_KEY = "waseel_auth_token";
|
||||
const USER_KEY = "waseel_auth_user";
|
||||
const DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
export type SessionUser = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role?: string | null;
|
||||
avatarUrl?: string | null;
|
||||
};
|
||||
|
||||
type AuthResult = { token: string; user: SessionUser };
|
||||
|
||||
type SessionContextValue = {
|
||||
isLoaded: boolean;
|
||||
isSignedIn: boolean;
|
||||
userId: string | null;
|
||||
user: SessionUser | null;
|
||||
setSession: (result: AuthResult) => Promise<void>;
|
||||
setUserRole: (role: string) => void;
|
||||
signOut: () => Promise<void>;
|
||||
};
|
||||
|
||||
const SessionContext = createContext<SessionContextValue | null>(null);
|
||||
|
||||
// Mirrors lib/jwt.ts payload decoding (no signature check needed client-side).
|
||||
export const decodeJwtExp = (token: string): number | null => {
|
||||
try {
|
||||
const claims = JSON.parse(
|
||||
atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")),
|
||||
);
|
||||
return typeof claims.exp === "number" ? claims.exp : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const SessionProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
const [user, setUser] = useState<SessionUser | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const restore = async () => {
|
||||
try {
|
||||
const [token, storedUser] = await Promise.all([
|
||||
SecureStore.getItemAsync(TOKEN_KEY),
|
||||
SecureStore.getItemAsync(USER_KEY),
|
||||
]);
|
||||
|
||||
if (!token || !storedUser) return;
|
||||
|
||||
const exp = decodeJwtExp(token) ?? 0;
|
||||
if (exp * 1000 < Date.now()) {
|
||||
await SecureStore.deleteItemAsync(TOKEN_KEY);
|
||||
await SecureStore.deleteItemAsync(USER_KEY);
|
||||
return;
|
||||
}
|
||||
|
||||
if (cancelled) return;
|
||||
|
||||
setAuthToken(token);
|
||||
setUser(JSON.parse(storedUser) as SessionUser);
|
||||
} catch (error) {
|
||||
console.error("[SESSION_RESTORE]: ", error);
|
||||
} finally {
|
||||
if (!cancelled) setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
void restore();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const setSession = useCallback(async (result: AuthResult) => {
|
||||
setAuthToken(result.token);
|
||||
setUser(result.user);
|
||||
|
||||
await SecureStore.setItemAsync(TOKEN_KEY, result.token);
|
||||
await SecureStore.setItemAsync(USER_KEY, JSON.stringify(result.user));
|
||||
}, []);
|
||||
|
||||
const setUserRole = useCallback(
|
||||
(role: string) => {
|
||||
setUser((currentUser) => {
|
||||
if (!currentUser) return currentUser;
|
||||
|
||||
const updated = { ...currentUser, role };
|
||||
|
||||
void SecureStore.setItemAsync(USER_KEY, JSON.stringify(updated));
|
||||
|
||||
return updated;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
clearAuthToken();
|
||||
setUser(null);
|
||||
|
||||
await SecureStore.deleteItemAsync(TOKEN_KEY);
|
||||
await SecureStore.deleteItemAsync(USER_KEY);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<SessionContextValue>(
|
||||
() => ({
|
||||
isLoaded,
|
||||
isSignedIn: user !== null,
|
||||
userId: user?.id ?? null,
|
||||
user,
|
||||
setSession,
|
||||
setUserRole,
|
||||
signOut,
|
||||
}),
|
||||
[isLoaded, user, setSession, setUserRole, signOut],
|
||||
);
|
||||
|
||||
return (
|
||||
<SessionContext.Provider value={value}>
|
||||
{children}
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useSession = (): SessionContextValue => {
|
||||
const context = useContext(SessionContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useSession must be used within a SessionProvider.");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
// Alias kept for parity with the previous auth API.
|
||||
export const useAuth = useSession;
|
||||
|
||||
export const TOKEN_TTL_SECONDS = DEFAULT_TOKEN_TTL_SECONDS;
|
||||
@@ -0,0 +1,39 @@
|
||||
import { sql } from "@/lib/db";
|
||||
import { signJwt } from "@/lib/jwt";
|
||||
|
||||
export type UserProfile = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string | null;
|
||||
};
|
||||
|
||||
type UserRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string | null;
|
||||
};
|
||||
|
||||
export const toProfile = (row: UserRow): UserProfile => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
email: row.email,
|
||||
role: row.role,
|
||||
});
|
||||
|
||||
export const issueSession = (
|
||||
row: UserRow,
|
||||
): { token: string; user: UserProfile } => ({
|
||||
token: signJwt({ sub: row.id, email: row.email }),
|
||||
user: toProfile(row),
|
||||
});
|
||||
|
||||
export const findUserByEmail = async (
|
||||
email: string,
|
||||
): Promise<UserRow | null> => {
|
||||
const rows = await sql<UserRow>`
|
||||
SELECT id, name, email, role FROM users WHERE email = ${email}
|
||||
`;
|
||||
return rows[0] ?? null;
|
||||
};
|
||||
+6
-9
@@ -1,20 +1,17 @@
|
||||
import type { Ride } from "@/types/type";
|
||||
|
||||
export const sortRides = (rides: Ride[]): Ride[] => {
|
||||
const result = rides.sort((a, b) => {
|
||||
const dateA = new Date(`${a.created_at}T${a.ride_time}`);
|
||||
const dateB = new Date(`${b.created_at}T${b.ride_time}`);
|
||||
return dateB.getTime() - dateA.getTime();
|
||||
});
|
||||
|
||||
return result.reverse();
|
||||
return [...rides].sort(
|
||||
(a, b) =>
|
||||
new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
|
||||
);
|
||||
};
|
||||
|
||||
export function formatTime(minutes: number): string {
|
||||
const formattedMinutes = +minutes?.toFixed(0) || 0;
|
||||
const formattedMinutes = Math.round(minutes) || 0;
|
||||
|
||||
if (formattedMinutes < 60) {
|
||||
return `${minutes} min`;
|
||||
return `${formattedMinutes} min`;
|
||||
} else {
|
||||
const hours = Math.floor(formattedMinutes / 60);
|
||||
const remainingMinutes = formattedMinutes % 60;
|
||||
|
||||
Generated
+953
-2470
File diff suppressed because it is too large
Load Diff
+3
-4
@@ -28,10 +28,8 @@
|
||||
"uber-clone",
|
||||
"uber",
|
||||
"expo-router",
|
||||
"clerk",
|
||||
"postgresql",
|
||||
"alert",
|
||||
"neon-postgres",
|
||||
"zustand",
|
||||
"mysql",
|
||||
"google-maps",
|
||||
@@ -72,17 +70,16 @@
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"@clerk/clerk-expo": "^2.2.5",
|
||||
"@expo/metro-runtime": "~3.2.3",
|
||||
"@expo/vector-icons": "^14.0.2",
|
||||
"@gorhom/bottom-sheet": "^4.6.4",
|
||||
"@neondatabase/serverless": "^0.9.4",
|
||||
"@react-navigation/native": "^6.0.2",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-prettier": "^5.2.1",
|
||||
"expo": "~51.0.28",
|
||||
"expo-auth-session": "~5.5.2",
|
||||
"expo-constants": "~16.0.2",
|
||||
"expo-crypto": "^57.0.1",
|
||||
"expo-font": "~12.0.9",
|
||||
"expo-linking": "^6.3.1",
|
||||
"expo-location": "^17.0.1",
|
||||
@@ -93,6 +90,7 @@
|
||||
"expo-system-ui": "~3.0.7",
|
||||
"expo-web-browser": "~13.0.3",
|
||||
"nativewind": "^2.0.11",
|
||||
"pg": "^8.23.0",
|
||||
"prettier": "^3.3.3",
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
@@ -111,6 +109,7 @@
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.20.0",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/pg": "^8.23.1",
|
||||
"@types/react": "~18.2.45",
|
||||
"@types/react-test-renderer": "^18.0.7",
|
||||
"eslint": "^8.57.0",
|
||||
|
||||
+69
-8
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"exclude": ["dashboard"],
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
|
||||
Reference in New Issue
Block a user