Created
March 4, 2024 22:07
-
-
Save Miguel07Alm/1fc4b77570d8902d741e54a2c80d15c2 to your computer and use it in GitHub Desktop.
Simple script for adding files to AWS S3 Bucket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use server"; | |
import { cookies } from "next/headers"; | |
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; | |
import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; | |
import crypto from "crypto"; | |
import verifyJwtToken from "@/utils/api/verifyJwtToken"; | |
const generateFileName = (bytes = 32) => | |
crypto.randomBytes(bytes).toString("hex"); | |
const s3 = new S3Client({ | |
region: process.env.AWS_BUCKET_REGION!, | |
credentials: { | |
accessKeyId: process.env.AWS_ACCESS_KEY!, | |
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!, | |
}, | |
}); | |
const allowedFileTypes = [ | |
"image/jpeg", | |
"image/png", | |
"image/webp", | |
"application/pdf", | |
]; | |
const maxFileSize = 1024 * 1024 * 10; // 10 MB | |
export async function getSignedURL( | |
type: string, | |
size: number, | |
checksum: string | |
) { | |
const access_token = cookies().get("access_token"); | |
if (!access_token) { | |
return { failure: "Not authenticated" }; | |
} | |
if (size > maxFileSize) { | |
return { | |
failure: "File too large", | |
}; | |
} | |
if (!allowedFileTypes.includes(type)) { | |
return { | |
failure: "File type not allowed", | |
}; | |
} | |
const decoded = await verifyJwtToken(access_token); | |
if (decoded) { | |
const email = decoded.email as string; | |
const putOBjCommand = new PutObjectCommand({ | |
Bucket: process.env.AWS_BUCKET_NAME!, | |
Key: generateFileName(), | |
ContentType: allowedFileTypes.join(","), | |
ContentLength: size, | |
ChecksumSHA256: checksum, | |
Metadata: { | |
email: email, | |
}, | |
}); | |
const signed_url = await getSignedUrl(s3, putOBjCommand, { | |
expiresIn: 60, | |
}); | |
return { | |
success: { | |
url: signed_url, | |
}, | |
}; | |
} | |
return { | |
failure: "Your token is not valid!", | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment