Skip to content

Commit

Permalink
Merge pull request #40 from yu23ki14/cdk
Browse files Browse the repository at this point in the history
deployment
  • Loading branch information
yu23ki14 authored Jul 9, 2024
2 parents 3361b99 + db18507 commit 6020b05
Show file tree
Hide file tree
Showing 19 changed files with 3,090 additions and 2,889 deletions.
15 changes: 13 additions & 2 deletions backend/src/auth/guards/nextauth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,18 @@ export class NextAuthGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
// Retrieving user sesion
const req = context.switchToHttp().getRequest();
const session = await getSession({ req });

// const session = await getSession({ req });
const getSession = await fetch(
`${process.env.NEXTAUTH_URL}/api/auth/session`,
{
method: 'GET',
headers: {
cookie: req.headers.cookie,
},
},
);
const session = await getSession.json();

// Checking for required roles
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
Expand All @@ -29,7 +40,7 @@ export class NextAuthGuard implements CanActivate {
]);

let user;
if (session) {
if (session && session.user) {
// Get user data based on session
user = await this.prisma.user.findUnique({
where: {
Expand Down
5 changes: 1 addition & 4 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ async function bootstrap() {
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));

app.enableCors({
origin:
process.env.NODE_ENV === 'production'
? process.env.FRONTEND_URL
: 'http://localhost:3001',
origin: process.env.FRONTEND_URL,
credentials: true,
});

Expand Down
6 changes: 5 additions & 1 deletion backend/src/qf/qf.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export class QfService {
if (!matchingRound || donationAmount <= 0) return 0;

const qfInfo = await this.calculateQuadraticFundingAmount(matchingRound.id);
console.log(qfInfo);

/**
* We can estimate the QF amount by doing these steps:
* 1. Square root the qfValue
Expand Down Expand Up @@ -155,7 +157,9 @@ export class QfService {
(prev, grantId) => {
const grants = prev.grants;
const qfValue = qfInfo.qfValues[grantId];
const qfPercentage = qfValue / qfInfo.sumOfQfValues;
const qfPercentage = qfInfo.sumOfQfValues
? qfValue / qfInfo.sumOfQfValues
: 0;
const qfAmount = qfPercentage * totalFundsInPool;

grants[grantId] = {
Expand Down
4 changes: 2 additions & 2 deletions cdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ DB のシークレット情報を secret manager に保存しているが、ARN
#### Frontend

1. `aws ecr get-login-password --region ap-northeast-1 --profile cfj_pgf | docker login --username AWS --password-stdin 905418185537.dkr.ecr.ap-northeast-1.amazonaws.com`
2. `docker build -t card-frame:latest -f ./Dockerfile .`
3. `docker tag card-frame:latest 905418185537.dkr.ecr.ap-northeast-1.amazonaws.com/stg-web2qf-frontend:latest`
2. `docker build -t web2qf-frontend:latest -f ./Dockerfile .`
3. `docker tag web2qf-frontend:latest 905418185537.dkr.ecr.ap-northeast-1.amazonaws.com/stg-web2qf-frontend:latest`
4. `docker push 905418185537.dkr.ecr.ap-northeast-1.amazonaws.com/stg-web2qf-frontend:latest`

### Backend
Expand Down
19 changes: 18 additions & 1 deletion cdk/bin/cdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { AmplifyStack } from "../lib/amplify-stack"
import { getConfig } from "../config/config"
import { VpcStack } from "../lib/vpc-stack"
import { RdsStack } from "../lib/rds-stack"
import { BackendAppStack } from "../lib/app-stack"
import { BackendAppStack, FrontendAppStack } from "../lib/app-stack"

const app = new cdk.App()

Expand Down Expand Up @@ -65,6 +65,23 @@ new BackendAppStack(
}
)

new FrontendAppStack(
app,
`${stage}${config.appName}FrontendApp`,
{
description: "Frontend App Runner for the application",
env: {
account: config.aws.account,
region: config.aws.region,
},
},
{
vpc: vpc.vpc,
config,
appRunnerSecurityGroup: rds.frontendAppRunnerSG,
}
)

// new AmplifyStack(
// app,
// `${stage}${config.appName}Amplify`,
Expand Down
7 changes: 6 additions & 1 deletion cdk/cdk.context.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,10 @@
]
}
]
}
},
"availability-zones:account=905418185537:region=ap-northeast-1": [
"ap-northeast-1a",
"ap-northeast-1c",
"ap-northeast-1d"
]
}
10 changes: 4 additions & 6 deletions cdk/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export function getConfig(stage: string) {
aws: {
account: process.env.AWS_ACCOUNT,
region: process.env.AWS_REGION,
vpcId: process.env.AWS_VPC_ID,
bastionKeypairId: process.env.AWS_BASTION_KEYPAIR_ID,
bastionKeypairName: process.env.AWS_BASTION_KEYPAIR_NAME,
},
Expand All @@ -28,18 +27,17 @@ export function getConfig(stage: string) {
frontend: {
url: process.env.FRONTEND_URL,
nextauth_url: process.env.NEXTAUTH_URL,
},

github: {
repository: process.env.GITHUB_REPOSITORY,
nextauth_secret: process.env.NEXTAUTH_SECRET,
fingerprint_key: process.env.FINGERPRINT_KEY,
cookie_domain: process.env.COOKIE_DOMAIN,
api_url: process.env.API_URL,
},

google: {
clientId: process.env.GOOGLE_CLIENT_ID,
},

secrets: {
github: process.env.GITHUB_TOKEN,
google_client_secret: process.env.GOOGLE_CLIENT_SECRET,
stripe_sk: process.env.STRIPE_SK,
stripe_pk: process.env.STRIPE_PK,
Expand Down
107 changes: 62 additions & 45 deletions cdk/construct/apprunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class BackendAppRunner extends Construct {
`${props.config.stage}-${props.config.appName}-AppRunner-VpcConnector`,
{
subnets: vpc.selectSubnets({
subnetType: ec2.SubnetType.PUBLIC,
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
}).subnetIds,
securityGroups: [appRunnerSecurityGroup.securityGroupId],
vpcConnectorName: `${
Expand Down Expand Up @@ -179,26 +179,26 @@ export class BackendAppRunner extends Construct {
}
}

export class FrameAppRunner extends Construct {
export class FrontendAppRunner extends Construct {
constructor(scope: Construct, id: string, props: AppRunnerProps) {
super(scope, id)

const { vpc, appRunnerSecurityGroup } = props
const { vpc, appRunnerSecurityGroup, config } = props

const instanceRole = new iam.Role(
scope,
`${props.config.stage}-${props.config.appName}-Frame-AppRunner-Role`,
`${props.config.stage}-${props.config.appName}-FrontAppRunner-Role`,
{
roleName: `${props.config.stage}-${props.config.appName}-Frame-AppRunner-Role`,
roleName: `${props.config.stage}-${props.config.appName}-FrontAppRunner-Role`,
assumedBy: new iam.ServicePrincipal("tasks.apprunner.amazonaws.com"),
}
)

const accessRole = new iam.Role(
scope,
`${props.config.stage}-${props.config.appName}-Frame-AppRunner-AccessRole`,
`${props.config.stage}-${props.config.appName}-FrontAppRunner-AccessRole`,
{
roleName: `${props.config.stage}-${props.config.appName}-Frame-AppRunner-AccessRole`,
roleName: `${props.config.stage}-${props.config.appName}-FrontAppRunner-AccessRole`,
assumedBy: new iam.ServicePrincipal("build.apprunner.amazonaws.com"),
}
)
Expand All @@ -208,33 +208,54 @@ export class FrameAppRunner extends Construct {
)
)

const secretsDB = secretsmanager.Secret.fromSecretNameV2(
scope,
`${
props.config.stage
}${props.config.appName.toLowerCase()}Rds-db-secret-${
props.config.database.secret_suffix
}`,
`${
props.config.stage
}${props.config.appName.toLowerCase()}Rds-db-secret-${
props.config.database.secret_suffix
}`
)

const vpcConnector = new apprunner.CfnVpcConnector(
scope,
`${props.config.stage}-${props.config.appName}-Frame-AppRunner-VpcConnector`,
`${props.config.stage}-${props.config.appName}-FrontAppRunner-VpcConnector`,
{
subnets: vpc.selectSubnets({
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
}).subnetIds,
securityGroups: [appRunnerSecurityGroup.securityGroupId],
vpcConnectorName: `${
props.config.stage
}-${props.config.appName.toLowerCase()}-frame-apprunner-vpc-connector`,
}-${props.config.appName.toLowerCase()}-frontapprunner-vpc-connector`,
}
)

const secretsDB = secretsmanager.Secret.fromSecretNameV2(
scope,
`${props.config.stage}-${props.config.appName.toLowerCase()}-db-secret-${
props.config.database.secret_suffix
}`,
`${props.config.stage}-${props.config.appName.toLowerCase()}-db-secret-${
props.config.database.secret_suffix
}`
)
const DATABASE_URL = `postgresql://${secretsDB
.secretValueFromJson("username")
.unsafeUnwrap()
.toString()}:${secretsDB
.secretValueFromJson("password")
.unsafeUnwrap()
.toString()}@${secretsDB
.secretValueFromJson("host")
.unsafeUnwrap()
.toString()}:${secretsDB
.secretValueFromJson("port")
.unsafeUnwrap()
.toString()}/${secretsDB
.secretValueFromJson("dbname")
.unsafeUnwrap()
.toString()}?schema=public&connect_timeout=300`

new apprunner.CfnService(
scope,
`${props.config.stage}-${props.config.appName}-Frame-AppRunner`,
`${props.config.stage}-${props.config.appName}-FrontAppRunner`,
{
sourceConfiguration: {
authenticationConfiguration: {
Expand All @@ -247,45 +268,41 @@ export class FrameAppRunner extends Construct {
props.config.aws.region
}.amazonaws.com/${
props.config.stage
}-${props.config.appName.toLowerCase()}-frame:latest`,
}-${props.config.appName.toLowerCase()}-frontend:latest`,
imageConfiguration: {
port: "3000",
runtimeEnvironmentVariables: [
{
name: "DB_HOST",
value: secretsDB
.secretValueFromJson("host")
.unsafeUnwrap()
.toString(),
name: "GOOGLE_CLIENT_ID",
value: config.google.clientId,
},
{
name: "DB_PORT",
value: secretsDB
.secretValueFromJson("port")
.unsafeUnwrap()
.toString(),
name: "GOOGLE_CLIENT_SECRET",
value: config.secrets.google_client_secret,
},
{
name: "DB_USER",
value: secretsDB
.secretValueFromJson("username")
.unsafeUnwrap()
.toString(),
name: "DATABASE_URL",
value: DATABASE_URL,
},
{
name: "DB_PASSWORD",
value: secretsDB
.secretValueFromJson("password")
.unsafeUnwrap()
.toString(),
name: "NEXT_PUBLIC_API_URL",
value: config.frontend.api_url,
},
{
name: "NEXT_PUBLIC_FINGERPRINT_KEY",
value: config.frontend.fingerprint_key,
},
{
name: "NEXTAUTH_URL",
value: "http://localhost:3000",
},
{
name: "DB_DATABASE",
value: "card_frame",
name: "NEXTAUTH_SECRET",
value: config.frontend.nextauth_secret,
},
{
name: "PORT",
value: "3000",
name: "COOKIE_DOMAIN",
value: config.frontend.cookie_domain,
},
],
},
Expand All @@ -309,7 +326,7 @@ export class FrameAppRunner extends Construct {

serviceName: `${
props.config.stage
}-${props.config.appName.toLowerCase()}-frame-apprunner`,
}-${props.config.appName.toLowerCase()}-front-apprunner`,
}
)
}
Expand Down
21 changes: 20 additions & 1 deletion cdk/lib/app-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as cdk from "aws-cdk-lib"
import * as ec2 from "aws-cdk-lib/aws-ec2"
import { Construct } from "constructs"
import { getConfig } from "../config/config"
import { BackendAppRunner } from "../construct/apprunner"
import { BackendAppRunner, FrontendAppRunner } from "../construct/apprunner"

interface AppProps {
vpc: ec2.IVpc
Expand All @@ -28,3 +28,22 @@ export class BackendAppStack extends cdk.Stack {
})
}
}

export class FrontendAppStack extends cdk.Stack {
constructor(
scope: Construct,
id: string,
props: cdk.StackProps,
appProps: AppProps
) {
super(scope, id, props)

const { vpc, appRunnerSecurityGroup, config } = appProps

new FrontendAppRunner(this, id, {
vpc,
appRunnerSecurityGroup,
config,
})
}
}
2 changes: 1 addition & 1 deletion cdk/lib/rds-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class RdsStack extends Stack {
maxAllocatedStorage: 16,
vpc,
vpcSubnets: {
subnetType: ec2.SubnetType.PUBLIC,
subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
},
credentials: this.rdsCredentials,
securityGroups: [this.dbSG],
Expand Down
Loading

0 comments on commit 6020b05

Please sign in to comment.