Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
79 changes: 79 additions & 0 deletions backend/src/iac/backend-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as servicediscovery from 'aws-cdk-lib/aws-servicediscovery';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as ssm from 'aws-cdk-lib/aws-ssm';

import { Construct } from 'constructs';
Expand Down Expand Up @@ -528,6 +529,78 @@ export class BackendStack extends cdk.Stack {
],
});

// Create S3 bucket for file uploads
const uploadBucket = new s3.Bucket(this, `${appName}UploadBucket-${props.environment}`, {
bucketName: `${appName.toLowerCase()}-uploads-${props.environment}-${this.account}`,
removalPolicy: RemovalPolicy.RETAIN,
cors: [
{
allowedMethods: [
s3.HttpMethods.GET,
s3.HttpMethods.POST,
s3.HttpMethods.PUT,
s3.HttpMethods.DELETE,
],
allowedOrigins: ['*'], // In production, you should restrict this to your domain
allowedHeaders: ['*'],
maxAge: 3000,
},
],
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, // Block all public access for security
});

// Create a policy for authenticated users to upload files
const uploadPolicy = new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['s3:PutObject', 's3:GetObject', 's3:DeleteObject'],
resources: [`${uploadBucket.bucketArn}/*`],
});

// Create an IAM role for authenticated users
const authenticatedRole = new iam.Role(
this,
`${appName}AuthenticatedRole-${props.environment}`,
{
assumedBy: new iam.FederatedPrincipal(
'cognito-identity.amazonaws.com',
{
StringEquals: {
'cognito-identity.amazonaws.com:aud': userPool.userPoolId,
},
'ForAnyValue:StringLike': {
'cognito-identity.amazonaws.com:amr': 'authenticated',
},
},
'sts:AssumeRoleWithWebIdentity',
),
},
);

// Attach the upload policy to the authenticated role
authenticatedRole.addToPolicy(uploadPolicy);

// Add environment variable to the container for the S3 bucket name
container.addEnvironment('S3_UPLOAD_BUCKET', uploadBucket.bucketName);

// Grant the task role access to the S3 bucket
uploadBucket.grantReadWrite(taskRole);

// Add more specific S3 permissions for file processing
taskRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
's3:GetObject',
's3:PutObject',
's3:DeleteObject',
's3:ListBucket',
's3:GetObjectTagging',
's3:PutObjectTagging',
],
resources: [uploadBucket.bucketArn, `${uploadBucket.bucketArn}/*`],
}),
);

// Outputs
new cdk.CfnOutput(this, 'ReportsTableName', {
value: reportsTable.tableName,
Expand All @@ -548,5 +621,11 @@ export class BackendStack extends cdk.Stack {
value: nlb.loadBalancerDnsName,
description: 'Network Load Balancer DNS Name',
});

// Add S3 bucket name to outputs
new cdk.CfnOutput(this, 'UploadBucketName', {
value: uploadBucket.bucketName,
description: 'S3 Bucket for file uploads',
});
}
}
26 changes: 16 additions & 10 deletions backend/src/reports/models/report.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,31 @@ export class Report {
@ApiProperty({ description: 'Unique identifier for the report' })
id: string;

@ApiProperty({ description: 'Title of the report' })
title: string;

@ApiProperty({ description: 'Content of the report' })
content: string;

@ApiProperty({ description: 'User ID of the report owner' })
userId: string;

@ApiProperty({ description: 'Creation timestamp' })
createdAt: string;
@ApiProperty({ description: 'Title of the report' })
title: string;

@ApiProperty({ description: 'Last update timestamp' })
updatedAt: string;
@ApiProperty({ description: 'Whether the report is bookmarked' })
bookmarked: boolean;

@ApiProperty({ description: 'Category of the report' })
category: string;

@ApiProperty({
description: 'Status of the report',
enum: ReportStatus,
default: ReportStatus.UNREAD,
})
status: ReportStatus;

@ApiProperty({ description: 'File path of the report' })
filePath: string;

@ApiProperty({ description: 'Creation timestamp' })
createdAt: string;

@ApiProperty({ description: 'Last update timestamp' })
updatedAt: string;
}
30 changes: 30 additions & 0 deletions backend/src/reports/reports.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
ValidationPipe,
Req,
UnauthorizedException,
Post,
} from '@nestjs/common';
import {
ApiTags,
Expand All @@ -16,6 +17,7 @@ import {
ApiBearerAuth,
ApiParam,
ApiQuery,
ApiBody,
} from '@nestjs/swagger';
import { ReportsService } from './reports.service';
import { Report } from './models/report.model';
Expand Down Expand Up @@ -105,6 +107,34 @@ export class ReportsController {
return this.reportsService.updateStatus(id, updateDto, userId);
}

@ApiOperation({ summary: 'Create a new report from S3 file' })
@ApiResponse({
status: 201,
description: 'Report created successfully',
type: Report,
})
@ApiBody({
schema: {
type: 'object',
properties: {
filePath: {
type: 'string',
description: 'S3 file path for the report',
},
},
required: ['filePath'],
},
description: 'S3 file path for the report',
})
@Post()
async createReport(
@Body('filePath') filePath: string,
@Req() request: RequestWithUser,
): Promise<Report> {
const userId = this.extractUserId(request);
return this.reportsService.saveReport(filePath, userId);
}

private extractUserId(request: RequestWithUser): string {
// The user object is attached to the request by our middleware
const user = request.user;
Expand Down
52 changes: 51 additions & 1 deletion backend/src/reports/reports.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ import {
GetItemCommand,
UpdateItemCommand,
DynamoDBServiceException,
PutItemCommand,
} from '@aws-sdk/client-dynamodb';
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
import { Report } from './models/report.model';
import { Report, ReportStatus } from './models/report.model';
import { GetReportsQueryDto } from './dto/get-reports.dto';
import { UpdateReportStatusDto } from './dto/update-report-status.dto';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class ReportsService {
Expand Down Expand Up @@ -250,4 +252,52 @@ export class ReportsService {
throw new InternalServerErrorException(`Failed to update report status for ID ${id}`);
}
}

async saveReport(filePath: string, userId: string): Promise<Report> {
if (!filePath) {
throw new NotFoundException('File URL is required');
}

if (!userId) {
throw new ForbiddenException('User ID is required');
}

try {
const newReport: Report = {
id: uuidv4(),
userId,
filePath,
title: 'New Report',
bookmarked: false,
category: '',
status: ReportStatus.UNREAD,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};

// Save to DynamoDB
const command = new PutItemCommand({
TableName: this.tableName,
Item: marshall(newReport),
});

await this.dynamoClient.send(command);
this.logger.log(`Successfully saved report with ID ${newReport.id} for user ${userId}`);

return newReport;
} catch (error: unknown) {
this.logger.error(`Error saving report for user ${userId}:`);
this.logger.error(error);

if (error instanceof DynamoDBServiceException) {
if (error.name === 'ResourceNotFoundException') {
throw new InternalServerErrorException(
`Table "${this.tableName}" not found. Please check your database configuration.`,
);
}
}

throw new InternalServerErrorException('Failed to save report to database');
}
}
}