Skip to content
Open
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
16 changes: 16 additions & 0 deletions cdk-deploy/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as cdk from "@aws-cdk/core";
import { StaticSite } from "./static-site-construct";

class StaticSiteStack extends cdk.Stack {
constructor(parent: cdk.App, name: string) {
super(parent, name);

new StaticSite(this, name);
}
}

const app = new cdk.App();

new StaticSiteStack(app, "useless-shop-2");

app.synth();
59 changes: 59 additions & 0 deletions cdk-deploy/static-site-construct.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Construct, Stack } from "@aws-cdk/core";
import * as s3 from "@aws-cdk/aws-s3";
import * as s3deploy from "@aws-cdk/aws-s3-deployment";
import * as iam from "@aws-cdk/aws-iam";
import * as cloudfront from "@aws-cdk/aws-cloudfront";

export class StaticSite extends Construct {
constructor(parent: Stack, name: string) {
super(parent, name);

const cloudFrontOAI = new cloudfront.OriginAccessIdentity(this, "useless-shop-2");

const siteBucket = new s3.Bucket(this, "useless-shop-bucket-1", {
bucketName: 'useless-shop-bucket-2',
websiteIndexDocument: "index.html",
publicReadAccess: false,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});

siteBucket.addToResourcePolicy(
new iam.PolicyStatement({
actions: ["s3:GetObject"],
resources: [siteBucket.arnForObjects("*")],
principals: [
new iam.CanonicalUserPrincipal(
cloudFrontOAI.cloudFrontOriginAccessIdentityS3CanonicalUserId
),
],
})
);

const distribution = new cloudfront.CloudFrontWebDistribution(
this,
"useless-shop-cfwd-2",
{
originConfigs: [
{
s3OriginSource: {
s3BucketSource: siteBucket,
originAccessIdentity: cloudFrontOAI,
},
behaviors: [
{
isDefaultBehavior: true,
},
],
},
],
}
);

new s3deploy.BucketDeployment(this, "useless-shop-bucket-deployment-2", {
sources: [s3deploy.Source.asset("./dist")],
destinationBucket: siteBucket,
distribution,
distributionPaths: ["/*"],
});
}
}
64 changes: 64 additions & 0 deletions cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"app": "npx ts-node --prefer-ts-exts ./cdk-deploy/index.ts",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"**/*.d.ts",
"**/*.js",
"tsconfig.json",
"package*.json",
"yarn.lock",
"node_modules",
"test"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true
}
}
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
"private": true,
"scripts": {
"start": "vite",
"deploy": "cdk deploy",
"destroy": "cdk destroy",
"bootstrap": "cdk bootstrap --profile=default",
"build": "tsc && vite build",
"preview": "npm run build && vite preview",
"test": "vitest",
Expand All @@ -23,11 +26,15 @@
"formik": "^2.2.9",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hot-toast": "^2.4.1",
"react-query": "^3.39.1",
"react-router-dom": "^6.3.0",
"yup": "^0.32.11"
},
"devDependencies": {
"@aws-cdk/aws-s3": "^1.204.0",
"@aws-cdk/aws-s3-deployment": "^1.204.0",
"@aws-cdk/core": "^1.204.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^14.2.1",
Expand All @@ -37,6 +44,8 @@
"@typescript-eslint/parser": "^5.30.5",
"@vitejs/plugin-react": "^1.3.2",
"@vitest/ui": "^0.18.0",
"aws-cdk": "^2.106.1",
"aws-cdk-lib": "^2.106.1",
"c8": "^7.11.3",
"eslint": "^8.19.0",
"eslint-config-prettier": "^8.5.0",
Expand Down
19 changes: 11 additions & 8 deletions src/components/MainLayout/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,17 @@ export default function Header() {
<AppBar position="relative">
<Toolbar>
<Typography variant="h6" sx={{ flexGrow: 1 }}>
<Link
component={RouterLink}
sx={{ color: "inherit" }}
underline="none"
to="/"
>
My Store!
</Link>
<div style={{ display: 'flex'}}>
<Link
style={{ margin: 'auto', transform: 'translateX(25%)'}}
component={RouterLink}
sx={{ color: "inherit" }}
underline="none"
to="/"
>
THE VIRTUES STORE
</Link>
</div>
</Typography>

{auth && (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React from "react";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import axios from "axios";
import toast from 'react-hot-toast';

type CSVFileImportProps = {
url: string;
Expand All @@ -24,23 +26,36 @@ export default function CSVFileImport({ url, title }: CSVFileImportProps) {

const uploadFile = async () => {
console.log("uploadFile to", url);
console.log('file', file);

// Get the presigned URL
// const response = await axios({
// method: "GET",
// url,
// params: {
// name: encodeURIComponent(file.name),
// },
// });
// console.log("File to upload: ", file.name);
// console.log("Uploading to: ", response.data);
// const result = await fetch(response.data, {
// method: "PUT",
// body: file,
// });
// console.log("Result: ", result);
// setFile("");
const token = window.localStorage.getItem('authorization_token');
console.log('token', token);

if (file) {
// Get the presigned URL
const { data: { signedUrl }} = await axios({
method: "GET",
headers: {
Authorization: `Basic ${token}`,
},
url,
params: {
name: encodeURIComponent(file.name),
},
});
console.log("File to upload: ", file.name);
console.log("Uploading to: ", signedUrl);
toast.success(`File "${file.name}" successfully uploaded to the import service`);

const result = await fetch(signedUrl, {
method: "PUT",
body: file,
});
console.log("Result: ", result);
setFile(undefined);
} else {
throw new Error('File is undefined');
}
};
return (
<Box>
Expand Down
4 changes: 2 additions & 2 deletions src/constants/apiPaths.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const API_PATHS = {
product: "https://.execute-api.eu-west-1.amazonaws.com/dev",
order: "https://.execute-api.eu-west-1.amazonaws.com/dev",
import: "https://.execute-api.eu-west-1.amazonaws.com/dev",
bff: "https://.execute-api.eu-west-1.amazonaws.com/dev",
import: "https://7dtijjqfhk.execute-api.us-east-1.amazonaws.com/dev",
bff: "https://7dtijjqfhk.execute-api.us-east-1.amazonaws.com/dev",
cart: "https://.execute-api.eu-west-1.amazonaws.com/dev",
};

Expand Down
20 changes: 20 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import { ReactQueryDevtools } from "react-query/devtools";
import { theme } from "~/theme";
import axios from "axios";
import toast, { Toaster } from 'react-hot-toast';

const queryClient = new QueryClient({
defaultOptions: {
Expand All @@ -19,6 +21,23 @@ if (import.meta.env.DEV) {
worker.start({ onUnhandledRequest: "bypass" });
}


axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response.status === 401) {
toast.error('401 Unauthorized: token is not provided');
}

if (error.response.status === 403) {
toast.error('403 Forbidden: token is not valid');
}
return Promise.reject(error);
}
);

const container = document.getElementById("app");
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const root = createRoot(container!);
Expand All @@ -29,6 +48,7 @@ root.render(
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
<Toaster />
</ThemeProvider>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
Expand Down
10 changes: 8 additions & 2 deletions src/queries/products.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ export function useAvailableProducts() {
"available-products",
async () => {
const res = await axios.get<AvailableProduct[]>(
`${API_PATHS.bff}/product/available`
`${API_PATHS.bff}/products`,
{
withCredentials: false,
}
);
return res.data;
}
Expand All @@ -29,7 +32,10 @@ export function useAvailableProduct(id?: string) {
["product", { id }],
async () => {
const res = await axios.get<AvailableProduct>(
`${API_PATHS.bff}/product/${id}`
`${API_PATHS.bff}/products/${id}`,
{
withCredentials: false,
}
);
return res.data;
},
Expand Down
4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"paths": {
"~/*": ["./*"]
},
"target": "ESNext",
"target": "ES2020",
"module": "commonjs",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
Expand All @@ -13,7 +14,6 @@
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
Expand Down