small directus lib patch for auth
This commit is contained in:
parent
5d2c668bad
commit
01c0d37d03
1 changed files with 154 additions and 54 deletions
208
lib/directus.ts
208
lib/directus.ts
|
|
@ -1,17 +1,18 @@
|
||||||
// lib/directus.ts
|
// lib/directus.ts
|
||||||
// Central Directus helpers used by API routes. Minimal hard-coding, robust parsing.
|
// Central Directus helpers used by API routes.
|
||||||
|
|
||||||
const BASE = process.env.DIRECTUS_URL!;
|
const BASE = process.env.DIRECTUS_URL!;
|
||||||
const TOKEN_SUBMIT =
|
const TOKEN_SUBMIT = process.env.DIRECTUS_TOKEN_SUBMIT!;
|
||||||
process.env.DIRECTUS_TOKEN_SUBMIT ??
|
const TOKEN_ADMIN_REGISTER = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || "";
|
||||||
process.env.DIRECTUS_STATIC_TOKEN ??
|
const ROLE_MEMBER_ID_ENV = process.env.DIRECTUS_ROLE_MEMBER_ID || "";
|
||||||
process.env.DIRECTUS_TOKEN ??
|
const ROLE_MEMBER_NAME_ENV = process.env.DIRECTUS_ROLE_MEMBER_NAME || "Users";
|
||||||
"";
|
|
||||||
const PROJECTS_COLLECTION =
|
const PROJECTS_COLLECTION =
|
||||||
process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
|
process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
|
||||||
|
|
||||||
if (!BASE) console.warn("[directus] Missing DIRECTUS_URL");
|
if (!BASE) console.warn("[directus] Missing DIRECTUS_URL");
|
||||||
if (!TOKEN_SUBMIT) console.warn("[directus] Missing submit token (DIRECTUS_TOKEN_SUBMIT / DIRECTUS_STATIC_TOKEN / DIRECTUS_TOKEN)");
|
if (!TOKEN_SUBMIT) console.warn("[directus] Missing DIRECTUS_TOKEN_SUBMIT");
|
||||||
|
if (!TOKEN_ADMIN_REGISTER) console.warn("[directus] Missing DIRECTUS_TOKEN_ADMIN_REGISTER (used for registration)");
|
||||||
|
|
||||||
export function bytesFromMB(mb: number) {
|
export function bytesFromMB(mb: number) {
|
||||||
return Math.round(mb * 1024 * 1024);
|
return Math.round(mb * 1024 * 1024);
|
||||||
|
|
@ -30,11 +31,7 @@ async function parseJsonSafe(res: Response) {
|
||||||
return { json, text };
|
return { json, text };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** directusFetch with the SUBMIT token (used by options + settings submit) */
|
||||||
* directusFetch:
|
|
||||||
* - Adds Authorization + Accept headers
|
|
||||||
* - Parses JSON safely and throws with readable error text on !ok
|
|
||||||
*/
|
|
||||||
export async function directusFetch<T = any>(
|
export async function directusFetch<T = any>(
|
||||||
path: string,
|
path: string,
|
||||||
init?: RequestInit
|
init?: RequestInit
|
||||||
|
|
@ -46,7 +43,30 @@ export async function directusFetch<T = any>(
|
||||||
Authorization: `Bearer ${TOKEN_SUBMIT}`,
|
Authorization: `Bearer ${TOKEN_SUBMIT}`,
|
||||||
...(init?.headers || {}),
|
...(init?.headers || {}),
|
||||||
},
|
},
|
||||||
cache: "no-store",
|
});
|
||||||
|
|
||||||
|
const { json, text } = await parseJsonSafe(res);
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Directus error ${res.status}: ${text || res.statusText}`);
|
||||||
|
}
|
||||||
|
return (json ?? {}) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same as above, but uses the ADMIN REGISTER token */
|
||||||
|
export async function directusAdminFetch<T = any>(
|
||||||
|
path: string,
|
||||||
|
init?: RequestInit
|
||||||
|
): Promise<T> {
|
||||||
|
if (!TOKEN_ADMIN_REGISTER) {
|
||||||
|
throw new Error("Missing DIRECTUS_TOKEN_ADMIN_REGISTER");
|
||||||
|
}
|
||||||
|
const res = await fetch(`${BASE}${path}`, {
|
||||||
|
...init,
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
Authorization: `Bearer ${TOKEN_ADMIN_REGISTER}`,
|
||||||
|
...(init?.headers || {}),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { json, text } = await parseJsonSafe(res);
|
const { json, text } = await parseJsonSafe(res);
|
||||||
|
|
@ -57,9 +77,10 @@ export async function directusFetch<T = any>(
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ─────────────────────────────────────────────────────────────
|
/* ─────────────────────────────────────────────────────────────
|
||||||
* Folder lookup (by "path" = "<parent>/<child>") with caching.
|
* On-the-fly folder lookup by "path" = "<parent>/<child>"
|
||||||
* Requires READ on directus_folders to fully resolve, but gracefully
|
* Caches results in-memory. If lookup is forbidden (403) or not found,
|
||||||
* degrades (returns undefined) if forbidden/not found.
|
* we return undefined and uploads proceed without a folder.
|
||||||
|
* Requires READ on directus_folders (id,name,parent.name) to fully work.
|
||||||
* ──────────────────────────────────────────────────────────── */
|
* ──────────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
type FolderItem = {
|
type FolderItem = {
|
||||||
|
|
@ -75,7 +96,7 @@ let folderListCacheAt = 0;
|
||||||
async function fetchAllFolders(): Promise<FolderItem[] | null> {
|
async function fetchAllFolders(): Promise<FolderItem[] | null> {
|
||||||
try {
|
try {
|
||||||
const q = `/folders?fields=id,name,parent.id,parent.name&limit=500`;
|
const q = `/folders?fields=id,name,parent.id,parent.name&limit=500`;
|
||||||
const res = await directusFetch<{ data: FolderItem[] }>(q);
|
const res = await directusAdminFetch<{ data: FolderItem[] }>(q);
|
||||||
return res?.data ?? [];
|
return res?.data ?? [];
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.warn("[directus] fetchAllFolders failed:", e?.message || e);
|
console.warn("[directus] fetchAllFolders failed:", e?.message || e);
|
||||||
|
|
@ -121,8 +142,10 @@ async function getFolderIdByPath(path: string): Promise<string | undefined> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* uploadFile:
|
* uploadFile:
|
||||||
* Uploads a file and (optionally) sets the folder **at create time**
|
* Robustly uploads a file (Blob/File). Accepts optional folder routing:
|
||||||
* so we don't need UPDATE permission on directus_files.
|
* - options.folderId: direct UUID if you have it
|
||||||
|
* - options.folderNamePath: "<parent>/<child>" lookup via /folders
|
||||||
|
* Also sets filename_download & optional title.
|
||||||
*/
|
*/
|
||||||
export async function uploadFile(
|
export async function uploadFile(
|
||||||
file: Blob | File,
|
file: Blob | File,
|
||||||
|
|
@ -136,7 +159,11 @@ export async function uploadFile(
|
||||||
|
|
||||||
let folderId = options?.folderId;
|
let folderId = options?.folderId;
|
||||||
if (!folderId && options?.folderNamePath) {
|
if (!folderId && options?.folderNamePath) {
|
||||||
folderId = await getFolderIdByPath(options.folderNamePath);
|
try {
|
||||||
|
folderId = await getFolderIdByPath(options.folderNamePath);
|
||||||
|
} catch {
|
||||||
|
// ignore; proceed without a folder
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (folderId) form.set("folder", folderId);
|
if (folderId) form.set("folder", folderId);
|
||||||
|
|
||||||
|
|
@ -152,11 +179,14 @@ export async function uploadFile(
|
||||||
const { json, text } = await parseJsonSafe(res);
|
const { json, text } = await parseJsonSafe(res);
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`File upload failed: status=${res.status} ${res.statusText} body=${(text || "").slice(0, 400) || "<empty>"}`
|
`File upload failed: status=${res.status} ${res.statusText} body=${(text || "").slice(
|
||||||
|
0,
|
||||||
|
400
|
||||||
|
) || "<empty>"}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const id = json?.data?.submission_id ?? json?.data?.id ?? json?.submission_id ?? json?.id;
|
const id = json?.data?.id ?? json?.id;
|
||||||
if (!id) throw new Error("File upload succeeded but no id returned");
|
if (!id) throw new Error("File upload succeeded but no id returned");
|
||||||
return { id: String(id) };
|
return { id: String(id) };
|
||||||
}
|
}
|
||||||
|
|
@ -165,51 +195,121 @@ export async function uploadFile(
|
||||||
export async function createSettingsItem(
|
export async function createSettingsItem(
|
||||||
collection: string,
|
collection: string,
|
||||||
payload: any
|
payload: any
|
||||||
): Promise<{ data: any }> {
|
): Promise<{ data: { id: string } }> {
|
||||||
return directusFetch<{ data: any }>(`/items/${collection}`, {
|
return directusFetch<{ data: { id: string } }>(`/items/${collection}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Project helpers (used by app/api/submit/project/route.ts) */
|
/** ─────────────────────────────────────────────────────────────
|
||||||
|
* Project helpers (used by app/api/submit/project/route.ts)
|
||||||
|
* Collection can be overridden via DIRECTUS_PROJECTS_COLLECTION
|
||||||
|
* ──────────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
export async function createProjectRow(
|
export async function createProjectRow(
|
||||||
payload: any
|
payload: any
|
||||||
): Promise<{ data: any }> {
|
): Promise<{ data: { id: string } }> {
|
||||||
return directusFetch<{ data: any }>(`/items/${PROJECTS_COLLECTION}`, {
|
return directusFetch<{ data: { id: string } }>(
|
||||||
method: "POST",
|
`/items/${PROJECTS_COLLECTION}`,
|
||||||
headers: { "Content-Type": "application/json" },
|
{
|
||||||
body: JSON.stringify(payload),
|
method: "POST",
|
||||||
});
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function patchProject(
|
export async function patchProject(
|
||||||
id: string | number,
|
id: string | number,
|
||||||
payload: any
|
payload: any
|
||||||
): Promise<{ data: any }> {
|
): Promise<{ data: { id: string } }> {
|
||||||
return directusFetch<{ data: any }>(`/items/${PROJECTS_COLLECTION}/${id}`, {
|
return directusFetch<{ data: { id: string } }>(
|
||||||
method: "PATCH",
|
`/items/${PROJECTS_COLLECTION}/${id}`,
|
||||||
headers: { "Content-Type": "application/json" },
|
{
|
||||||
body: JSON.stringify(payload),
|
method: "PATCH",
|
||||||
});
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// One-time diagnostic: log which role this token maps to (safe in prod)
|
/* ─────────────────────────────────────────────────────────────
|
||||||
(async () => {
|
* Auth helpers (registration / login support)
|
||||||
if (!BASE || !TOKEN_SUBMIT) return;
|
* ──────────────────────────────────────────────────────────── */
|
||||||
try {
|
|
||||||
const r = await fetch(`${BASE}/users/me?fields=role.name`, {
|
export async function resolveMemberRoleId(): Promise<string> {
|
||||||
headers: { Authorization: `Bearer ${TOKEN_SUBMIT}` },
|
if (ROLE_MEMBER_ID_ENV) return ROLE_MEMBER_ID_ENV;
|
||||||
cache: "no-store",
|
|
||||||
});
|
// Fallback by role name (e.g., "Users")
|
||||||
if (r.ok) {
|
const name = ROLE_MEMBER_NAME_ENV;
|
||||||
const j = await r.json().catch(() => ({}));
|
const q = `/roles?filter[name][_eq]=${encodeURIComponent(
|
||||||
console.log(`[directus] using role: ${j?.data?.role?.name ?? "unknown"}`);
|
name
|
||||||
} else {
|
)}&fields=id,name&limit=1`;
|
||||||
console.warn(`[directus] whoami failed with ${r.status}`);
|
const { data } = await directusAdminFetch<{ data: Array<{ id: string }> }>(q);
|
||||||
}
|
const hit = data?.[0]?.id;
|
||||||
} catch (e: any) {
|
if (!hit) throw new Error(`Role not found: ${name}`);
|
||||||
console.warn(`[directus] whoami error: ${e?.message ?? e}`);
|
return hit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create a Directus user (username required, email optional). */
|
||||||
|
export async function createDirectusUser(input: {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
email?: string;
|
||||||
|
roleId?: string;
|
||||||
|
}): Promise<{ id: string }> {
|
||||||
|
const role = input.roleId || (await resolveMemberRoleId());
|
||||||
|
|
||||||
|
// If email is omitted, create a stable placeholder so login can still work.
|
||||||
|
const email =
|
||||||
|
input.email && input.email.trim()
|
||||||
|
? input.email.trim()
|
||||||
|
: `${input.username}@noemail.local`;
|
||||||
|
|
||||||
|
const res = await directusAdminFetch<{ data: { id: string } }>(`/users`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
status: "active",
|
||||||
|
role,
|
||||||
|
username: input.username,
|
||||||
|
email,
|
||||||
|
password: input.password,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return { id: String(res?.data?.id) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Find user's email by username (returns null if not found) */
|
||||||
|
export async function emailForUsername(username: string): Promise<string | null> {
|
||||||
|
const q = `/users?filter[username][_eq]=${encodeURIComponent(
|
||||||
|
username
|
||||||
|
)}&fields=email&limit=1`;
|
||||||
|
const { data } = await directusAdminFetch<{ data: Array<{ email?: string }> }>(
|
||||||
|
q
|
||||||
|
);
|
||||||
|
const em = data?.[0]?.email;
|
||||||
|
return em ? String(em) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Proxy Directus /auth/login and return tokens (email required here). */
|
||||||
|
export async function loginDirectus(email: string, password: string) {
|
||||||
|
const res = await fetch(`${BASE}/auth/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { json, text } = await parseJsonSafe(res);
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Directus error ${res.status}: ${text || res.statusText}`);
|
||||||
}
|
}
|
||||||
})();
|
// Directus typically returns { data: { access_token, refresh_token, expires } }
|
||||||
|
return json?.data ?? json;
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue