Files
website/lib/auth-user.ts
T

89 lines
2.3 KiB
TypeScript

import {
clearTokens,
getAccessToken,
} from "@/lib/session";
export type WebsiteAuthUser = {
id: string;
cellNumber: string;
email: string | null;
firstName: string | null;
lastName: string | null;
firstNameEn: string | null;
lastNameEn: string | null;
roles: string[];
dashboard: "super_admin" | "business" | "customer";
businesses: {
id: string;
name: string;
slug: string;
isOwner: boolean;
}[];
};
const MESHKEE_API_URL =
process.env.NEXT_PUBLIC_MESHKEE_API_URL?.replace(/\/$/, "") ||
"https://api.meshkee.com/api/v1";
export function getCustomerDashboardUrl() {
return (
process.env.NEXT_PUBLIC_CUSTOMER_DASHBOARD_URL?.replace(/\/$/, "") ||
"http://customer.localhost:3002"
);
}
export function getAdminDashboardUrl() {
return (
process.env.NEXT_PUBLIC_ADMIN_DASHBOARD_URL?.replace(/\/$/, "") ||
process.env.NEXT_PUBLIC_DASHBOARD_URL?.replace(/\/$/, "") ||
"http://localhost:3002"
);
}
export function getBusinessDashboardUrl() {
return (
process.env.NEXT_PUBLIC_BUSINESS_DASHBOARD_URL?.replace(/\/$/, "") ||
"http://business.localhost:3002"
);
}
export function displayNameFor(user: WebsiteAuthUser | null | undefined) {
if (!user) return "";
const first = (user.firstNameEn || user.firstName || "").trim();
const last = (user.lastNameEn || user.lastName || "").trim();
const full = [first, last].filter(Boolean).join(" ");
if (full) return full;
return user.cellNumber || "Account";
}
/** Header label: first name only. */
export function firstNameFor(user: WebsiteAuthUser | null | undefined) {
if (!user) return "";
const first = (user.firstNameEn || user.firstName || "").trim();
if (first) return first.split(/\s+/)[0] || first;
return user.cellNumber || "Account";
}
export async function fetchCurrentUser(
signal?: AbortSignal,
): Promise<WebsiteAuthUser | null> {
const token = getAccessToken();
if (!token) return null;
const response = await fetch(`${MESHKEE_API_URL}/auth/me`, {
headers: { Authorization: `Bearer ${token}` },
signal,
cache: "no-store",
});
if (response.status === 401 || response.status === 403) {
clearTokens();
return null;
}
if (!response.ok) return null;
const payload = (await response.json()) as { user?: WebsiteAuthUser };
return payload.user ?? null;
}