Compare commits
4 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2f712dba23 | |||
| 1abeab6e46 | |||
| fe9eb915e1 | |||
| 86cdffdd1c |
16 changed files with 2918 additions and 223 deletions
2180
docs/Ai-converstion.md
Normal file
2180
docs/Ai-converstion.md
Normal file
File diff suppressed because it is too large
Load diff
BIN
docs/Ai-converstion.pdf
Normal file
BIN
docs/Ai-converstion.pdf
Normal file
Binary file not shown.
|
|
@ -356,3 +356,17 @@ Now we will go now and add metadata
|
||||||
Now we have the metadata along with some great filters on the data board page
|
Now we have the metadata along with some great filters on the data board page
|
||||||
|
|
||||||
Now we are going to implement an an update of a file or folder stored. 12/1/2026
|
Now we are going to implement an an update of a file or folder stored. 12/1/2026
|
||||||
|
|
||||||
|
For download there 2 function we need to implement
|
||||||
|
|
||||||
|
1) down load the file to ~/user/Downloads, this should work for any file type including pdf
|
||||||
|
|
||||||
|
2) if the file is a pdf open the file in another tab in the browser as most browser support reading a pdf
|
||||||
|
|
||||||
|
For download there 2 function we need to implement
|
||||||
|
|
||||||
|
1) down load the file to ~/user/Downloads, this should work for any file type including pdf
|
||||||
|
|
||||||
|
2) if the file is a pdf open the file in another tab in the browser as most browser support reading a pdf
|
||||||
|
|
||||||
|
So we need to implement 2 new actions, downLoad file and open pdf to read. Does this make sense ?
|
||||||
BIN
docs/notes.pdf
BIN
docs/notes.pdf
Binary file not shown.
66
src/app/api/download/route.ts
Normal file
66
src/app/api/download/route.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
// src/app/api/download/route.ts
|
||||||
|
"use server"
|
||||||
|
|
||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { auth } from "@/auth"; // Import the auth function from your central config
|
||||||
|
import { prisma } from '@/lib/prisma';
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
// 1. Check Authentication using the V5 auth() helper
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
// In V5, tokens are usually handled in the session callback
|
||||||
|
if (!session || !session.accessToken) {
|
||||||
|
return new NextResponse("Unauthorized - No Access Token found", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Get parameters from URL
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const fileNodeId = searchParams.get('id');
|
||||||
|
const mode = searchParams.get('mode') === 'inline' ? 'inline' : 'attachment';
|
||||||
|
|
||||||
|
if (!fileNodeId) {
|
||||||
|
return new NextResponse("File ID is required", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Find the file in your Postgres FileNode table
|
||||||
|
const fileNode = await prisma.fileNode.findUnique({
|
||||||
|
where: { id: fileNodeId }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!fileNode || !fileNode.oneDriveId) {
|
||||||
|
return new NextResponse("File not found in database", { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Fetch the file stream from Microsoft Graph
|
||||||
|
const graphResponse = await fetch(
|
||||||
|
`https://graph.microsoft.com/v1.0/me/drive/items/${fileNode.oneDriveId}/content`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${session.accessToken}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!graphResponse.ok) {
|
||||||
|
const errorText = await graphResponse.text();
|
||||||
|
console.error('MS Graph Error:', errorText);
|
||||||
|
return new NextResponse(`OneDrive Error: ${graphResponse.statusText}`, { status: graphResponse.status });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Stream the response directly to the client
|
||||||
|
return new NextResponse(graphResponse.body, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': fileNode.mimeType || 'application/octet-stream',
|
||||||
|
// Note: Using encodeURIComponent for filename to handle special characters
|
||||||
|
'Content-Disposition': `${mode}; filename="${encodeURIComponent(fileNode.name)}"`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Download error:', error);
|
||||||
|
return new NextResponse("Internal Server Error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,7 +6,7 @@ import { revalidatePath } from "next/cache";
|
||||||
import { getFreshAccessToken } from "@/lib/auth-utils";
|
import { getFreshAccessToken } from "@/lib/auth-utils";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 1. FETCH: Get all file nodes
|
* 1. FETCH: Get all file nodes for the Dashboard
|
||||||
*/
|
*/
|
||||||
export async function getFileNodes() {
|
export async function getFileNodes() {
|
||||||
try {
|
try {
|
||||||
|
|
@ -23,83 +23,94 @@ export async function getFileNodes() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 2. DELETE: Remove from OneDrive and Database
|
* 2. DOWNLOAD: Generates the authenticated OneDrive URL
|
||||||
* Improved to ensure DB removal even if OneDrive API returns errors.
|
*/
|
||||||
|
export async function getDownloadUrlAction(id: string) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
|
const file = await prisma.fileNode.findUnique({ where: { id } });
|
||||||
|
if (!file || !file.oneDriveId) throw new Error("File not found or missing cloud ID");
|
||||||
|
|
||||||
|
const accessToken = await getFreshAccessToken(session.user.id);
|
||||||
|
const res = await fetch(
|
||||||
|
`https://graph.microsoft.com/v1.0/me/drive/items/${file.oneDriveId}`,
|
||||||
|
{ headers: { Authorization: `Bearer ${accessToken}` } }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!res.ok) throw new Error("Failed to contact OneDrive");
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
const downloadUrl = data["@microsoft.graph.downloadUrl"];
|
||||||
|
|
||||||
|
if (!downloadUrl) throw new Error("OneDrive did not provide a download link");
|
||||||
|
|
||||||
|
return { downloadUrl };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 3. DELETE: Remove from OneDrive (via ID) and Database
|
||||||
|
* Folders are virtual (DB only), so cloud deletion is skipped if oneDriveId is null.
|
||||||
*/
|
*/
|
||||||
export async function deleteFileAction(fileId: string) {
|
export async function deleteFileAction(fileId: string) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user?.id) throw new Error("Unauthorized");
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
// 1. Find the node to check permissions
|
|
||||||
const node = await prisma.fileNode.findUnique({
|
const node = await prisma.fileNode.findUnique({
|
||||||
where: { id: fileId },
|
where: { id: fileId },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!node) {
|
if (!node) {
|
||||||
// If not in DB, trigger a refresh anyway to clear the UI
|
|
||||||
revalidatePath("/dashboard");
|
revalidatePath("/dashboard");
|
||||||
return { success: true, message: "Item already removed from database" };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
// @ts-ignore - role added via auth callbacks
|
// @ts-ignore
|
||||||
const isAdmin = session.user.role === "ADMIN";
|
const isAdmin = session.user.role === "ADMIN";
|
||||||
const isOwner = node.ownerId === session.user.id;
|
const isOwner = node.ownerId === session.user.id;
|
||||||
|
|
||||||
if (!isAdmin && !isOwner) {
|
if (!isAdmin && !isOwner) {
|
||||||
throw new Error("Permission Denied: You do not have authority to delete this item.");
|
throw new Error("Permission Denied.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.isFolder && !isAdmin) {
|
|
||||||
throw new Error("Security Restriction: Only Administrators can delete folders.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. OneDrive Deletion Attempt
|
|
||||||
try {
|
try {
|
||||||
const accessToken = await getFreshAccessToken(session.user.id);
|
const accessToken = await getFreshAccessToken(session.user.id);
|
||||||
|
|
||||||
if (accessToken) {
|
// Only attempt cloud deletion if it's a file/storage with a oneDriveId.
|
||||||
const rootFolder = "WebCalibre";
|
// Virtual folders created in the DB have no oneDriveId and are skipped.
|
||||||
// We target the folder on OneDrive by the ID stored in our DB
|
if (accessToken && node.oneDriveId) {
|
||||||
const onedrivePath = `https://graph.microsoft.com/v1.0/me/drive/root:/${rootFolder}/${node.id}`;
|
const onedriveRes = await fetch(
|
||||||
|
`https://graph.microsoft.com/v1.0/me/drive/items/${node.oneDriveId}`,
|
||||||
const onedriveRes = await fetch(onedrivePath, {
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: { Authorization: `Bearer ${accessToken}` },
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
if (!onedriveRes.ok && onedriveRes.status !== 404) {
|
if (!onedriveRes.ok && onedriveRes.status !== 404) {
|
||||||
const errData = await onedriveRes.json().catch(() => ({}));
|
console.warn("OneDrive Deletion Warning: Cloud record might still exist.");
|
||||||
console.warn("OneDrive Deletion Warning (Cloud record might still exist):", errData);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (cloudError) {
|
} catch (cloudError) {
|
||||||
// We catch cloud errors but DO NOT throw them, so we can proceed to delete the DB record
|
console.error("Cloud cleanup failed:", cloudError);
|
||||||
console.error("Cloud communication failed, proceeding with DB cleanup:", cloudError);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Database Deletion (The Source of Truth for your UI)
|
|
||||||
try {
|
try {
|
||||||
await prisma.fileNode.delete({
|
await prisma.fileNode.delete({ where: { id: fileId } });
|
||||||
where: { id: fileId }
|
|
||||||
});
|
|
||||||
|
|
||||||
revalidatePath("/dashboard");
|
revalidatePath("/dashboard");
|
||||||
revalidatePath("/upload");
|
revalidatePath("/upload");
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (dbError: any) {
|
} catch (dbError) {
|
||||||
console.error("Database deletion failed:", dbError);
|
|
||||||
throw new Error("Failed to remove the record from the database.");
|
throw new Error("Failed to remove the record from the database.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 3. MOVE: Assign file to folder or folder to another folder
|
* 4. MOVE: Assign file to folder or folder to another folder (Virtual Move)
|
||||||
*/
|
*/
|
||||||
export async function moveNodeAction(nodeId: string, newParentId: string | null) {
|
export async function moveNodeAction(nodeId: string, newParentId: string | null) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user?.id) throw new Error("Unauthorized");
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
if (nodeId === newParentId) throw new Error("Cannot move to self.");
|
if (nodeId === newParentId) throw new Error("Cannot move to self.");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
@ -107,10 +118,69 @@ export async function moveNodeAction(nodeId: string, newParentId: string | null)
|
||||||
where: { id: nodeId },
|
where: { id: nodeId },
|
||||||
data: { parentId: newParentId }
|
data: { parentId: newParentId }
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath("/dashboard");
|
revalidatePath("/dashboard");
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error("Move failed.");
|
throw new Error("Move failed.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 5. UPDATE & REPLACE: Full update of metadata and OneDrive content
|
||||||
|
*/
|
||||||
|
export async function updateFileFullAction(formData: FormData) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
|
const id = formData.get("id") as string;
|
||||||
|
const name = formData.get("name") as string;
|
||||||
|
const description = formData.get("description") as string;
|
||||||
|
const parentIdRaw = formData.get("parentId") as string;
|
||||||
|
const metadataStr = formData.get("metadata") as string;
|
||||||
|
const newFile = formData.get("file") as File | null;
|
||||||
|
|
||||||
|
const parentId = parentIdRaw === "root" ? null : parentIdRaw;
|
||||||
|
let metadata = JSON.parse(metadataStr);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const accessToken = await getFreshAccessToken(session.user.id);
|
||||||
|
const node = await prisma.fileNode.findUnique({ where: { id } });
|
||||||
|
|
||||||
|
// Update physical file content only if a new file is uploaded and we have a target oneDriveId
|
||||||
|
if (newFile && newFile.size > 0 && node?.oneDriveId) {
|
||||||
|
const onedrivePath = `https://graph.microsoft.com/v1.0/me/drive/items/${node.oneDriveId}/content`;
|
||||||
|
|
||||||
|
const uploadRes = await fetch(onedrivePath, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
"Content-Type": newFile.type
|
||||||
|
},
|
||||||
|
body: Buffer.from(await newFile.arrayBuffer()),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!uploadRes.ok) throw new Error("OneDrive content update failed");
|
||||||
|
|
||||||
|
metadata.type = newFile.name.split('.').pop()?.toUpperCase() || 'UNKNOWN';
|
||||||
|
metadata.mimeType = newFile.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.fileNode.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
parentId,
|
||||||
|
metadata,
|
||||||
|
size: newFile ? BigInt(newFile.size) : undefined,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
return { success: true };
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Full Update Failure:", error);
|
||||||
|
throw new Error(error.message || "Failed to update record.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,8 +1,19 @@
|
||||||
"use client";
|
'use client';
|
||||||
|
|
||||||
|
// src/app/dashboard/dashboard-view.tsx
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import {
|
import {
|
||||||
Button, CircularProgress, Box, Chip, IconButton, Tooltip, Typography, Stack, TextField, InputAdornment
|
Button,
|
||||||
|
CircularProgress,
|
||||||
|
Box,
|
||||||
|
Chip,
|
||||||
|
IconButton,
|
||||||
|
Typography,
|
||||||
|
Stack,
|
||||||
|
TextField,
|
||||||
|
InputAdornment,
|
||||||
|
Tooltip
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import {
|
import {
|
||||||
DataGrid,
|
DataGrid,
|
||||||
|
|
@ -17,9 +28,12 @@ import RefreshIcon from "@mui/icons-material/Refresh";
|
||||||
import FolderIcon from "@mui/icons-material/Folder";
|
import FolderIcon from "@mui/icons-material/Folder";
|
||||||
import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
|
import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
|
||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
|
import EditIcon from "@mui/icons-material/Edit";
|
||||||
import SearchIcon from '@mui/icons-material/Search';
|
import SearchIcon from '@mui/icons-material/Search';
|
||||||
import CancelIcon from '@mui/icons-material/Cancel';
|
import CancelIcon from '@mui/icons-material/Cancel';
|
||||||
|
import DownloadIcon from '@mui/icons-material/Download';
|
||||||
|
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
|
||||||
|
|
||||||
import { syncOneDrive } from "./sync-actions";
|
import { syncOneDrive } from "./sync-actions";
|
||||||
import { deleteFileAction } from "./actions";
|
import { deleteFileAction } from "./actions";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
|
@ -30,7 +44,6 @@ function CustomToolbar() {
|
||||||
<Typography variant="h6" fontWeight="bold" color="primary">
|
<Typography variant="h6" fontWeight="bold" color="primary">
|
||||||
Library
|
Library
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
<QuickFilter sx={{ display: 'flex', alignItems: 'center' }}>
|
<QuickFilter sx={{ display: 'flex', alignItems: 'center' }}>
|
||||||
<QuickFilterControl
|
<QuickFilterControl
|
||||||
render={({ ref, ...controlProps }, state) => (
|
render={({ ref, ...controlProps }, state) => (
|
||||||
|
|
@ -115,6 +128,17 @@ export default function DashboardView({ initialFiles, user }: DashboardViewProps
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- NEW DOWNLOAD FUNCTIONS ---
|
||||||
|
const handleDownload = (id: string) => {
|
||||||
|
// Triggers local folder download via Content-Disposition: attachment
|
||||||
|
window.location.href = `/api/download?id=${id}&mode=attachment`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleViewInTab = (id: string) => {
|
||||||
|
// Opens in a new tab via Content-Disposition: inline
|
||||||
|
window.open(`/api/download?id=${id}&mode=inline`, '_blank');
|
||||||
|
};
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
{
|
{
|
||||||
field: "name",
|
field: "name",
|
||||||
|
|
@ -139,10 +163,7 @@ export default function DashboardView({ initialFiles, user }: DashboardViewProps
|
||||||
field: "type",
|
field: "type",
|
||||||
headerName: "Type",
|
headerName: "Type",
|
||||||
width: 120,
|
width: 120,
|
||||||
// Fixed: Pulling type from metadata since it's not a top-level property
|
valueGetter: (value, row) => row.metadata?.type || (row.isFolder ? "Folder" : "File"),
|
||||||
valueGetter: (value, row) => {
|
|
||||||
return row.metadata?.type || (row.isFolder ? "Folder" : "File");
|
|
||||||
},
|
|
||||||
renderCell: (params) => (
|
renderCell: (params) => (
|
||||||
<Typography variant="caption" sx={{ textTransform: 'uppercase', fontWeight: 'bold', color: 'text.secondary' }}>
|
<Typography variant="caption" sx={{ textTransform: 'uppercase', fontWeight: 'bold', color: 'text.secondary' }}>
|
||||||
{params.value}
|
{params.value}
|
||||||
|
|
@ -152,21 +173,60 @@ export default function DashboardView({ initialFiles, user }: DashboardViewProps
|
||||||
{
|
{
|
||||||
field: "size",
|
field: "size",
|
||||||
headerName: "Size",
|
headerName: "Size",
|
||||||
width: 120,
|
width: 100,
|
||||||
renderCell: (params) => params.row.isFolder ? "--" : `${(Number(params.value) / 1024 / 1024).toFixed(2)} MB`
|
renderCell: (params) => params.row.isFolder ? "--" : `${(Number(params.value) / 1024 / 1024).toFixed(2)} MB`
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "actions",
|
field: "actions",
|
||||||
headerName: "Actions",
|
headerName: "Actions",
|
||||||
width: 100,
|
width: 180, // Increased width to accommodate new buttons
|
||||||
align: 'right',
|
align: 'right',
|
||||||
renderCell: (params) => (
|
renderCell: (params) => {
|
||||||
(isAdmin || params.row.ownerId === user?.id) && (
|
const isOwner = params.row.ownerId === user?.id;
|
||||||
<IconButton size="small" color="error" onClick={() => handleDelete(params.row.id, params.row.name)}>
|
const isFolder = params.row.isFolder;
|
||||||
<DeleteIcon fontSize="small" />
|
|
||||||
</IconButton>
|
return (
|
||||||
)
|
<Stack direction="row" spacing={0.5} justifyContent="flex-end">
|
||||||
)
|
{!isFolder && (
|
||||||
|
<>
|
||||||
|
<Tooltip title="View in Tab">
|
||||||
|
<IconButton size="small" color="info" onClick={() => handleViewInTab(params.row.id)}>
|
||||||
|
<OpenInNewIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="Download to Folder">
|
||||||
|
<IconButton size="small" color="success" onClick={() => handleDownload(params.row.id)}>
|
||||||
|
<DownloadIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{(isAdmin || isOwner) && (
|
||||||
|
<>
|
||||||
|
<Tooltip title="Edit Details">
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="primary"
|
||||||
|
onClick={() => router.push(`/update/${params.row.id}`)}
|
||||||
|
>
|
||||||
|
<EditIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="Delete">
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="error"
|
||||||
|
onClick={() => handleDelete(params.row.id, params.row.name)}
|
||||||
|
>
|
||||||
|
<DeleteIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "metadata_search",
|
field: "metadata_search",
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
|
@ -7,64 +6,37 @@ import { getFreshAccessToken } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function syncOneDrive() {
|
export async function syncOneDrive() {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
|
|
||||||
if (!session?.user?.id) throw new Error("Unauthorized");
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const accessToken = await getFreshAccessToken(session.user.id);
|
const accessToken = await getFreshAccessToken(session.user.id);
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
throw new Error("Microsoft account not linked properly or session expired.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch("https://graph.microsoft.com/v1.0/me/drive/root:/WebCalibre:/children", {
|
const response = await fetch("https://graph.microsoft.com/v1.0/me/drive/root:/WebCalibre:/children", {
|
||||||
headers: {
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) return { success: true, count: 0 };
|
||||||
const errorData = await response.json();
|
|
||||||
if (response.status === 404) {
|
|
||||||
return { success: true, count: 0 };
|
|
||||||
}
|
|
||||||
throw new Error(errorData.error?.message || "Failed to fetch data from OneDrive");
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
let syncedCount = 0;
|
let syncedCount = 0;
|
||||||
|
|
||||||
// Regular expression to identify if a string is a UUID
|
|
||||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
for (const item of data.value) {
|
for (const item of data.value) {
|
||||||
const isFolder = !!item.folder;
|
const isFolder = !!item.folder;
|
||||||
|
|
||||||
/**
|
// Only skip if it's a folder AND it's a UUID (storage container)
|
||||||
* FILTER: If the item is a folder and the name is a UUID, skip it.
|
// If a user named a file with a UUID, we still want it.
|
||||||
* These are storage containers created by the upload action, not user-facing folders.
|
|
||||||
*/
|
|
||||||
if (isFolder && uuidRegex.test(item.name)) {
|
if (isFolder && uuidRegex.test(item.name)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const extension = isFolder
|
const extension = isFolder ? 'FOLDER' : (item.name.split('.').pop()?.toUpperCase() || 'UNKNOWN');
|
||||||
? 'FOLDER'
|
|
||||||
: (item.name.split('.').pop()?.toUpperCase() || 'UNKNOWN');
|
|
||||||
|
|
||||||
const fileSize = item.size ? BigInt(item.size) : BigInt(0);
|
|
||||||
|
|
||||||
await prisma.fileNode.upsert({
|
await prisma.fileNode.upsert({
|
||||||
where: { oneDriveId: item.id },
|
where: { oneDriveId: item.id }, // Primary match
|
||||||
update: {
|
update: {
|
||||||
name: item.name,
|
name: item.name,
|
||||||
size: fileSize,
|
size: BigInt(item.size || 0),
|
||||||
isFolder: isFolder,
|
isFolder: isFolder,
|
||||||
metadata: {
|
|
||||||
type: extension,
|
|
||||||
mimeType: item.file?.mimeType || null
|
|
||||||
},
|
|
||||||
path: item.parentReference?.path + '/' + item.name,
|
path: item.parentReference?.path + '/' + item.name,
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
},
|
},
|
||||||
|
|
@ -72,14 +44,11 @@ export async function syncOneDrive() {
|
||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
oneDriveId: item.id,
|
oneDriveId: item.id,
|
||||||
name: item.name,
|
name: item.name,
|
||||||
size: fileSize,
|
size: BigInt(item.size || 0),
|
||||||
isFolder: isFolder,
|
isFolder: isFolder,
|
||||||
path: item.parentReference?.path + '/' + item.name,
|
path: item.parentReference?.path + '/' + item.name,
|
||||||
ownerId: session.user.id,
|
ownerId: session.user.id,
|
||||||
metadata: {
|
metadata: { type: extension, mimeType: item.file?.mimeType || null },
|
||||||
type: extension,
|
|
||||||
mimeType: item.file?.mimeType || null
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
syncedCount++;
|
syncedCount++;
|
||||||
|
|
@ -87,9 +56,7 @@ export async function syncOneDrive() {
|
||||||
|
|
||||||
revalidatePath('/dashboard');
|
revalidatePath('/dashboard');
|
||||||
return { success: true, count: syncedCount };
|
return { success: true, count: syncedCount };
|
||||||
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error("Sync Process Failure:", error.message);
|
throw new Error(error.message);
|
||||||
throw new Error(error.message || "An unexpected error occurred during sync.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,69 +0,0 @@
|
||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
import { Box, Button, Typography, Paper, LinearProgress, Container } from "@mui/material";
|
|
||||||
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
|
||||||
import { uploadFileAction } from "../upload-actions";
|
|
||||||
|
|
||||||
export default function UploadPage() {
|
|
||||||
const [file, setFile] = useState<File | null>(null);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
|
|
||||||
const handleUpload = async () => {
|
|
||||||
if (!file) return;
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append("file", file);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await uploadFileAction(formData);
|
|
||||||
alert("Book added to WebCalibre!");
|
|
||||||
setFile(null);
|
|
||||||
} catch (err) {
|
|
||||||
alert("Upload failed. Check console.");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Container maxWidth="sm" sx={{ mt: 8 }}>
|
|
||||||
<Paper elevation={3} sx={{ p: 4, textAlign: 'center', borderRadius: 4 }}>
|
|
||||||
<Typography variant="h5" gutterBottom fontWeight="bold">
|
|
||||||
Upload to Library
|
|
||||||
</Typography>
|
|
||||||
<Typography color="textSecondary" mb={4}>
|
|
||||||
Files will be saved in your OneDrive "WebCalibre" folder.
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Box sx={{ border: '2px dashed #ccc', p: 4, mb: 3, borderRadius: 2 }}>
|
|
||||||
<input
|
|
||||||
accept=".pdf,.epub,.mobi,.txt"
|
|
||||||
style={{ display: 'none' }}
|
|
||||||
id="file-input"
|
|
||||||
type="file"
|
|
||||||
onChange={(e) => setFile(e.target.files?.[0] || null)}
|
|
||||||
/>
|
|
||||||
<label htmlFor="file-input">
|
|
||||||
<Button variant="outlined" component="span" startIcon={<CloudUploadIcon />}>
|
|
||||||
{file ? file.name : "Choose Book File"}
|
|
||||||
</Button>
|
|
||||||
</label>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{loading && <LinearProgress sx={{ mb: 2 }} />}
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
fullWidth
|
|
||||||
size="large"
|
|
||||||
disabled={!file || loading}
|
|
||||||
onClick={handleUpload}
|
|
||||||
>
|
|
||||||
{loading ? "Uploading..." : "Start Upload"}
|
|
||||||
</Button>
|
|
||||||
</Paper>
|
|
||||||
</Container>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
49
src/app/update/[id]/_actions.ts
Normal file
49
src/app/update/[id]/_actions.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
'use server';
|
||||||
|
|
||||||
|
//src/app/update/[id]/_actions.ts
|
||||||
|
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
|
||||||
|
export async function updateFileAction(formData: FormData) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
|
const id = formData.get("id") as string;
|
||||||
|
const name = formData.get("name") as string;
|
||||||
|
const description = formData.get("description") as string;
|
||||||
|
const parentIdRaw = formData.get("parentId") as string;
|
||||||
|
const customMetadataRaw = formData.get("customMetadata") as string;
|
||||||
|
|
||||||
|
const parentId = (parentIdRaw === "" || parentIdRaw === "root") ? null : parentIdRaw;
|
||||||
|
const customMetadata = customMetadataRaw ? JSON.parse(customMetadataRaw) : {};
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Get existing record to preserve system metadata (like mimeType)
|
||||||
|
const existing = await prisma.fileNode.findUnique({ where: { id } });
|
||||||
|
const existingMetadata = (existing?.metadata as Record<string, any>) || {};
|
||||||
|
|
||||||
|
// 2. Update the record
|
||||||
|
await prisma.fileNode.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
parentId,
|
||||||
|
metadata: {
|
||||||
|
...customMetadata, // User's new keys
|
||||||
|
type: name.split('.').pop()?.toUpperCase() || existingMetadata.type || "FILE",
|
||||||
|
mimeType: existingMetadata.mimeType // Preserve the original mimeType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
revalidatePath(`/update/${id}`);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Update error:", error);
|
||||||
|
return { success: false, message: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/app/update/[id]/page.tsx
Normal file
34
src/app/update/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { redirect, notFound } from "next/navigation";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { Container } from "@mui/material";
|
||||||
|
import UpdateView from "./update-view";
|
||||||
|
|
||||||
|
// Note: params is now handled as a Promise
|
||||||
|
export default async function UpdatePage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session) redirect("/");
|
||||||
|
|
||||||
|
// 1. Await the params to get the actual ID
|
||||||
|
const { id } = await params;
|
||||||
|
|
||||||
|
// 2. Fetch the specific file using the awaited ID
|
||||||
|
const fileNode = await prisma.fileNode.findUnique({
|
||||||
|
where: { id: id }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!fileNode) notFound();
|
||||||
|
|
||||||
|
// Fetch folders for the destination dropdown
|
||||||
|
const folders = await prisma.fileNode.findMany({
|
||||||
|
where: { isFolder: true },
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
select: { id: true, name: true }
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container maxWidth="md" sx={{ py: 8 }}>
|
||||||
|
<UpdateView fileNode={fileNode} folders={folders} />
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
171
src/app/update/[id]/update-view.tsx
Normal file
171
src/app/update/[id]/update-view.tsx
Normal file
|
|
@ -0,0 +1,171 @@
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import {
|
||||||
|
Box, Button, Typography, Paper, Stack,
|
||||||
|
TextField, MenuItem, IconButton, Grid, Divider
|
||||||
|
} from "@mui/material";
|
||||||
|
import SaveIcon from "@mui/icons-material/Save";
|
||||||
|
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
|
||||||
|
import AssignmentIcon from '@mui/icons-material/Assignment';
|
||||||
|
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
|
||||||
|
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
||||||
|
import FolderIcon from "@mui/icons-material/Folder";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { updateFileAction } from "./_actions";
|
||||||
|
|
||||||
|
interface MetadataPair {
|
||||||
|
key: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function UpdateView({ fileNode, folders }: any) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
// 1. Initialize Basic Info
|
||||||
|
const [name, setName] = useState(fileNode.name);
|
||||||
|
const [description, setDescription] = useState(fileNode.description || "");
|
||||||
|
const [parentId, setParentId] = useState(fileNode.parentId || "");
|
||||||
|
|
||||||
|
// 2. Parse existing JSON metadata into Key/Value array for the UI
|
||||||
|
// We filter out 'type' and 'mimeType' as they are system-managed
|
||||||
|
const initialMetadata = Object.entries(fileNode.metadata || {})
|
||||||
|
.filter(([key]) => !['type', 'mimeType'].includes(key))
|
||||||
|
.map(([key, value]) => ({ key, value: String(value) }));
|
||||||
|
|
||||||
|
const [customMetadata, setCustomMetadata] = useState<MetadataPair[]>(initialMetadata);
|
||||||
|
|
||||||
|
const handleUpdate = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("id", fileNode.id);
|
||||||
|
formData.append("name", name);
|
||||||
|
formData.append("description", description);
|
||||||
|
formData.append("parentId", parentId);
|
||||||
|
|
||||||
|
// Convert array back to object for storage
|
||||||
|
const metadataObj = customMetadata.reduce((acc, curr) => {
|
||||||
|
if (curr.key.trim()) acc[curr.key.trim()] = curr.value;
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, string>);
|
||||||
|
|
||||||
|
formData.append("customMetadata", JSON.stringify(metadataObj));
|
||||||
|
|
||||||
|
const res = await updateFileAction(formData);
|
||||||
|
if (res.success) {
|
||||||
|
router.push("/dashboard");
|
||||||
|
router.refresh();
|
||||||
|
} else {
|
||||||
|
alert("Update failed");
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper sx={{ p: { xs: 3, md: 6 }, borderRadius: 4 }} elevation={3}>
|
||||||
|
<Button startIcon={<ArrowBackIcon />} onClick={() => router.back()} sx={{ mb: 2 }}>
|
||||||
|
Back
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Typography variant="h4" fontWeight={900} color="primary" gutterBottom>
|
||||||
|
Edit File Details
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Stack spacing={4} sx={{ mt: 2 }}>
|
||||||
|
{/* Name Field */}
|
||||||
|
<TextField
|
||||||
|
label="File Name"
|
||||||
|
fullWidth value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
slotProps={{ inputLabel: { shrink: true } }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Folder Select */}
|
||||||
|
<TextField
|
||||||
|
id="update-dest-select"
|
||||||
|
select fullWidth label="Destination Folder"
|
||||||
|
value={parentId}
|
||||||
|
onChange={(e) => setParentId(e.target.value)}
|
||||||
|
slotProps={{
|
||||||
|
select: { displayEmpty: true },
|
||||||
|
inputLabel: { shrink: true }
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MenuItem value=""><em>-- Root --</em></MenuItem>
|
||||||
|
{folders.map((f: any) => (
|
||||||
|
<MenuItem key={f.id} value={f.id}>{f.name}</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
|
||||||
|
{/* Custom Metadata Section */}
|
||||||
|
<Box>
|
||||||
|
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||||
|
<Typography variant="h6" fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||||
|
<AssignmentIcon color="primary" /> Custom Attributes
|
||||||
|
</Typography>
|
||||||
|
<Button
|
||||||
|
startIcon={<AddCircleOutlineIcon />}
|
||||||
|
size="small"
|
||||||
|
onClick={() => setCustomMetadata([...customMetadata, { key: "", value: "" }])}
|
||||||
|
>
|
||||||
|
Add Field
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Stack spacing={2}>
|
||||||
|
{customMetadata.map((row, index) => (
|
||||||
|
<Grid container spacing={1} key={index} alignItems="center">
|
||||||
|
<Grid item xs={5}>
|
||||||
|
<TextField
|
||||||
|
fullWidth size="small" placeholder="Key"
|
||||||
|
value={row.key}
|
||||||
|
onChange={(e) => {
|
||||||
|
const updated = [...customMetadata];
|
||||||
|
updated[index].key = e.target.value;
|
||||||
|
setCustomMetadata(updated);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={6}>
|
||||||
|
<TextField
|
||||||
|
fullWidth size="small" placeholder="Value"
|
||||||
|
value={row.value}
|
||||||
|
onChange={(e) => {
|
||||||
|
const updated = [...customMetadata];
|
||||||
|
updated[index].value = e.target.value;
|
||||||
|
setCustomMetadata(updated);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
<Grid item xs={1}>
|
||||||
|
<IconButton color="error" onClick={() => setCustomMetadata(customMetadata.filter((_, i) => i !== index))}>
|
||||||
|
<DeleteOutlineIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
label="Description"
|
||||||
|
multiline rows={4} fullWidth
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
slotProps={{ inputLabel: { shrink: true } }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="contained" size="large" fullWidth
|
||||||
|
startIcon={<SaveIcon />}
|
||||||
|
onClick={handleUpdate}
|
||||||
|
disabled={loading}
|
||||||
|
sx={{ py: 1.5, fontWeight: 'bold' }}
|
||||||
|
>
|
||||||
|
{loading ? "Saving..." : "Save Changes"}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -5,17 +5,55 @@ import { getFreshAccessToken } from "@/lib/auth-utils";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
|
||||||
// createFolderAction remains the same...
|
/**
|
||||||
|
* 1. CREATE FOLDER: Virtual Only
|
||||||
|
* Logic: User-created organizational folders exist ONLY in the database.
|
||||||
|
* No call to OneDrive is made here.
|
||||||
|
*/
|
||||||
|
export async function createFolderAction(name: string, parentId?: string | null) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const internalId = crypto.randomUUID();
|
||||||
|
|
||||||
|
const newNode = await prisma.fileNode.create({
|
||||||
|
data: {
|
||||||
|
id: internalId,
|
||||||
|
oneDriveId: null, // Virtual folders do not have a cloud ID
|
||||||
|
name: name,
|
||||||
|
isFolder: true,
|
||||||
|
path: `virtual:/${name}`,
|
||||||
|
ownerId: session.user.id,
|
||||||
|
parentId: parentId || null,
|
||||||
|
metadata: { type: "FOLDER" }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/upload");
|
||||||
|
revalidatePath("/dashboard");
|
||||||
|
|
||||||
|
return { success: true, node: newNode };
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Folder creation error:", error);
|
||||||
|
throw new Error(error.message || "Failed to create virtual folder");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 2. UPLOAD FILE: Physical Container
|
||||||
|
* Logic: Creates a physical folder (UUID) on OneDrive to hold the file.
|
||||||
|
* This ensures every file has a unique storage space in the cloud.
|
||||||
|
*/
|
||||||
export async function uploadFileAction(formData: FormData) {
|
export async function uploadFileAction(formData: FormData) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user?.id) throw new Error("Unauthorized");
|
if (!session?.user?.id) throw new Error("Unauthorized");
|
||||||
|
|
||||||
const file = formData.get("file") as File;
|
const file = formData.get("file") as File;
|
||||||
const description = formData.get("description") as string || "";
|
const description = formData.get("description") as string || "";
|
||||||
const parentId = formData.get("parentId") as string | null;
|
const parentIdRaw = formData.get("parentId") as string | null;
|
||||||
|
const parentId = (parentIdRaw === "" || parentIdRaw === "root") ? null : parentIdRaw;
|
||||||
|
|
||||||
// Parse the dynamic metadata from the client
|
|
||||||
const customMetadataRaw = formData.get("customMetadata") as string;
|
const customMetadataRaw = formData.get("customMetadata") as string;
|
||||||
const customMetadata = customMetadataRaw ? JSON.parse(customMetadataRaw) : {};
|
const customMetadata = customMetadataRaw ? JSON.parse(customMetadataRaw) : {};
|
||||||
|
|
||||||
|
|
@ -23,54 +61,75 @@ export async function uploadFileAction(formData: FormData) {
|
||||||
|
|
||||||
const accessToken = await getFreshAccessToken(session.user.id);
|
const accessToken = await getFreshAccessToken(session.user.id);
|
||||||
const rootFolder = "WebCalibre";
|
const rootFolder = "WebCalibre";
|
||||||
const internalId = crypto.randomUUID();
|
const internalId = crypto.randomUUID(); // This UUID will be the OneDrive folder name
|
||||||
|
|
||||||
// 1. Create OneDrive Storage Folder
|
// 1. Create the Physical Storage Folder on OneDrive
|
||||||
const createSubFolderRes = await fetch(`https://graph.microsoft.com/v1.0/me/drive/root:/${rootFolder}:/children`, {
|
const createSubFolderRes = await fetch(`https://graph.microsoft.com/v1.0/me/drive/root:/${rootFolder}:/children`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
|
headers: {
|
||||||
body: JSON.stringify({ name: internalId, folder: {} })
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: internalId,
|
||||||
|
folder: {},
|
||||||
|
"@microsoft.graph.conflictBehavior": "fail"
|
||||||
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!createSubFolderRes.ok) throw new Error("Storage directory creation failed");
|
if (!createSubFolderRes.ok) {
|
||||||
|
const errorData = await createSubFolderRes.json();
|
||||||
|
throw new Error(errorData.error?.message || "Storage directory creation failed");
|
||||||
|
}
|
||||||
const subFolderData = await createSubFolderRes.json();
|
const subFolderData = await createSubFolderRes.json();
|
||||||
|
|
||||||
// 2. Upload Session & File Transfer (Existing logic is fine)
|
// 2. Create Upload Session inside the new Physical Folder
|
||||||
const sessionUrl = `https://graph.microsoft.com/v1.0/me/drive/items/${subFolderData.id}:/${encodeURIComponent(file.name)}:/createUploadSession`;
|
const sessionUrl = `https://graph.microsoft.com/v1.0/me/drive/items/${subFolderData.id}:/${encodeURIComponent(file.name)}:/createUploadSession`;
|
||||||
const sessionRes = await fetch(sessionUrl, {
|
const sessionRes = await fetch(sessionUrl, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
|
headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ item: { "@microsoft.graph.conflictBehavior": "replace" } })
|
body: JSON.stringify({ item: { "@microsoft.graph.conflictBehavior": "replace" } })
|
||||||
});
|
});
|
||||||
|
|
||||||
const { uploadUrl } = await sessionRes.json();
|
const { uploadUrl } = await sessionRes.json();
|
||||||
const buffer = Buffer.from(await file.arrayBuffer());
|
const buffer = Buffer.from(await file.arrayBuffer());
|
||||||
await fetch(uploadUrl, {
|
|
||||||
|
// 3. PUT the file binary
|
||||||
|
const uploadRes = await fetch(uploadUrl, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: { "Content-Length": `${file.size}`, "Content-Range": `bytes 0-${file.size - 1}/${file.size}` },
|
headers: {
|
||||||
|
"Content-Length": `${file.size}`,
|
||||||
|
"Content-Range": `bytes 0-${file.size - 1}/${file.size}`
|
||||||
|
},
|
||||||
body: buffer
|
body: buffer
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. Final Database Record with Merged Metadata
|
const uploadedFileData = await uploadRes.json();
|
||||||
|
const oneDriveId = uploadedFileData.id;
|
||||||
const extension = file.name.split('.').pop()?.toUpperCase() || "UNKNOWN";
|
const extension = file.name.split('.').pop()?.toUpperCase() || "UNKNOWN";
|
||||||
|
|
||||||
|
// 4. Create record in Database
|
||||||
|
// Link it to the VIRTUAL folder via parentId
|
||||||
await prisma.fileNode.create({
|
await prisma.fileNode.create({
|
||||||
data: {
|
data: {
|
||||||
id: internalId,
|
id: internalId,
|
||||||
|
oneDriveId: oneDriveId,
|
||||||
name: file.name,
|
name: file.name,
|
||||||
description: description,
|
description: description,
|
||||||
size: BigInt(file.size),
|
size: BigInt(file.size),
|
||||||
isFolder: false,
|
isFolder: false,
|
||||||
path: `/${rootFolder}/${internalId}/${file.name}`,
|
path: `/${rootFolder}/${internalId}/${file.name}`,
|
||||||
ownerId: session.user.id,
|
ownerId: session.user.id,
|
||||||
parentId: parentId || null,
|
parentId: parentId,
|
||||||
metadata: {
|
metadata: {
|
||||||
...customMetadata, // User's dynamic keys (Latitude, Author, etc.)
|
...customMetadata,
|
||||||
type: extension, // System keys (preserved for UI icons)
|
type: extension,
|
||||||
mimeType: file.type
|
mimeType: file.type
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath("/dashboard");
|
revalidatePath("/dashboard");
|
||||||
|
revalidatePath("/upload");
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
@ -1,28 +1,20 @@
|
||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState, useRef } from "react";
|
||||||
import {
|
import {
|
||||||
Box, Button, Typography, Paper, LinearProgress, Stack,
|
Box, Button, Typography, Paper, Stack,
|
||||||
TextField, MenuItem, IconButton, Tooltip, Divider,
|
TextField, MenuItem, IconButton, Divider,
|
||||||
Grid
|
Grid, CircularProgress
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
||||||
import CreateNewFolderIcon from "@mui/icons-material/CreateNewFolder";
|
|
||||||
import FolderIcon from "@mui/icons-material/Folder";
|
import FolderIcon from "@mui/icons-material/Folder";
|
||||||
|
import CreateNewFolderIcon from "@mui/icons-material/CreateNewFolder";
|
||||||
import AssignmentIcon from '@mui/icons-material/Assignment';
|
import AssignmentIcon from '@mui/icons-material/Assignment';
|
||||||
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
|
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
|
||||||
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { uploadFileAction, createFolderAction } from "./_actions";
|
import { uploadFileAction, createFolderAction } from "./_actions";
|
||||||
|
|
||||||
const formatFileSize = (bytes: number) => {
|
|
||||||
if (bytes === 0) return '0 Bytes';
|
|
||||||
const k = 1024;
|
|
||||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
|
||||||
};
|
|
||||||
|
|
||||||
interface MetadataPair {
|
interface MetadataPair {
|
||||||
key: string;
|
key: string;
|
||||||
value: string;
|
value: string;
|
||||||
|
|
@ -30,19 +22,37 @@ interface MetadataPair {
|
||||||
|
|
||||||
export default function UploadView({ user, folders = [] }: any) {
|
export default function UploadView({ user, folders = [] }: any) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const [file, setFile] = useState<File | null>(null);
|
const [file, setFile] = useState<File | null>(null);
|
||||||
const [description, setDescription] = useState("");
|
const [description, setDescription] = useState("");
|
||||||
const [parentId, setParentId] = useState("");
|
const [parentId, setParentId] = useState("");
|
||||||
const [status, setStatus] = useState<'idle' | 'uploading' | 'success'>('idle');
|
const [status, setStatus] = useState<'idle' | 'uploading' | 'success'>('idle');
|
||||||
|
|
||||||
// Dynamic Metadata State
|
|
||||||
const [customMetadata, setCustomMetadata] = useState<MetadataPair[]>([]);
|
const [customMetadata, setCustomMetadata] = useState<MetadataPair[]>([]);
|
||||||
|
|
||||||
|
// Folder Creation State
|
||||||
const [showFolderInput, setShowFolderInput] = useState(false);
|
const [showFolderInput, setShowFolderInput] = useState(false);
|
||||||
const [newFolderName, setNewFolderName] = useState("");
|
const [newFolderName, setNewFolderName] = useState("");
|
||||||
const [isCreatingFolder, setIsCreatingFolder] = useState(false);
|
const [isCreatingFolder, setIsCreatingFolder] = useState(false);
|
||||||
|
|
||||||
|
const handleCreateFolder = async () => {
|
||||||
|
if (!newFolderName.trim()) return;
|
||||||
|
setIsCreatingFolder(true);
|
||||||
|
try {
|
||||||
|
// FIX: Pass the current parentId to the action so it nests correctly
|
||||||
|
const result = await createFolderAction(newFolderName, parentId);
|
||||||
|
if (result.success) {
|
||||||
|
setNewFolderName("");
|
||||||
|
setShowFolderInput(false);
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
alert(err.message || "Failed to create folder");
|
||||||
|
} finally {
|
||||||
|
setIsCreatingFolder(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const addMetadataRow = () => setCustomMetadata([...customMetadata, { key: "", value: "" }]);
|
const addMetadataRow = () => setCustomMetadata([...customMetadata, { key: "", value: "" }]);
|
||||||
|
|
||||||
const removeMetadataRow = (index: number) => {
|
const removeMetadataRow = (index: number) => {
|
||||||
|
|
@ -64,7 +74,6 @@ export default function UploadView({ user, folders = [] }: any) {
|
||||||
formData.append("description", description);
|
formData.append("description", description);
|
||||||
formData.append("parentId", parentId);
|
formData.append("parentId", parentId);
|
||||||
|
|
||||||
// Pass custom metadata as a JSON string
|
|
||||||
const metadataObj = customMetadata.reduce((acc, curr) => {
|
const metadataObj = customMetadata.reduce((acc, curr) => {
|
||||||
if (curr.key.trim()) acc[curr.key.trim()] = curr.value;
|
if (curr.key.trim()) acc[curr.key.trim()] = curr.value;
|
||||||
return acc;
|
return acc;
|
||||||
|
|
@ -79,6 +88,7 @@ export default function UploadView({ user, folders = [] }: any) {
|
||||||
setFile(null);
|
setFile(null);
|
||||||
setDescription("");
|
setDescription("");
|
||||||
setCustomMetadata([]);
|
setCustomMetadata([]);
|
||||||
|
router.push("/dashboard");
|
||||||
router.refresh();
|
router.refresh();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
@ -94,42 +104,97 @@ export default function UploadView({ user, folders = [] }: any) {
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
<Stack spacing={4} sx={{ mt: 4 }}>
|
<Stack spacing={4} sx={{ mt: 4 }}>
|
||||||
{/* Section 1: Destination (Condensed for brevity, same as your original) */}
|
{/* 1. Destination */}
|
||||||
<Box>
|
<Box>
|
||||||
<Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
<Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||||
<FolderIcon color="primary" /> 1. Destination
|
<FolderIcon color="primary" /> 1. Destination
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
<Stack direction="row" spacing={1}>
|
<Stack direction="row" spacing={1}>
|
||||||
<TextField
|
<TextField
|
||||||
select fullWidth label="Target Project / Folder"
|
id="project-destination-select"
|
||||||
|
select
|
||||||
|
fullWidth
|
||||||
|
label="Target Project / Folder"
|
||||||
value={parentId}
|
value={parentId}
|
||||||
onChange={(e) => setParentId(e.target.value)}
|
onChange={(e) => setParentId(e.target.value)}
|
||||||
|
size="small"
|
||||||
|
slotProps={{
|
||||||
|
select: { displayEmpty: true },
|
||||||
|
inputLabel: { shrink: true },
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<MenuItem value=""><em>-- Root --</em></MenuItem>
|
<MenuItem value=""><em>-- Root (Main Folder) --</em></MenuItem>
|
||||||
{folders.map((f: any) => (
|
{folders.map((f: any) => (
|
||||||
<MenuItem key={f.id} value={f.id}>{f.name}</MenuItem>
|
<MenuItem key={f.id} value={f.id}>{f.name}</MenuItem>
|
||||||
))}
|
))}
|
||||||
</TextField>
|
</TextField>
|
||||||
<IconButton color="primary" onClick={() => setShowFolderInput(!showFolderInput)} sx={{ border: '1px solid #ccc', borderRadius: 1 }}>
|
<IconButton
|
||||||
|
color="primary"
|
||||||
|
onClick={() => setShowFolderInput(!showFolderInput)}
|
||||||
|
sx={{ border: '1px solid #ccc', borderRadius: 1 }}
|
||||||
|
>
|
||||||
<CreateNewFolderIcon />
|
<CreateNewFolderIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
|
{showFolderInput && (
|
||||||
|
<Box sx={{ mt: 2, p: 2, bgcolor: '#f8f9fa', borderRadius: 2 }}>
|
||||||
|
<Typography variant="subtitle2" gutterBottom>
|
||||||
|
{parentId ? `Create inside current selection` : `Create at Root`}
|
||||||
|
</Typography>
|
||||||
|
<Stack direction="row" spacing={1}>
|
||||||
|
<TextField
|
||||||
|
fullWidth size="small" placeholder="Folder Name (e.g. Project-2)"
|
||||||
|
value={newFolderName}
|
||||||
|
onChange={(e) => setNewFolderName(e.target.value)}
|
||||||
|
onKeyPress={(e) => e.key === 'Enter' && handleCreateFolder()}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={handleCreateFolder}
|
||||||
|
disabled={isCreatingFolder || !newFolderName}
|
||||||
|
>
|
||||||
|
{isCreatingFolder ? <CircularProgress size={24} /> : "Create"}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{/* Section 2: Upload Area */}
|
{/* 2. Upload Area */}
|
||||||
<Box>
|
<Box>
|
||||||
<Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
<Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||||
<CloudUploadIcon color="primary" /> 2. Upload File
|
<CloudUploadIcon color="primary" /> 2. Upload File
|
||||||
</Typography>
|
</Typography>
|
||||||
<input type="file" id="file-input" hidden onChange={(e) => setFile(e.target.files?.[0] || null)} />
|
|
||||||
<label htmlFor="file-input">
|
<input
|
||||||
<Button variant="outlined" component="span" fullWidth sx={{ p: 4, borderStyle: 'dashed' }}>
|
type="file"
|
||||||
{file ? file.name : "Select File"}
|
ref={fileInputRef}
|
||||||
</Button>
|
style={{ display: 'none' }}
|
||||||
</label>
|
onChange={(e) => setFile(e.target.files?.[0] || null)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
fullWidth
|
||||||
|
sx={{ p: 4, borderStyle: 'dashed', textTransform: 'none' }}
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
>
|
||||||
|
{file ? (
|
||||||
|
<Box>
|
||||||
|
<Typography color="success.main" fontWeight="bold">✓ {file.name}</Typography>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
Click to change file ({(file.size / 1024 / 1024).toFixed(2)} MB)
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
"Click to Select File"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{/* Section 3: Dynamic Metadata Area */}
|
{/* 3. Custom Attributes */}
|
||||||
<Box>
|
<Box>
|
||||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
|
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
|
||||||
<Typography variant="h6" fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
<Typography variant="h6" fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||||
|
|
@ -140,16 +205,12 @@ export default function UploadView({ user, folders = [] }: any) {
|
||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 2 }}>
|
|
||||||
Add specific details like Author, Latitude, Aperture, or Part Number.
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Stack spacing={2}>
|
<Stack spacing={2}>
|
||||||
{customMetadata.map((row, index) => (
|
{customMetadata.map((row, index) => (
|
||||||
<Grid container spacing={1} key={index} alignItems="center">
|
<Grid container spacing={1} key={index} alignItems="center">
|
||||||
<Grid item xs={5}>
|
<Grid item xs={5}>
|
||||||
<TextField
|
<TextField
|
||||||
fullWidth size="small" placeholder="Key (e.g. Latitude)"
|
fullWidth size="small" placeholder="Key (e.g. Project-ID)"
|
||||||
value={row.key} onChange={(e) => updateMetadataRow(index, 'key', e.target.value)}
|
value={row.key} onChange={(e) => updateMetadataRow(index, 'key', e.target.value)}
|
||||||
/>
|
/>
|
||||||
</Grid>
|
</Grid>
|
||||||
|
|
@ -180,8 +241,9 @@ export default function UploadView({ user, folders = [] }: any) {
|
||||||
variant="contained" size="large" fullWidth
|
variant="contained" size="large" fullWidth
|
||||||
disabled={!file || status === 'uploading'}
|
disabled={!file || status === 'uploading'}
|
||||||
onClick={handleUpload}
|
onClick={handleUpload}
|
||||||
|
sx={{ py: 2, fontWeight: 'bold' }}
|
||||||
>
|
>
|
||||||
{status === 'uploading' ? 'Processing...' : 'Add to Library'}
|
{status === 'uploading' ? 'Uploading to OneDrive...' : 'Start Upload'}
|
||||||
</Button>
|
</Button>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
|
||||||
20
src/auth.ts
20
src/auth.ts
|
|
@ -1,3 +1,4 @@
|
||||||
|
// src/auth.ts
|
||||||
import NextAuth from "next-auth";
|
import NextAuth from "next-auth";
|
||||||
import { PrismaAdapter } from "@auth/prisma-adapter";
|
import { PrismaAdapter } from "@auth/prisma-adapter";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
@ -10,6 +11,7 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||||
callbacks: {
|
callbacks: {
|
||||||
async jwt({ token, account, user }) {
|
async jwt({ token, account, user }) {
|
||||||
// 1. Handle OAuth tokens (from first sign-in)
|
// 1. Handle OAuth tokens (from first sign-in)
|
||||||
|
// This captures the tokens directly from the Microsoft Azure response
|
||||||
if (account) {
|
if (account) {
|
||||||
token.accessToken = account.access_token;
|
token.accessToken = account.access_token;
|
||||||
token.refreshToken = account.refresh_token;
|
token.refreshToken = account.refresh_token;
|
||||||
|
|
@ -17,10 +19,10 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Attach User ID and Role to the token
|
// 2. Attach User ID and Role to the token
|
||||||
// When 'user' exists, it's the first time we've fetched this user from the DB during login
|
// This runs when the user first logs in
|
||||||
if (user) {
|
if (user) {
|
||||||
token.sub = user.id;
|
token.sub = user.id;
|
||||||
// @ts-ignore - 'role' exists on our custom User model
|
// @ts-ignore - 'role' is a custom field in your Postgres User table
|
||||||
token.role = user.role;
|
token.role = user.role;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -29,10 +31,16 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||||
|
|
||||||
async session({ session, token }) {
|
async session({ session, token }) {
|
||||||
// 3. Pass values from the JWT Token into the Client-facing Session
|
// 3. Pass values from the JWT Token into the Client-facing Session
|
||||||
if (session?.user && token.sub) {
|
// This makes the tokens and IDs available to your API routes and Components
|
||||||
session.user.id = token.sub;
|
if (session?.user) {
|
||||||
// @ts-ignore - Attaching the role so the Navbar and Settings page can see it
|
session.user.id = token.sub as string;
|
||||||
session.user.role = token.role;
|
|
||||||
|
// @ts-ignore - Attaching the role for UI permissions
|
||||||
|
session.user.role = token.role as string;
|
||||||
|
|
||||||
|
// IMPORTANT: We must attach the accessToken here so the
|
||||||
|
// /api/download route can use it to fetch from MS Graph
|
||||||
|
session.accessToken = token.accessToken as string;
|
||||||
}
|
}
|
||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
|
|
|
||||||
24
src/types/next-auth.d.ts
vendored
Normal file
24
src/types/next-auth.d.ts
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
// src/types/next-auth.d.ts
|
||||||
|
import NextAuth, { DefaultSession } from "next-auth"
|
||||||
|
import { JWT } from "next-auth/jwt"
|
||||||
|
|
||||||
|
declare module "next-auth" {
|
||||||
|
/**
|
||||||
|
* Returned by `useSession`, `auth`, and received as a prop on the `SessionProvider` React Context
|
||||||
|
*/
|
||||||
|
interface Session {
|
||||||
|
accessToken?: string;
|
||||||
|
user: {
|
||||||
|
id: string;
|
||||||
|
role?: string;
|
||||||
|
} & DefaultSession["user"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module "next-auth/jwt" {
|
||||||
|
/** Returned by the `jwt` callback and `getToken`, when using JWT sessions */
|
||||||
|
interface JWT {
|
||||||
|
accessToken?: string;
|
||||||
|
role?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue