Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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: 82 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 { Construct } from 'constructs';
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
Expand Down Expand Up @@ -515,6 +516,81 @@ 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,
versioned: true, // Enable versioning in production
Copy link
Collaborator

Choose a reason for hiding this comment

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

I believe we don't need to use versioning.

lifecycleRules: [
{
noncurrentVersionExpiration: cdk.Duration.days(7),
// Move objects to infrequent access after 30 days
transitions: [
{
storageClass: s3.StorageClass.INFREQUENT_ACCESS,
transitionAfter: cdk.Duration.days(30),
},
],
},
],
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}/*`],
conditions: {
// Restrict uploads to PDF and JPG files
StringLike: {
's3:x-amz-content-type': ['application/pdf', 'image/jpeg', 'image/jpg'],
Copy link
Collaborator

Choose a reason for hiding this comment

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

we don't need to have validation here since that means we have the validation in many places and when we want to make any kind of change like add more file types, we'll have to change multiple places.

},
},
});

// 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);

// Outputs
new cdk.CfnOutput(this, 'ReportsTableName', {
value: reportsTable.tableName,
Expand All @@ -535,5 +611,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',
});
}
}
31 changes: 23 additions & 8 deletions backend/src/reports/models/report.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,40 @@ export class Report {
@ApiProperty({ description: 'Unique identifier for the report' })
id: string;

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

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

@ApiProperty({ description: 'Content of the report' })
content: string;
@ApiProperty({ description: 'Whether the report is bookmarked' })
bookmark: boolean;

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

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

@ApiProperty({ description: 'Last update timestamp' })
updatedAt: string;
@ApiProperty({ description: 'Doctor associated with the report' })
doctor: string;

@ApiProperty({ description: 'Facility where the report was created' })
facility: string;

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

@ApiProperty({ description: 'File URL of the report' })
fileUrl: 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: {
fileUrl: {
type: 'string',
description: 'S3 file URL for the report',
},
},
required: ['fileUrl'],
},
description: 'S3 file URL for the report',
})
@Post()
async createReport(
@Body('fileUrl') fileUrl: string,
@Req() request: RequestWithUser,
): Promise<Report> {
const userId = this.extractUserId(request);
return this.reportsService.saveReport(fileUrl, userId);
}

private extractUserId(request: RequestWithUser): string {
// The user object is attached to the request by our middleware
const user = request.user;
Expand Down
55 changes: 54 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,55 @@ export class ReportsService {
throw new InternalServerErrorException(`Failed to update report status for ID ${id}`);
}
}

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

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

try {
const newReport: Report = {
id: uuidv4(),
userId,
fileUrl,
title: 'New Report',
bookmark: false,
category: '',
date: '',
doctor: '',
facility: '',
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');
}
}
}