Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 80 additions & 2 deletions custom/uploader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ const progress = ref(0);
const uploaded = ref(false);
const uploadedSize = ref(0);

const downloadFileUrl = ref('');

watch(() => uploaded, (value) => {
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The watch function is incorrectly watching the entire uploaded ref object instead of its value. It should be watch(uploaded, (value) => ...) or watch(() => uploaded.value, (value) => ...) to properly react to changes in the uploaded state.

Suggested change
watch(() => uploaded, (value) => {
watch(uploaded, (value) => {

Copilot uses AI. Check for mistakes.
emit('update:emptiness', !value);
});
Expand All @@ -118,9 +120,45 @@ function uploadGeneratedImage(imgBlob) {
});
}

onMounted(() => {
onMounted(async () => {
const previewColumnName = `previewUrl_${props.meta.pluginInstanceId}`;
if (props.record[previewColumnName]) {

let queryValues;
try {
queryValues = JSON.parse(atob(route.query.values as string));
} catch (e) {
queryValues = {};
}

if (queryValues[props.meta.pathColumnName]) {


Comment on lines +134 to +135
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty lines (134-135) should be removed to maintain consistent code formatting.

Suggested change

Copilot uses AI. Check for mistakes.
downloadFileUrl.value = queryValues[props.meta.pathColumnName];

const resp = await callAdminForthApi({
path: `/plugin/${props.meta.pluginInstanceId}/get-file-download-url`,
method: 'POST',
body: {
filePath: queryValues[props.meta.pathColumnName]
},
});
if (resp.error) {
adminforth.alert({
message: t('Error getting file url'),
variant: 'danger'
});
return;
}
const file = await downloadAsFile(resp.url);
if (!file) {
return;
}
onFileChange({
target: {
files: [file],
},
});
} else if (props.record[previewColumnName]) {
imgPreview.value = props.record[previewColumnName];
uploaded.value = true;
emit('update:emptiness', false);
Expand Down Expand Up @@ -300,6 +338,46 @@ const onFileChange = async (e) => {
}
}

async function downloadAsFile(url) {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ fileDownloadURL: url }),
};
const fullPath = `${import.meta.env.VITE_ADMINFORTH_PUBLIC_PATH || ''}/adminapi/v1/plugin/${props.meta.pluginInstanceId}/proxy-download`;
const resp = await fetch(fullPath, options);
let isError = false;
try {
const jsonResp = await resp.clone().json();
if (jsonResp.error) {
adminforth.alert({
message: t('Error uploading file'),
variant: 'danger'
});
isError = true;
}
} catch (e) {

}

if (isError) {
return null;
}

const blob = await resp.blob();

const filename = url.split('/').pop()?.split('?')[0] || `file`;
const filenameParts = filename.split('.');
const extension = filenameParts.length > 1 ? filenameParts.pop() : '';
const nameWithoutExt = filenameParts.join('.');
const newFileName = extension
? `${nameWithoutExt}_copy_${Date.now()}.${extension}`
: `${filename}_copy_${Date.now()}`;

const file = new File([blob], newFileName, { type: blob.type });
return file;
}

</script>
47 changes: 47 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { PluginOptions } from './types.js';
import { AdminForthPlugin, AdminForthResourceColumn, AdminForthResource, Filters, IAdminForth, IHttpServer, suggestIfTypo } from "adminforth";
import { Readable } from "stream";
import { RateLimiter } from "adminforth";
import { url } from 'inspector/promises';

const ADMINFORTH_NOT_YET_USED_TAG = 'adminforth-candidate-for-cleanup';

Expand Down Expand Up @@ -86,6 +87,7 @@ export default class UploadPlugin extends AdminForthPlugin {
minShowWidth: this.options.preview?.minShowWidth,
generationPrompt: this.options.generation?.generationPrompt,
recorPkFieldName: this.resourceConfig.columns.find((column: any) => column.primaryKey)?.name,
pathColumnName: this.options.pathColumnName,
};
// define components which will be imported from other components
this.componentPath('imageGenerator.vue');
Expand Down Expand Up @@ -411,6 +413,51 @@ export default class UploadPlugin extends AdminForthPlugin {
},
});

server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get-file-download-url`,
handler: async ({ body, adminUser }) => {
const { filePath } = body;
if (!filePath) {
return { error: 'Missing filePath' };
}
const url = await this.options.storageAdapter.getDownloadUrl(filePath, 1800);

return {
url,
};
},
Comment on lines +418 to +428
Copy link

Copilot AI Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The endpoint doesn't validate user authorization to access the specific file. Any authenticated admin user can request a download URL for any file path. Consider adding authorization checks to ensure the user has permission to access the file, or at least verify the file belongs to a resource the user can access.

Copilot uses AI. Check for mistakes.
});

server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/proxy-download`,
handler: async ({ body, response }) => {
const { fileDownloadURL } = body;

if (!fileDownloadURL) {
return { error: 'Missing fileDownloadURL' };
}

const upstream = await fetch(fileDownloadURL);
if (!upstream.ok || !upstream.body) {
return { error: `Failed to download file (status ${upstream.status})` };
}

const contentType = upstream.headers.get('content-type') || 'application/octet-stream';
const contentLength = upstream.headers.get('content-length');
const contentDisposition = upstream.headers.get('content-disposition');

response.setHeader('Content-Type', contentType);
if (contentLength) response.setHeader('Content-Length', contentLength);
if (contentDisposition) response.setHeader('Content-Disposition', contentDisposition);

//@ts-ignore Node 18+: convert Web stream to Node stream and pipe to response
Readable.fromWeb(upstream.body).pipe(response.blobStream());
return null;
},
});

}

}