Skip to content

Commit

Permalink
add jwt and terraform setting update (#2)
Browse files Browse the repository at this point in the history
* .

* update aws context

* update .env

* encrypt .env && google_key

* add enviroment tar file

* update apollo server context

base64 encoding update

* .

* .

* .

* jwt verify update

auth0/node-jsonwebtoken#208 (comment)
자바와 nodejs의 jwt토큰 호환성 에러해결

* .

* .

* .

* update traivs

* update travis.yml

* update aws credencial

* remove directives

* update .env in private.tar.enc

* terraform add i_am_role cloudwatch for lamdbda

* update terraform.tf

* .

* .

* .

* update mutation

* update mutation

* update lambda loadbalancer

* update terrform

* .

* .

* .

* .

* before merge
  • Loading branch information
lcc3108 authored Dec 14, 2019
1 parent 67a2021 commit 7624dc7
Show file tree
Hide file tree
Showing 12 changed files with 228 additions and 30 deletions.
Binary file removed .env.enc
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ node_modules
aws_key.json
google_key.json
.terraform
*.tar
*.log
dist
index.zip
Expand Down
11 changes: 5 additions & 6 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ cache:
- "$HOME/terraform"
env:
global:
- secure: p/c6ViUEAHhs0nV7xWVZCrfxjFwSVVENcT89HwgaPk0t8KsPbmA13dR8Zz6lJ8qUBMpx+MKm0c98/aG/JFUQrc9D8gbpBpU5wJUlHpO4ZdXww2U13+baDFe3md84t7oFxKzEcAvFo0G/tRFTFyir+jgzGwlwAlB18+iKwc+4Zg9GmFgkp/sO84A/SIIAa9VM7ELNG4Z9B8wtYd+iTQfy20noF6M6QYq9HyhU5oeVLjnrchpjUO4SCXsHuh6uAVbCuFNA9yXxrD3IVEedfB0Grpniwvcjlfj+LvximYccn1Ppw+Q6pQEif2ZgfQySuk/T53ZFnZTpEy2U3uc470rLaaRYLiBOdG3Fad1Lh8SOfXPPrX1pc2BOdg4962XtlD//88FXzWyxk2bg4ID27xFc+huWUJ8dEjzFNFjT74o2dO0BW7u0RtK9JqggI2kwcJn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VkW6ZL7qXxwNhkvcHuItlVFEJ6x4iqMhi9XOdQ7R8fIylDHCZZZ3tr0QPta8lRSXl06w/B6ZHlt/8nBQ5WMG+4puPYwCKKcHIceKZGWfZGKtrUue9f8COFqIpetMB0uBwPrUbKQVceOO41CCgHaHWXBMXaRPz1Yy27tH9hSNMDstYs8guc+G+AZqJCzJhZoRbKwIlvoNwAWw/juV97K9iTLpeGLMnH8CZy2UwrLwIqW+mfBLWopC00PeM/UPtcmUa4CejupuXJd0sbPmhiu/XISiLlcp7olcE64R+7h+QHaNYGyG2XA/f0yjBO4dsV75fgUn0ptlH7r+HCwTQupzkZD5djmwhh9BR5iOdEGJ47m8LBMQYKtyjP67wmV0B8EYfnB+K+d7g060v24+4FA4QlU77vRyqg8qhxbTtLAY/ee0WR2b0to=
before_install:
- openssl aes-256-cbc -K $encrypted_3e39b73e0d5c_key -iv $encrypted_3e39b73e0d5c_iv
-in google_key.json.enc -out google_key.json -d
- openssl aes-256-cbc -K $encrypted_a0b6ad2b92c2_key -iv $encrypted_a0b6ad2b92c2_iv
-in .env.enc -out .env -d
-in private.tar.enc -out private.tar -d
- tar xvf private.tar
- |
if [ ! -d "$HOME/terraform/bin" ]; then
rm -rf "$HOME/terraform"
Expand Down
Binary file removed google_key.json.enc
Binary file not shown.
Binary file added private.tar.enc
Binary file not shown.
20 changes: 16 additions & 4 deletions src/controllers/graphql/aws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,34 @@ import { ApolloServer } from "apollo-server-lambda";
import { typeDefs } from "@/models/graphql/types";
import { resolvers } from "@/controllers/graphql/resolvers";
import jwt from "jsonwebtoken";
import { schemaDirectives } from "@/models/graphql/directives";

export const awsServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ APIGatewayProxyEvent }) => {
if (!APIGatewayProxyEvent.headers.authorization) return { user: undefined };
context: ({ event }) => {
console.log("event", event);
console.log("event.header", event.headers);
if (!event.headers.Authorization) {
console.log("no header");
return { user: undefined };
}

const token = APIGatewayProxyEvent.headers.authorization.substr(7);
const token = event.headers.Authorization.substr(7);
console.log("token", token);

try {
const user = jwt.verify(token, Buffer.from(process.env.JWT_SECRET, "base64"));
const user = jwt.verify(token, process.env.JWT_SECRET);
console.log("auth success");

return { user };
} catch {
console.log("auth fail");

return { user: undefined };
}
},
schemaDirectives,
playground: false,
introspection: false,
});
Expand Down
19 changes: 14 additions & 5 deletions src/controllers/graphql/gcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,32 @@ import { ApolloServer, gql } from "apollo-server-cloud-functions";
import { typeDefs } from "@/models/graphql/types";
import { resolvers } from "@/controllers/graphql/resolvers";
import jwt from "jsonwebtoken";
import { schemaDirectives } from "@/models/graphql/directives";

export const gcpServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
if (!req.headers.authorization) return { user: undefined };
if (!req.headers.authorization) {
console.log("no header");
return { user: undefined };
}

const token = req.headers.authorization.substr(7);

console.log("token", token);
try {
const user = jwt.verify(token, Buffer.from(process.env.JWT_SECRET, "base64"));
const user = jwt.verify(token, process.env.JWT_SECRET);
console.log("yes verify");

return { user };
} catch {
console.log("no verify");

return { user: undefined };
}
},
playground: false,
introspection: false,
schemaDirectives,
// playground: false,
// introspection: false,
});
gcpServer.setGraphQLPath("/");
18 changes: 14 additions & 4 deletions src/controllers/graphql/mutation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import { sendmail } from "../mail/ses";

export default {
sendEmail: async (_, { to, title, body }, { user }) => {
if (!user) return "no auth";
const result = await sendmail(to, title, body);
return result;
sendEmail: async (_, { to, title, body }, { user, ...etc }) => {
console.log("user", user);
console.log("etc", etc);
if (!user) {
console.log("true");
return { status: 403, message: "no auth" };
}
console.log("false");
try {
const result = await sendmail(to, title, body);
return { status: 200, message: result.messageId };
} catch (err) {
return { status: 500, message: err };
}
},
};
16 changes: 16 additions & 0 deletions src/models/graphql/directives/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { SchemaDirectiveVisitor } from "apollo-server-cloud-functions";
import { defaultFieldResolver } from "graphql";

export class IsAuthDirective extends SchemaDirectiveVisitor {
public visitFieldDefinition(field) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function(...args) {
const [, {}, { user }] = args;
if (!user) {
throw new Error("User not authenticated");
}
// args[2].authUser = authUser;
return resolve.apply(this, args);
};
}
}
5 changes: 5 additions & 0 deletions src/models/graphql/directives/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { IsAuthDirective } from "./auth";

export const schemaDirectives = {
isAuth: IsAuthDirective,
};
2 changes: 2 additions & 0 deletions src/models/graphql/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { gql } from "apollo-server-lambda";

export const typeDefs = gql`
directive @isAuth on FIELD_DEFINITION
type Response {
status: Int!
message: String!
Expand Down
166 changes: 155 additions & 11 deletions terraform.tf
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# TF-UPGRADE-TODO: Block type was not recognized, so this block and its contents were not automatically upgraded.
#init

#module
terraform {
backend "remote" {
hostname = "app.terraform.io"
Expand Down Expand Up @@ -52,7 +52,22 @@ resource "google_cloudfunctions_function" "function" {
provider "aws" {
region = "us-east-1"
}
#data
data "aws_vpc" "jclip" {
default = true
}

data "aws_subnet_ids" "default" {
vpc_id = data.aws_vpc.jclip.id


}

data "aws_security_groups" "default" {
tags = {
service = "jclip"
}
}
#source upload

resource "aws_s3_bucket" "jclip_bucket" {
Expand Down Expand Up @@ -106,18 +121,85 @@ resource "aws_lambda_permission" "apigw_lambda" {
}

resource "aws_lambda_function" "lambda" {
depends_on = [aws_s3_bucket_object.jclip_bucket_object]

depends_on = [aws_iam_role_policy_attachment.lambda_logs, aws_cloudwatch_log_group.example, aws_s3_bucket_object.jclip_bucket_object]
role = aws_iam_role.iam_for_lambda.arn
s3_bucket = "jclip"
s3_key = "${data.archive_file.jclip_zip.output_md5}.zip"
function_name = "jclip_api"
role = aws_iam_role.role.arn
handler = "index.awsHandler"
runtime = "nodejs8.10"
vpc_config {
subnet_ids = data.aws_subnet_ids.default.ids
security_group_ids = data.aws_security_groups.default.ids
}
# The filebase64sha256() function is available in Terraform 0.11.12 and later
# For Terraform 0.11.11 and earlier, use the base64sha256() function and the file() function:
# source_code_hash = "${base64sha256(file("lambda.zip"))}"
}

#Aplication LoadBalancer

resource "aws_lb" "default" {
name = "jcliplb"
internal = false
load_balancer_type = "application"
security_groups = data.aws_security_groups.default.ids
subnets = data.aws_subnet_ids.default.ids

enable_deletion_protection = false
}

resource "aws_lb_target_group" "default" {
name = "jcliplb-TG"
target_type = "lambda"
}

resource "aws_lb_listener" "default" {
load_balancer_arn = aws_lb.default.arn
port = "80"
protocol = "HTTP"

default_action {
type = "forward"
target_group_arn = aws_lb_target_group.default.arn
}
}

resource "aws_lb_listener_rule" "lambda" {
listener_arn = aws_lb_listener.default.arn
priority = 100

action {
type = "forward"
target_group_arn = aws_lb_target_group.default.arn
}
condition{
path_pattern {
values = ["/**"]
}
}

}

resource "aws_lambda_permission" "with_lb" {
statement_id = "AllowExecutionFromLB"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.lambda.function_name
principal = "elasticloadbalancing.amazonaws.com"
source_arn = aws_lb_target_group.default.arn
}

resource "aws_lb_target_group_attachment" "default" {
target_group_arn = aws_lb_target_group.default.arn
target_id = aws_lambda_function.lambda.arn
}

# return base url
output "base_url" {
value = aws_lb.default.dns_name
}
#API gateway
resource "aws_api_gateway_stage" "default" {
stage_name = "default"
rest_api_id = aws_api_gateway_rest_api.api.id
Expand All @@ -137,11 +219,75 @@ resource "aws_api_gateway_method_response" "response_200" {
status_code = "200"
}

# IAM
resource "aws_iam_role" "role" {
name = "myrole"
# This is to optionally manage the CloudWatch Log Group for the Lambda Function.
# If skipping this resource configuration, also add "logs:CreateLogGroup" to the IAM policy below.
resource "aws_cloudwatch_log_group" "example" {
name = "/aws/lambda/jclip_api"
retention_in_days = 14
}

# See also the following AWS managed policy: AWSLambdaBasicExecutionRole
resource "aws_iam_policy" "lambda_logging" {
name = "lambda_logging"
path = "/"
description = "IAM policy for logging from a lambda"

policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"],
"Resource": "arn:aws:logs:*:*:*",
"Effect": "Allow"
}
]
}
EOF
}

resource "aws_iam_policy" "network" {
name = "lambda_network"
path = "/"
description = "IAM policy for logging from a lambda"

assume_role_policy = <<POLICY
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeNetworkInterfaces",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeInstances",
"ec2:AttachNetworkInterface"
],
"Resource": "*"
}
]
}
EOF
}

resource "aws_iam_role_policy_attachment" "lambda_logs" {
role = aws_iam_role.iam_for_lambda.name
policy_arn = aws_iam_policy.network.arn
}

resource "aws_iam_role_policy_attachment" "lambda_network" {
role = aws_iam_role.iam_for_lambda.name
policy_arn = aws_iam_policy.lambda_logging.arn
}

resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"

assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
Expand All @@ -155,7 +301,5 @@ resource "aws_iam_role" "role" {
}
]
}
POLICY

}

EOF
}

0 comments on commit 7624dc7

Please sign in to comment.