mirror of
https://github.com/Hestia-Homes/assessment-model.git
synced 2026-06-08 11:37:25 +00:00
using rotating aws credentials
This commit is contained in:
parent
07be8eaf84
commit
2b17aad9a7
1 changed files with 26 additions and 5 deletions
|
|
@ -1,12 +1,28 @@
|
|||
// pages/api/get-presigned-url.ts
|
||||
import S3 from "aws-sdk/clients/s3";
|
||||
import STS from "aws-sdk/clients/sts"; // Import STS for temporary credentials
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
// Validate the input
|
||||
const PresignedUrlBodySchema = z.object({
|
||||
fileKey: z.string(),
|
||||
});
|
||||
|
||||
// Function to get temporary credentials using GetSessionToken
|
||||
async function getTemporaryCredentials() {
|
||||
const sts = new STS({
|
||||
accessKeyId: process.env.RETROFIT_ENERGY_ASSESSMENTS_AWS_ACCESS_KEY, // Your permanent access key
|
||||
secretAccessKey: process.env.ENERGY_ASSESSMENTS_AWS_SECRET, // Your permanent secret access key
|
||||
region: process.env.PRESIGN_AWS_REGION,
|
||||
});
|
||||
|
||||
// Request temporary credentials with GetSessionToken
|
||||
const data = await sts.getSessionToken({ DurationSeconds: 900 }).promise(); // Token valid for 15 minutes
|
||||
return data.Credentials;
|
||||
}
|
||||
|
||||
// API handler
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
let validatedBody;
|
||||
|
|
@ -21,27 +37,32 @@ export async function POST(request: NextRequest) {
|
|||
}
|
||||
|
||||
try {
|
||||
// Get temporary credentials using GetSessionToken
|
||||
const credentials = await getTemporaryCredentials();
|
||||
|
||||
// Initialize S3 with temporary credentials
|
||||
const s3 = new S3({
|
||||
signatureVersion: "v4",
|
||||
region: process.env.PRESIGN_AWS_REGION,
|
||||
accessKeyId: process.env.RETROFIT_ENERGY_ASSESSMENTS_AWS_ACCESS_KEY,
|
||||
secretAccessKey: process.env.ENERGY_ASSESSMENTS_AWS_SECRET,
|
||||
accessKeyId: credentials.AccessKeyId,
|
||||
secretAccessKey: credentials.SecretAccessKey,
|
||||
sessionToken: credentials.SessionToken, // Include session token
|
||||
});
|
||||
|
||||
const { fileKey } = validatedBody;
|
||||
|
||||
// Presigned URL is valid for 5 minutes
|
||||
// Generate presigned URL valid for 5 minutes
|
||||
const preSignedUrl = await s3.getSignedUrl("getObject", {
|
||||
Bucket: process.env.RETROFIT_ENERGY_ASSESSMENTS_BUCKET,
|
||||
Key: fileKey,
|
||||
Expires: 5 * 60,
|
||||
Expires: 5 * 60, // URL expiration in seconds
|
||||
});
|
||||
|
||||
return new NextResponse(JSON.stringify({ url: preSignedUrl }), {
|
||||
status: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
console.error("Error generating presigned URL:", error);
|
||||
return new NextResponse(JSON.stringify({ msg: "Internal server error" }), {
|
||||
status: 500,
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue