Skip to content

Commit

Permalink
Update with more organized api code
Browse files Browse the repository at this point in the history
  • Loading branch information
gugzkumar committed Dec 7, 2019
1 parent a522017 commit 8eef943
Show file tree
Hide file tree
Showing 14 changed files with 197 additions and 199 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ api/dependencies/*
api/notebooks
api/cached-dependencies
archived-services
__dependencies__

# CLIENT UI Ignores
client-ui/angular-output/*
Expand Down
2 changes: 2 additions & 0 deletions api/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pyjwt==1.7.1
cryptography==2.8
125 changes: 0 additions & 125 deletions api/sheet/_code_/app.py

This file was deleted.

10 changes: 10 additions & 0 deletions api/src/__core__/authentication_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from __dependencies__ import jwt

def apply(event):
headers = event['headers']
algorithm = 'RS256'
token = "eyJraWQiOiJVVTRHTmZ4WXJTOXlCQXFGdnpJVUNTQ2YxZWcwcUpRaFwvSHg2dGZiUW00UT0iLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiWm5iYnRqdFdSNDVZbm1yWVZ3UkFUUSIsInN1YiI6IjQ4ZTZiNDdlLTllYjUtNDI3OC04NTUzLTFkZGNhYmM2OTQ2ZiIsImF1ZCI6IjEzcjZrOWE5NHZvNDBwcWE4M2NkbWhvbWptIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImV2ZW50X2lkIjoiZGJjN2UzY2ItNWZiYS00ZGM1LWEyYjEtOGE5M2VhZDE2OGQyIiwidG9rZW5fdXNlIjoiaWQiLCJhdXRoX3RpbWUiOjE1NzU2ODA2OTksImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy1lYXN0LTEuYW1hem9uYXdzLmNvbVwvdXMtZWFzdC0xX01abG4zeXpLbiIsImNvZ25pdG86dXNlcm5hbWUiOiJHdWd6IiwiZXhwIjoxNTc1Njg0Mjk5LCJpYXQiOjE1NzU2ODA2OTksImVtYWlsIjoiZ2FnYW50dW51Z3VudGxhQHNhaW1haWwuY29tIn0.KJ2_S7siRtnl4RItwwBrJbVZtcR37a25jMhK1MzagSdAG5E6eWy3uhNgggiKBWlDIw3KYVhFnaAPqsGJPyU2m6i9Q6Cpeb3bXKpVAgW0KQUaQd8PX2AYxzR46kwahqay0gfXH2fywODK_mWOYNjr2njW0WINiG74bVNYxNG0mZ4_UREK39UEDlApLtWWHcFghYytY5b0Wl2nLv7UQjAcbVHaafZ1EyzcpbqdB_nEMsCHRXiGQmKmXGHa6LNAtEWCbDYcY1UAoMyC3RhFwdT5gy_gx55G5VTNolwVAl34azd4DqZelaTcR_C4lWZwXipWlJzXA4eBWCEuX5rSZRHsQw"
jwt.decode(token, 'secret', algorithms=[algorithm])
if ('Authorization' in headers) and (headers['Authorization']):
jwt_token = headers['Authorization']
print(jwt_token)
5 changes: 5 additions & 0 deletions api/src/__core__/json_parsing_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import json

def apply(event):
if ('body' in event) and (event['body']):
event['body'] = json.loads(event['body'])
20 changes: 20 additions & 0 deletions api/src/__core__/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
AVAILABLE_FILE_TYPES = [
'abap', 'abc', 'actionscript', 'ada', 'apache_conf', 'apex', 'applescript', 'asciidoc', 'asl',
'assembly_x86', 'autohotkey', 'batchfile', 'bro', 'c9search', 'c_cpp', 'cirru', 'clojure', 'cobol',
'coffee', 'coldfusion', 'csharp', 'csound_document', 'csound_orchestra', 'csound_score', 'csp', 'css',
'curly', 'd', 'dart', 'diff', 'django', 'dockerfile', 'dot', 'drools', 'edifact', 'eiffel', 'ejs',
'elixir', 'elm', 'erlang', 'forth', 'fortran', 'fsharp', 'fsl', 'ftl', 'gcode', 'gherkin', 'gitignore',
'glsl', 'gobstones', 'golang', 'graphqlschema', 'groovy', 'haml', 'handlebars', 'haskell',
'haskell_cabal', 'haxe', 'hjson', 'html', 'html_elixir', 'html_ruby', 'ini', 'io', 'jack', 'jade', 'java',
'javascript', 'json', 'jsoniq', 'jsp', 'jssm', 'jsx', 'julia', 'kotlin', 'latex', 'less', 'liquid',
'lisp', 'livescript', 'logiql', 'logtalk', 'lsl', 'lua', 'luapage', 'lucene', 'makefile', 'markdown',
'mask', 'matlab', 'maze', 'mel', 'mixal', 'mushcode', 'mysql', 'nix', 'nsis', 'objectivec', 'ocaml',
'pascal', 'perl', 'perl6', 'pgsql', 'php', 'php_laravel_blade', 'pig', 'plain_text', 'powershell',
'praat', 'prolog', 'properties', 'protobuf', 'puppet', 'python', 'r', 'razor', 'rdoc', 'red', 'redshift',
'rhtml', 'rst', 'ruby', 'rust', 'sass', 'scad', 'scala', 'scheme', 'scss', 'sh', 'sjs', 'slim', 'smarty',
'snippets', 'soy_template', 'space', 'sparql', 'sql', 'sqlserver', 'stylus', 'svg', 'swift', 'tcl',
'terraform', 'tex', 'text', 'textile', 'toml', 'tsx', 'turtle', 'twig', 'typescript', 'vala', 'vbscript',
'velocity', 'verilog', 'vhdl', 'visualforce', 'wollok', 'xml', 'xquery', 'yaml'
]
SHEET_DATA_S3_BUCKET='scratch-cheetsheet-storage'
ADMIN_USER='default'
22 changes: 22 additions & 0 deletions api/src/__core__/utilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import json
import datetime

def get_a_blank_new_sheet():
return {
"defaultFileType": None,
"dateCreated": datetime.datetime.now().timestamp(),
"dateUpdated": datetime.datetime.now().timestamp(),
"leftIndexCards": [
],
"rightIndexCards": [
]
}

def get_error_response(message, statusCode=400):
return {
'statusCode': statusCode,
'body': json.dumps({
'message': message
}),
'headers': {'Access-Control-Allow-Origin': "*"}
}
1 change: 1 addition & 0 deletions api/src/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Leave This File Empty
35 changes: 35 additions & 0 deletions api/src/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import json
import importlib
import sys
from __core__ import authentication_middleware, json_parsing_middleware
# sys.path.append("./__dependencies__")


def main(event, context):
# Extract htttp information from the endpoint
api_resource_path = event["resource"]
api_http_method = event["httpMethod"].lower()

# Apply middleware
authentication_middleware.apply(event)
json_parsing_middleware.apply(event)

# Load the correct python module for the api endpoint
api_resource_path = event["resource"]
spec = importlib.util.spec_from_file_location("module.name", f'./{api_resource_path}/__init__.py')
endpoint_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(endpoint_module)

# Check if the method belongs to the module
if api_http_method not in dir(endpoint_module):
return {
"statusCode": 405,
"body": json.dumps({
"message": "Method Not Allowed"
})
}

# Return desired result of api endpoint
response = getattr(endpoint_module, api_http_method)(event, context)
response["headers"] = {'Access-Control-Allow-Origin': "*"}
return response
73 changes: 73 additions & 0 deletions api/src/sheet/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""
API methods for /sheet
"""
import boto3
import json
import datetime
from boto3 import client
s3_client = client('s3')
from __core__.settings import AVAILABLE_FILE_TYPES, SHEET_DATA_S3_BUCKET, ADMIN_USER
from __core__.utilities import get_a_blank_new_sheet, get_error_response

user = ADMIN_USER
s3_get_sheet_names_response = s3_client.list_objects(
Bucket = SHEET_DATA_S3_BUCKET,
Prefix = f'{user}/',
Delimiter = '/'
)['CommonPrefixes']
all_current_sheet_names = [obj['Prefix'][(len(user)+1):-1] for obj in s3_get_sheet_names_response]

def get(event, context):
"""
Get All Sheets
"""
return {
"statusCode": 200,
"body": json.dumps({
'result': {
'sheetNames': all_current_sheet_names
}
})
}

def post(event, context):
"""
Create A New Sheet
"""

if 'sheetName' not in event['body'] or event['body']['sheetName'] is None:
# Error if no sheet name was provided
return get_error_response('No name for sheet was provided')

if event['body']['sheetName'] in all_current_sheet_names:
# Error if sheet name exists
return get_error_response(f'Sheet with name {event["body"]["sheetName"]} already exists')

if 'defaultFileType' not in event['body'] or event['body']['sheetName'] is None:
# Error if Default File type was not provided
return get_error_response('No Default File Type was provided')

if event['body']['defaultFileType'] not in AVAILABLE_FILE_TYPES:
# Error if Default File type is not supported
return get_error_response(f'Default file type {event["body"]["defaultFileType"]} is not supported')

# Create Empty sheet in S3 bucket
new_sheet = get_a_blank_new_sheet()
new_sheet['defaultFileType'] = event['body']['defaultFileType']
s3_client.put_object(
ACL='private',
Body = (bytes(json.dumps(new_sheet).encode('UTF-8'))),
Bucket = cheetsheet_bucket_name,
Key=f'{user}/{event["body"]["sheetName"]}/sheet.json'

)

return {
"statusCode": 200,
"body": json.dumps({
'results': {
'sheetName': event["body"]["sheetName"],
'sheetData': new_sheet
}
})
}
Loading

0 comments on commit 8eef943

Please sign in to comment.