Skip to content

Commit

Permalink
loader, and move api methods
Browse files Browse the repository at this point in the history
  • Loading branch information
gugzkumar committed Apr 29, 2019
1 parent 0fe97a5 commit 5c42fef
Show file tree
Hide file tree
Showing 22 changed files with 694 additions and 69 deletions.
206 changes: 206 additions & 0 deletions api/authorizer/authorizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
"""
Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
"""
from __future__ import print_function

import re
import time
import pprint
import json


def lambda_handler(event, context):
print("Client token: " + event['authorizationToken'])
print("Method ARN: " + event['methodArn'])

principalId = "user|a1b2c3d4"
tmp = event['methodArn'].split(':')
apiGatewayArnTmp = tmp[5].split('/')
awsAccountId = tmp[4]

policy = AuthPolicy(principalId, awsAccountId)
policy.restApiId = apiGatewayArnTmp[0]
policy.region = tmp[3]
policy.stage = apiGatewayArnTmp[1]

policy.allowMethod(HttpVerb.GET, "/sheet/*")
policy.allowMethod(HttpVerb.GET, "/sheet")
policy.denyMethod(HttpVerb.POST, "/sheet")
policy.denyMethod(HttpVerb.POST, "/sheet/*")
policy.denyMethod(HttpVerb.PUT, "/sheet")
policy.denyMethod(HttpVerb.PUT, "/sheet/*")
policy.denyMethod(HttpVerb.DELETE, "/sheet")
policy.denyMethod(HttpVerb.DELETE, "/sheet/*")

# Finally, build the policy
authResponse = policy.build()

context = {
'user': sdad
}
# context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it
# context['obj'] = {'foo':'bar'} <- also invalid

authResponse['context'] = context

return authResponse

class HttpVerb:
GET = "GET"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
HEAD = "HEAD"
DELETE = "DELETE"
OPTIONS = "OPTIONS"
ALL = "*"

class AuthPolicy(object):
awsAccountId = ""
"""The AWS account id the policy will be generated for. This is used to create the method ARNs."""
principalId = ""
"""The principal used for the policy, this should be a unique identifier for the end user."""
version = "2012-10-17"
"""The policy version used for the evaluation. This should always be '2012-10-17'"""
pathRegex = "^[/.a-zA-Z0-9-\*]+$"
"""The regular expression used to validate resource paths for the policy"""

"""these are the internal lists of allowed and denied methods. These are lists
of objects and each object has 2 properties: A resource ARN and a nullable
conditions statement.
the build method processes these lists and generates the approriate
statements for the final policy"""
allowMethods = []
denyMethods = []

restApiId = "*"
"""The API Gateway API id. By default this is set to '*'"""
region = "*"
"""The region where the API is deployed. By default this is set to '*'"""
stage = "*"
"""The name of the stage used in the policy. By default this is set to '*'"""

def __init__(self, principal, awsAccountId):
self.awsAccountId = awsAccountId
self.principalId = principal
self.allowMethods = []
self.denyMethods = []

def _addMethod(self, effect, verb, resource, conditions):
"""Adds a method to the internal lists of allowed or denied methods. Each object in
the internal list contains a resource ARN and a condition statement. The condition
statement can be null."""
if verb != "*" and not hasattr(HttpVerb, verb):
raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class")
resourcePattern = re.compile(self.pathRegex)
if not resourcePattern.match(resource):
raise NameError("Invalid resource path: " + resource + ". Path should match " + self.pathRegex)

if resource[:1] == "/":
resource = resource[1:]

resourceArn = ("arn:aws:execute-api:" +
self.region + ":" +
self.awsAccountId + ":" +
self.restApiId + "/" +
self.stage + "/" +
verb + "/" +
resource)

if effect.lower() == "allow":
self.allowMethods.append({
'resourceArn' : resourceArn,
'conditions' : conditions
})
elif effect.lower() == "deny":
self.denyMethods.append({
'resourceArn' : resourceArn,
'conditions' : conditions
})

def _getEmptyStatement(self, effect):
"""Returns an empty statement object prepopulated with the correct action and the
desired effect."""
statement = {
'Action': 'execute-api:Invoke',
'Effect': effect[:1].upper() + effect[1:].lower(),
'Resource': []
}

return statement

def _getStatementForEffect(self, effect, methods):
"""This function loops over an array of objects containing a resourceArn and
conditions statement and generates the array of statements for the policy."""
statements = []

if len(methods) > 0:
statement = self._getEmptyStatement(effect)

for curMethod in methods:
if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
statement['Resource'].append(curMethod['resourceArn'])
else:
conditionalStatement = self._getEmptyStatement(effect)
conditionalStatement['Resource'].append(curMethod['resourceArn'])
conditionalStatement['Condition'] = curMethod['conditions']
statements.append(conditionalStatement)

statements.append(statement)

return statements

def allowAllMethods(self):
"""Adds a '*' allow to the policy to authorize access to all methods of an API"""
self._addMethod("Allow", HttpVerb.ALL, "*", [])

def denyAllMethods(self):
"""Adds a '*' allow to the policy to deny access to all methods of an API"""
self._addMethod("Deny", HttpVerb.ALL, "*", [])

def allowMethod(self, verb, resource):
"""Adds an API Gateway method (Http verb + Resource path) to the list of allowed
methods for the policy"""
self._addMethod("Allow", verb, resource, [])

def denyMethod(self, verb, resource):
"""Adds an API Gateway method (Http verb + Resource path) to the list of denied
methods for the policy"""
self._addMethod("Deny", verb, resource, [])

def allowMethodWithConditions(self, verb, resource, conditions):
"""Adds an API Gateway method (Http verb + Resource path) to the list of allowed
methods and includes a condition for the policy statement. More on AWS policy
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
self._addMethod("Allow", verb, resource, conditions)

def denyMethodWithConditions(self, verb, resource, conditions):
"""Adds an API Gateway method (Http verb + Resource path) to the list of denied
methods and includes a condition for the policy statement. More on AWS policy
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
self._addMethod("Deny", verb, resource, conditions)

def build(self):
"""Generates the policy document based on the internal lists of allowed and denied
conditions. This will generate a policy with two main statements for the effect:
one statement for Allow and one statement for Deny.
Methods that includes conditions will have their own statement in the policy."""
if ((self.allowMethods is None or len(self.allowMethods) == 0) and
(self.denyMethods is None or len(self.denyMethods) == 0)):
raise NameError("No statements defined for the policy")

policy = {
'principalId' : self.principalId,
'policyDocument' : {
'Version' : self.version,
'Statement' : []
}
}

policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Allow", self.allowMethods))
policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Deny", self.denyMethods))

return policy
4 changes: 3 additions & 1 deletion client-ui/angular-code/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SheetComponent } from './sheet/sheet.component';
import { AuthResolver } from './core/guardsAndResolvers/auth.resolve';
import { SheetResolver } from './core/guardsAndResolvers/sheet.resolve';

const routes: Routes = [
{
path: '',
component: SheetComponent,
resolve: {
auth: AuthResolver
auth: AuthResolver,
sheet: SheetResolver
}
}
];
Expand Down
3 changes: 3 additions & 0 deletions client-ui/angular-code/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<!-- <app-header>
</app-header> -->
<div>
<app-loader></app-loader>
</div>
<div class="app-container">
<div class="header-container">
<app-header>
Expand Down
4 changes: 4 additions & 0 deletions client-ui/angular-code/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Component, HostListener } from '@angular/core';
import { MatSnackBar } from '@angular/material';
import { AuthService } from './core/services/auth.service';
import { SheetService } from './core/services/sheet.service';

@Component({
Expand All @@ -11,6 +12,7 @@ export class AppComponent {

constructor(
private sheetService: SheetService,
private authService: AuthService,
private snackBar: MatSnackBar
) { }

Expand All @@ -20,6 +22,7 @@ export class AppComponent {
// KeyBoard Events For The App
@HostListener('document:keydown.meta.s', ['$event'])
handleKeyboardEventCommandS(event: KeyboardEvent) {
if (!this.authService.isLoggedIn) return;
if (!this.sheetService.disableSave && this.sheetService.currentSheetValue.isDirty) {
this.sheetService.saveCurrentSheet().subscribe(
() => {
Expand All @@ -42,6 +45,7 @@ export class AppComponent {

@HostListener('document:keydown.meta.e', ['$event'])
handleKeyboardEventCommandE(event: KeyboardEvent) {
if (!this.authService.isLoggedIn) return;
this.sheetService.editModeOn = !this.sheetService.editModeOn
event.preventDefault();
}
Expand Down
8 changes: 5 additions & 3 deletions client-ui/angular-code/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
Expand All @@ -11,6 +10,7 @@ import {
MatDialogModule,
MatIconModule,
MatInputModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSidenavModule,
MatSnackBarModule,
Expand All @@ -37,6 +37,7 @@ import { ConfirmationDialogComponent } from './confirmation-dialog/confirmation-
import { EditIndexCardDialogComponent } from './edit-index-card-dialog/edit-index-card-dialog.component';
import { CreateSheetDialogComponent } from './create-sheet-dialog/create-sheet-dialog.component';
import { CreateIndexCardDialogComponent } from './create-index-card-dialog/create-index-card-dialog.component';
import { LoaderComponent } from './loader/loader.component';

@NgModule({
declarations: [
Expand All @@ -49,14 +50,14 @@ import { CreateIndexCardDialogComponent } from './create-index-card-dialog/creat
ConfirmationDialogComponent,
EditIndexCardDialogComponent,
CreateSheetDialogComponent,
CreateIndexCardDialogComponent
CreateIndexCardDialogComponent,
LoaderComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
CoreModule,
HttpClientModule,
FormsModule,
// Angular Material imports
MatAutocompleteModule,
Expand All @@ -66,6 +67,7 @@ import { CreateIndexCardDialogComponent } from './create-index-card-dialog/creat
MatDialogModule,
MatIconModule,
MatInputModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSidenavModule,
MatSnackBarModule,
Expand Down
12 changes: 10 additions & 2 deletions client-ui/angular-code/src/app/core/core.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { SheetService } from './services/sheet.service';
import { SheetResolver } from './guardsAndResolvers/sheet.resolve';
import { AceEditorService } from './services/ace-editor.service';
import { AuthResolver } from './guardsAndResolvers/auth.resolve';
import { LoaderService } from './services/loader.service';
import { LoaderInterceptor } from './interceptors/loader.interceptor';
import {
IfEditModeDirective,
IfViewModeDirective,
Expand All @@ -24,12 +28,16 @@ import { EditorDirective } from './directives/editor.directive';
EditorDirective
],
imports: [
CommonModule
CommonModule,
HttpClientModule
],
providers: [
SheetService,
SheetResolver,
AceEditorService,
AuthResolver
AuthResolver,
LoaderService,
{ provide: HTTP_INTERCEPTORS, useClass: LoaderInterceptor, multi: true }
],
exports: [
IfEditModeDirective,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { SheetService } from '../services/sheet.service';
import { Observable } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
// import 'rxjs/add/operator/map';

@Injectable()
export class SheetResolver implements Resolve<any> {
constructor(private sheetService: SheetService) { }
resolve() {
const request = this.sheetService.loadSheetMenu().pipe(
mergeMap(responseBody => {
const sheets = responseBody['result']['sheetNames'];
return this.sheetService.setSelectedSheet(sheets[0]);
})
);
// mergeMap()
// const request = this.sheetService.loadSheetMenu().subscribe((responseBody) => {
// const sheets = responseBody['result']['sheetNames'];
// this.sheetService.setSelectedSheet(sheets[0]);
// }, () => {});
return request;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Injectable } from "@angular/core";
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Observable } from "rxjs";
import { finalize } from "rxjs/operators";

import { LoaderService } from '../services/loader.service';

@Injectable()
export class LoaderInterceptor implements HttpInterceptor {

constructor(public loaderService: LoaderService) {
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loaderService.show();
console.log('Called?');
return next.handle(req).pipe(
finalize(() => this.loaderService.hide())
);
}
}
Loading

0 comments on commit 5c42fef

Please sign in to comment.