Add self-hosted auth, admin API, and owner web dashboard
- Replace Clerk with self-hosted JWT auth (register/login/verify, bcrypt passwords, Gmail OTP with console fallback) - Add lib/db.ts pg pool + transaction helpers; seed script migrates legacy Clerk-era schema (drop clerk_id, enforce UUID ids and unique email) - Add owner-gated admin API: stats, users, drivers CRUD, rides - Add dashboard/ Vite React owner dashboard (login, overview, users, fleet, rides) with dev-server proxy to avoid Expo CORS middleware - Add scripts/set-owner.mjs for role management
This commit is contained in:
@@ -0,0 +1,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) {
|
||||
|
||||
+21
-19
@@ -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,
|
||||
password: form.password,
|
||||
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 });
|
||||
router.replace("/");
|
||||
} else {
|
||||
Alert.alert("Error", "Invalid email or password.");
|
||||
setForm((prevForm) => ({
|
||||
...prevForm,
|
||||
password: "",
|
||||
}));
|
||||
}
|
||||
await setSession(response.data);
|
||||
router.replace("/");
|
||||
} 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">
|
||||
|
||||
+54
-38
@@ -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,
|
||||
password: form.password,
|
||||
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,
|
||||
const response = await fetchAPI("/(api)/auth/verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: form.email, code: verification.code }),
|
||||
});
|
||||
|
||||
if (completeSignUp.status === "complete") {
|
||||
await fetchAPI("/(api)/user", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: form.name,
|
||||
email: form.email,
|
||||
clerkId: completeSignUp.createdUserId,
|
||||
}),
|
||||
});
|
||||
|
||||
await setActive({ session: completeSignUp.createdSessionId });
|
||||
setVerification((prevVerification) => ({
|
||||
...prevVerification,
|
||||
state: "success",
|
||||
}));
|
||||
} else {
|
||||
setVerification((prevVerification) => ({
|
||||
...prevVerification,
|
||||
error: "Verification failed.",
|
||||
state: "failed",
|
||||
}));
|
||||
}
|
||||
await setSession(response.data);
|
||||
setVerification((prevVerification) => ({
|
||||
...prevVerification,
|
||||
state: "success",
|
||||
}));
|
||||
} 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>
|
||||
|
||||
<Text className="text-lg font-JakartaRegular text-[#0CC25F]">
|
||||
${driverDetails?.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",
|
||||
);
|
||||
|
||||
+9
-16
@@ -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,22 +34,16 @@ 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>
|
||||
<Stack>
|
||||
<Stack.Screen name="index" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="(root)" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="(auth)" options={{ headerShown: false }} />
|
||||
</Stack>
|
||||
<SessionProvider>
|
||||
<Stack>
|
||||
<Stack.Screen name="index" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="(root)" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="(auth)" options={{ headerShown: false }} />
|
||||
</Stack>
|
||||
|
||||
<StatusBar style="dark" />
|
||||
</ClerkLoaded>
|
||||
</ClerkProvider>
|
||||
<StatusBar style="dark" />
|
||||
</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" />;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user