Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding-variables #83

Closed
wants to merge 1 commit into from
Closed
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
14 changes: 6 additions & 8 deletions aws-auth-patch.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
# This is a sample aws-auth-patch.yml file.
# Actual aws-auth-patch.yml will be created at /System/Volumes/Data/private/tmp/aws-auth-patch.yml path.

apiVersion: v1
data:
mapRoles: |
- groups:
- system:bootstrappers
- system:nodes
rolearn: arn:aws:iam::519002666132:role/eksctl-simple-jwt-api-nodegroup-n-NodeInstanceRole-1DBHED9TMYRZZ
rolearn: arn:aws:iam::391733008457:role/eksctl-simple-jwt-api-nodegroup-ng-NodeInstanceRole-3NrAWtBKUgyV
username: system:node:{{EC2PrivateDNSName}}
- groups:
- system:masters
rolearn: arn:aws:iam::519002666132:role/UdacityFlaskDeployCBKubectlRole
rolearn: arn:aws:iam::391733008457:role/UdacityFlaskDeployCBKubectlRole
username: build
kind: ConfigMap
metadata:
creationTimestamp: "2022-05-11T11:16:26Z"
creationTimestamp: "2024-09-03T06:38:52Z"
name: aws-auth
namespace: kube-system
resourceVersion: "1631"
uid: 86402a4e-a9ff-4721-8c24-f0c4258f7440
resourceVersion: "1372"
uid: f63a7f5b-f7ff-4271-be54-aedd93ce93fd
21 changes: 8 additions & 13 deletions ci-cd-codepipeline.cfn.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ AWSTemplateFormatVersion: 2010-09-09

Description: EKSWSV1


Parameters:

EksClusterName:
Type: String
Description: The name of the EKS cluster created
Expand All @@ -17,7 +15,7 @@ Parameters:
GitSourceRepo:
Type: String
Description: GitHub source repository - must contain a Dockerfile and buildspec.yml in the base
Default: cd0157-Server-Deployment-and-Containerization
Default: Server-Deployment-and-Containerization
MinLength: 1
MaxLength: 100
ConstraintDescription: You must enter a GitHub repository name
Expand All @@ -40,7 +38,7 @@ Parameters:

GitHubUser:
Type: String
Default: SudKul
Default: aparna67
Description: GitHub username or organization
MinLength: 3
MaxLength: 100
Expand All @@ -62,7 +60,6 @@ Parameters:
MaxLength: 100
ConstraintDescription: You must enter a kubectl IAM role


Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
Expand Down Expand Up @@ -101,9 +98,7 @@ Metadata:
EksClusterName:
default: EKS cluster name


Resources:

EcrDockerRepository:
Type: AWS::ECR::Repository
DeletionPolicy: Retain
Expand All @@ -130,7 +125,7 @@ Resources:
'LogicalResourceId': event['LogicalResourceId'],
'Data': {"Message": "Resource creation successful!"},
}

http = urllib3.PoolManager()
client = boto3.client('iam')
try:
Expand Down Expand Up @@ -260,25 +255,25 @@ Resources:
Effect: Allow
Action:
- sts:AssumeRole
- Resource: '*'
- Resource: "*"
Effect: Allow
Action:
- eks:Describe*
- Resource: '*'
- Resource: "*"
Effect: Allow
Action:
- ssm:GetParameters
- Resource: '*'
- Resource: "*"
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- Resource: '*'
- Resource: "*"
Effect: Allow
Action:
- ecr:GetAuthorizationToken
- Resource: '*'
- Resource: "*"
Effect: Allow
Action:
- ec2:CreateNetworkInterface
Expand Down
74 changes: 40 additions & 34 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,19 @@
from flask import Flask, jsonify, request, abort


JWT_SECRET = os.environ.get('JWT_SECRET', 'abc123abc1234')
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')
JWT_SECRET = os.environ.get("JWT_SECRET", "abc123abc1234")
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")


def _logger():
'''
"""
Setup logger format, level, and handler.

RETURNS: log object
'''
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
"""
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)

log = logging.getLogger(__name__)
log.setLevel(LOG_LEVEL)
Expand All @@ -35,81 +37,85 @@ def _logger():


LOG = _logger()
LOG.debug("Starting with log level: %s" % LOG_LEVEL )
LOG.debug("Starting with log level: %s" % LOG_LEVEL)
APP = Flask(__name__)


def require_jwt(function):
"""
Decorator to check valid jwt is present.
"""

@functools.wraps(function)
def decorated_function(*args, **kws):
if not 'Authorization' in request.headers:
if not "Authorization" in request.headers:
abort(401)
data = request.headers['Authorization']
token = str.replace(str(data), 'Bearer ', '')
data = request.headers["Authorization"]
token = str.replace(str(data), "Bearer ", "")
try:
jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
except: # pylint: disable=bare-except
jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
except: # pylint: disable=bare-except
abort(401)

return function(*args, **kws)

return decorated_function


@APP.route('/', methods=['POST', 'GET'])
@APP.route("/", methods=["POST", "GET"])
def health():
return jsonify("Healthy")
# return jsonify("Healthy")/
return jsonify({"status": "Healthy"})


@APP.route('/auth', methods=['POST'])
@APP.route("/auth", methods=["POST"])
def auth():
"""
Create JWT token based on email.
"""
request_data = request.get_json()
email = request_data.get('email')
password = request_data.get('password')
email = request_data.get("email")
password = request_data.get("password")
if not email:
LOG.error("No email provided")
return jsonify({"message": "Missing parameter: email"}, 400)
if not password:
LOG.error("No password provided")
return jsonify({"message": "Missing parameter: password"}, 400)
body = {'email': email, 'password': password}
body = {"email": email, "password": password}

user_data = body

return jsonify(token=_get_jwt(user_data).decode('utf-8'))
return jsonify(token=_get_jwt(user_data).decode("utf-8"))


@APP.route('/contents', methods=['GET'])
@APP.route("/contents", methods=["GET"])
def decode_jwt():
"""
Check user token and return non-secret data
"""
if not 'Authorization' in request.headers:
if not "Authorization" in request.headers:
abort(401)
data = request.headers['Authorization']
token = str.replace(str(data), 'Bearer ', '')
data = request.headers["Authorization"]
token = str.replace(str(data), "Bearer ", "")
try:
data = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
except: # pylint: disable=bare-except
data = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
except: # pylint: disable=bare-except
abort(401)


response = {'email': data['email'],
'exp': data['exp'],
'nbf': data['nbf'] }
response = {"email": data["email"], "exp": data["exp"], "nbf": data["nbf"]}
return jsonify(**response)


def _get_jwt(user_data):
exp_time = datetime.datetime.utcnow() + datetime.timedelta(weeks=2)
payload = {'exp': exp_time,
'nbf': datetime.datetime.utcnow(),
'email': user_data['email']}
return jwt.encode(payload, JWT_SECRET, algorithm='HS256')
payload = {
"exp": exp_time,
"nbf": datetime.datetime.utcnow(),
"email": user_data["email"],
}
return jwt.encode(payload, JWT_SECRET, algorithm="HS256")


if __name__ == '__main__':
APP.run(host='127.0.0.1', port=8080, debug=True)
if __name__ == "__main__":
APP.run(host="127.0.0.1", port=8080, debug=True)
20 changes: 10 additions & 10 deletions trust.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::519002666132:root"
},
"Action": "sts:AssumeRole"
}
]
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::391733008457:root"
},
"Action": "sts:AssumeRole"
}
]
}
Loading