def demo_app_auth(): demo = app.Chalice('app-name') @demo.authorizer() def auth_with_explicit_policy(auth_request): token = auth_request.token if token == 'allow': return { 'context': {}, 'principalId': 'user', 'policyDocument': { 'Version': '2012-10-17', 'Statement': [{ 'Action': 'execute-api:Invoke', 'Effect': 'Allow', 'Resource': [ "arn:aws:execute-api:mars-west-1:123456789012:" "ymy8tbxw7b/api/GET/explicit" ] }] } } else: return { 'context': {}, 'principalId': '', 'policyDocument': { 'Version': '2012-10-17', 'Statement': [{ 'Action': 'execute-api:Invoke', 'Effect': 'Deny', 'Resource': [ "arn:aws:execute-api:mars-west-1:123456789012:" "ymy8tbxw7b/api/GET/explicit" ] }] } } @demo.authorizer() def demo_authorizer_returns_none(auth_request): return None @demo.authorizer() def demo_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['/index'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') @demo.authorizer() def resource_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['/resource/foobar'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') @demo.authorizer() def all_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['*'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') @demo.authorizer() def landing_page_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['/'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') iam_authorizer = IAMAuthorizer() cognito_authorizer = CognitoUserPoolAuthorizer('app-name', []) @demo.route('/', authorizer=landing_page_auth) def landing_view(): return {} @demo.route('/index', authorizer=demo_auth) def index_view(): return {} @demo.route('/secret', authorizer=demo_auth) def secret_view(): return {} @demo.route('/resource/{name}', authorizer=resource_auth) def single_value(name): return {'resource': name} @demo.route('/secret/{value}', authorizer=all_auth) def secret_view_value(value): return {'secret': value} @demo.route('/explicit', authorizer=auth_with_explicit_policy) def explicit(): return {} @demo.route('/iam', authorizer=iam_authorizer) def iam_route(): return {} @demo.route('/cognito', authorizer=cognito_authorizer) def cognito_route(): return {} @demo.route('/none', authorizer=demo_authorizer_returns_none) def none_auth(): return {} return demo
from chalice import BadRequestError, Chalice, NotFoundError from chalicelib import database, utils from chalice import CognitoUserPoolAuthorizer import os import logging authorizer = CognitoUserPoolAuthorizer( 'ChaliceUserPool', provider_arns=[os.environ['USER_POOL_ARN']]) app = Chalice(app_name='videos-api') app.log.setLevel(logging.INFO) # TABLE_NAME = 'videos' # すべてのvideoを取得する @app.route('/videos', methods=['GET'], cors=True, authorizer=authorizer) def get_all_videos(): return database.get_all_videos() # 指定されたIDのvideoを取得する @app.route('/videos/{video_id}', methods=['GET'], cors=True, authorizer=authorizer) def get_video(video_id): app.log.debug("success") video = database.get_video(video_id) if video: return video else:
from chalice import Chalice, CognitoUserPoolAuthorizer, CORSConfig, Rate import chalicelib.controllers.docs_controller as doc_controller import chalicelib.controllers.audit_controller as audit_controller import chalicelib.controllers.s3_controller as s3_controller import chalicelib.services.user_service as user_service import chalicelib.config as config import logging ############## Chalice CONFIG ########## app = Chalice(app_name='mybooks') app.debug = True app.log.setLevel(logging.DEBUG) authorizer = CognitoUserPoolAuthorizer( config.COGNITO_USER_POOL_NAME, provider_arns=[config.COGNITO_USER_POOL_ARN]) CORS_CONFIG = CORSConfig(allow_origin="*", allow_headers=[ 'Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key', 'X-Amz-Security-Token' ], max_age=600, expose_headers=[ 'Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key', 'X-Amz-Security-Token' ], allow_credentials=True) ########################################
from chalice import Chalice, NotFoundError, Response, CORSConfig, AuthResponse, AuthRoute, CognitoUserPoolAuthorizer from basicauth import decode app = Chalice(app_name='todo-app') app.debug = True cognito_authorizer = CognitoUserPoolAuthorizer( 'qa_test', header='Authorization', provider_arns=[ 'arn:aws:cognito-idp:eu-west-1:299416431288:userpool/eu-west-1_YTEukGzRd' ]) cors_config = CORSConfig(allow_origin="*") def current_user(): auth_context = app.current_request.context.get('authorizer', {}) return auth_context.get('claims', {}).get('cognito:username') @app.route('/todo', authorizer=cognito_authorizer, cors=cors_config) def todos(): print("Current user is {}".format(current_user())) user = current_user().capitalize() test = "hallo" return {'test': test, 'user': user}
import logging import os from chalice import Chalice, CognitoUserPoolAuthorizer from chalicelib.src.main.activities import activities from chalicelib.src.main.expenses import expenses from chalicelib.src.main.users import users app = Chalice(app_name='xpenses') app.debug = True logger = logging.getLogger() logger.setLevel(logging.INFO) authorizer = CognitoUserPoolAuthorizer( 'xpensesPool', provider_arns=[os.environ.get("COGNITO_USER_POOL_ARN")]) # Users @app.route('/users/{username}', methods=['GET'], authorizer=authorizer) def get_user_by_id(username): return users.get_user_by_name(username) # Expenses @app.route('/expenses', methods=['POST'], authorizer=authorizer) def create_expenses(): return expenses.create(app.current_request.json_body) @app.route('/expenses/{expense_id}', methods=['GET'], authorizer=authorizer)
return AuthResponse(routes=[], principal_id='user') # setup authorisers for view methods iam_authorizer = IAMAuthorizer() set_authorizer = os.getenv(params.AUTHORIZER_PARAM) if set_authorizer == params.AUTHORIZER_IAM: use_authorizer = iam_authorizer elif set_authorizer == params.AUTHORIZER_COGNITO: # check that we have the required configuration to setup Cognito auth cog_pool_name = os.getenv(params.COGNITO_POOL_NAME) cog_provider_arns = os.getenv(params.COGNITO_PROVIDER_ARNS) if cog_pool_name is not None and cog_provider_arns is not None: cognito_authorizer = CognitoUserPoolAuthorizer(cog_pool_name, provider_arns=cog_provider_arns.split(',')) else: print("Unable to configure Cognito Authorizer without %s and %s configuration items" % params.COGNITO_POOL_NAME, params.COGNITO_PROVIDER_ARNS) elif set_authorizer == params.AUTHORIZER_CUSTOM: use_authorizer = None else: use_authorizer = None if use_authorizer is None: print("Stage deployed without Authorizer") else: print("Using Authorizer %s" % set_authorizer.__name__) # setup class logger log = utils.setup_logging()
# S3 resources dataplane_s3_bucket = os.environ['DATAPLANE_BUCKET'] # Cognito resources # From cloudformation stack cognito_user_pool_arn = os.environ['USER_POOL_ARN'] # TODO: Should we add a variable for the upload bucket? base_s3_uri = 'private/assets/' s3_client = boto3.client('s3') s3_resource = boto3.resource('s3') authorizer = CognitoUserPoolAuthorizer('MieUserPool', header='Authorization', provider_arns=[cognito_user_pool_arn]) class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def check_required_input(key, dict, objectname): if key not in dict: raise BadRequestError("Key '%s' is required in '%s' input" % (key, objectname))
from chalice import Chalice, CORSConfig, CognitoUserPoolAuthorizer import boto3 from chalicelib import util app = Chalice(app_name='quickdraw-lambdas') cors_config = CORSConfig(allow_origin='https://quickdraw.ixora.io', ) authorizer = CognitoUserPoolAuthorizer( 'GoogleQuickdraw', header='Authorization', provider_arns=[('arn:aws:cognito-idp:us-east-1:386512717651:' 'userpool/us-east-1_7OESlcisr')]) dynamodb = boto3.resource( 'dynamodb', region_name='us-east-1', ) table = dynamodb.Table('GoogleQuickdraw') @app.route('/drawings/{country}/{category}/{recognized}', cors=cors_config) def get_drawings(country, category, recognized): """return all of the drawings for a country and category the country and category codes join together to form a compound partition key. the database is designed to return all of the sketches in a single partition, making this process more efficient. some filtering can be done for recognized or unrecognized drawings.
from chalice import Chalice, NotFoundError, Response, CORSConfig, AuthResponse, AuthRoute, CognitoUserPoolAuthorizer import boto3 app = Chalice(app_name='clientserving') app.debug = True cors_config = CORSConfig(allow_origin="*") cognito_client = boto3.client('cognito-idp') ledger = boto3.resource('dynamodb').Table('ledger') demo = boto3.resource('dynamodb').Table('demo-documents') cognito_authorizer = CognitoUserPoolAuthorizer( 'streamUserPool', header='Authorization', provider_arns=[ 'arn:aws:cognito-idp:eu-west-1:228802818628:userpool/eu-west-1_Tw7W5AmAS' ]) userresponse = cognito_client.list_users(UserPoolId='eu-west-1_Tw7W5AmAS', Limit=50) @app.route('/application_context', authorizer=cognito_authorizer, cors=cors_config) def context_provider(): ## Add tenant isolation auth_context = app.current_request.context.get('authorizer', {}) customer = auth_context.get('claims', {}).get('custom:customer') user = auth_context.get('claims', {}).get('cognito:username')
import backend.aws.dynamodb as dynamodb from backend.api.config_get_by_tag import config_get_by_tag from backend.api.config_upsert import config_upsert from backend.api.subscriptions.add_subscription import add_subscription from backend.api.subscriptions.get_subscriptions import get_subscriptions from backend.api.subscriptions.delete_subscription import delete_subscription from backend.util.environment import get_name client = boto3.client('lambda') app = Chalice(app_name='data-marketplace-backend') app.debug = True authorizer = CognitoUserPoolAuthorizer( 'MyPool', provider_arns=[ 'arn:aws:cognito-idp:us-west-2:280996535957:userpool/us-west-2_CoIS7kwaJ' ]) def get_body( myapp): #TODO: check what happens if I use "app" instead of a param return myapp.current_request.json_body def get_param(myapp, param): if myapp.current_request.query_params == None: return None else: return myapp.current_request.query_params.get(param)
from chalice import CognitoUserPoolAuthorizer, IAMAuthorizer from ...settings import settings cognito_authorizer = CognitoUserPoolAuthorizer( settings.AWS_COGNITO_USER_POOL_NAME, header='Authorization', provider_arns=[settings.AWS_COGNITO_USER_POOL_ARN]) iam_authorizer = IAMAuthorizer()
db.echo = False app = Chalice(app_name='helloworld') app.debug = True CITIES_TO_STATE = { "seattle":"wa", "portland":"OR" } OBJECTS = {} authorizer = CognitoUserPoolAuthorizer( 'ArgusAviation', header='Authorization', provider_arns=['arn:aws:cognito-idp:us-east-2:415718553612:userpool/us-east-2_H8klEUvPX']) @app.route('/', cors=True) def index(): result = db.engine.execute(get_next_line_number_query) result2 = [row['description'] for row in result] for row in result: print("description:", row['description']) return result2 @app.route('/cities/{city}', cors=True, authorizer=authorizer) def state_of_city(city): return {'state':CITIES_TO_STATE[city]}
app = Chalice(app_name=aws_resources['APP']) collection_name = aws_resources['MONGO_COLLECTION'] client = pymongo.MongoClient(aws_resources['MONGO_CONNSTRING']) db = client[aws_resources['MONGO_DATABASE']] s3 = boto3.resource('s3') settings = { 'site-bucket': aws_resources['SITE_BUCKET'], 'data-folder': aws_resources['DATA_FOLDER'] } authorizer = CognitoUserPoolAuthorizer(aws_resources['USERPOOL'], header='Authorization', provider_arns=aws_resources['ARN']) def parseS3Time(dt): return str(dt).split('+')[0] def modelExists(_modelname): return any(x['model'] == _modelname for x in getModelNames( settings['site-bucket'], settings['data-folder'] + "/")) def getModelNames(_bucket, _prefix): s3_objects_resp = s3.meta.client.list_objects(Bucket=_bucket, Prefix=_prefix)
from chalice import Chalice, NotFoundError, Response, CORSConfig, AuthResponse, AuthRoute, CognitoUserPoolAuthorizer from basicauth import decode import os from chalicelib.tododb import TodoDB app = Chalice(app_name='todo-app') app.debug = True cognito_authorizer = CognitoUserPoolAuthorizer( 'TodoUserPool', header='Authorization', provider_arns=[os.getenv("USER_POOL_ARN")]) cors_config = CORSConfig(allow_origin="*") TODO_DB = TodoDB() @app.authorizer() def basic_auth(auth_request): username, password = decode(auth_request.token) if username == password: context = {'stripe_user_id': '1234', 'is_admin': True} return AuthResponse(routes=['/*'], principal_id=username, context=context) return AuthResponse(routes=[], principal_id=None) @app.route('/', authorizer=basic_auth)
from chalicelib.transformed_redshift_job import * from chalicelib.run_raw_job import createrawjob try: import ConfigParser as parser except: import configparser as parser # In Python 3, ConfigParser has been renamed to configparser for PEP 8 compliance. properties = {} app = Chalice(app_name='AwsDatalakeServerless') app.debug = True resource = boto3.resource('s3') randomnumber = random.randint(1, 10000000000) strnumber = str(randomnumber) authorizer = CognitoUserPoolAuthorizer( 'CognitoAuthorizer', provider_arns=[os.environ['cognitoPoolArn']]) @app.route("/prop", authorizer=authorizer, methods=['GET'], cors=True) def read_Properties(): config = parser.ConfigParser() bucket_name = os.environ['destination_bucket_name'] file_name = os.environ['properties_file_name'] #bucket_name="aws-datalake-47lining" #file_name="appconfig.ini" print("bucket_name:::::", bucket_name) print("file_name::::", file_name) try: resource.Bucket(bucket_name).download_file(file_name, '/tmp/appconfig.ini') except Exception as e:
from chalicelib.scraper import BUCKET, WorkerMsg, handler from chalicelib.utils import Dict2Obj STAGE = os.environ.get('CHALICE_STAGE', 'dev') PAGE_QUE_URL = os.environ.get('pageQueUrl') sqs = boto3.client('sqs') app = Chalice(app_name='kendra-scrap') app.debug = True if STAGE == 'dev': CognitoUserPool = 'arn:aws:cognito-idp:us-west-2:213888382832:userpool/us-west-2_CtB4uaG0r' else: CognitoUserPool = "arn:aws:cognito-idp:us-west-2:213888382832:userpool/us-west-2_pdulBxv2r" authorizer = CognitoUserPoolAuthorizer('KendraBtnUserPool', provider_arns=[CognitoUserPool], header='Authorization') class GraphQLView: schema = schema root_value = None context = None pretty = False graphiql = True graphiql_version = None graphiql_template = None graphiql_html_title = None middleware = None batch = False jinja_env = None
import boto3 from chalice import Chalice from chalice import CognitoUserPoolAuthorizer from chalice.app import BadRequestError from chalicelib import db from chalicelib.validates import Validates _DB = None app = Chalice(app_name='serverless-todo-backend') app.debug = True authorizer = CognitoUserPoolAuthorizer( 'ToDoAppUserPool', provider_arns=[os.environ.get('USER_POOL_ARN')] ) def get_authorized_username(current_request): """トークンから cognito:username を取得 Return: str: cognito:username を返します None: cognito:username がない場合 None を返します """ try: username = current_request.context['authorizer']['claims']["cognito:username"] except KeyError: username = None return username
from chalice import Chalice, CognitoUserPoolAuthorizer from elasticsearch import Elasticsearch, RequestsHttpConnection from elasticsearch_dsl import Search from aws_requests_auth.aws_auth import AWSRequestsAuth from geomet import wkt import boto3 import os es_endpoint = os.environ['ES_ENDPOINT'] user_pool_arn = os.environ['USER_POOL_ARN'] app = Chalice(app_name='ImageCatalogAPI') authorizer = CognitoUserPoolAuthorizer('TestPool', provider_arns=[user_pool_arn]) session = boto3.session.Session() credentials = session.get_credentials().get_frozen_credentials() awsauth = AWSRequestsAuth(aws_access_key=credentials.access_key, aws_secret_access_key=credentials.secret_key, aws_token=credentials.token, aws_host=es_endpoint, aws_region=session.region_name, aws_service='es') client = Elasticsearch(hosts=[{ 'host': es_endpoint, 'port': 443 }], http_auth=awsauth, use_ssl=True, verify_certs=True,
from chalice import Chalice, CognitoUserPoolAuthorizer, CORSConfig, NotFoundError from os import getenv from fdbk.utils import create_db_connection from fdbk.server import ServerHandlers app = Chalice(app_name='fdbk-lambda') authorizer = CognitoUserPoolAuthorizer('FdbkPool', provider_arns=[getenv('USER_POOL_ARN')]) cors_config = CORSConfig( allow_origin=getenv('CLIENT_URL'), allow_credentials=True, ) db_connection = create_db_connection('fdbk_dynamodb_plugin', []) handlers = ServerHandlers(db_connection) @app.route('/overview', authorizer=authorizer, cors=cors_config, methods=['GET']) def overview(): data, code = handlers.get_overview( query_args=app.current_request.query_params) if code == 404: raise NotFoundError(data.get('error')) return data
from chalice import Chalice, CognitoUserPoolAuthorizer, BadRequestError, NotFoundError from wfapi.error import WFLoginError from wfapi import Workflowy import boto3 from decouple import config import email # Chalice application config app = Chalice(app_name='personalstats') app.debug = config('DEBUG', default=False, cast=bool) # Authorizer for most endpoints authorizer = CognitoUserPoolAuthorizer( config('COGNITO_USER_POOL_NAME'), provider_arns=[config("COGNITO_USER_POOL_ARN")]) # Cognito client for getting users from the backend cognito_client = boto3.client('cognito-idp') dynamo_db = boto3.client('dynamodb', region_name='us-west-1') s3_client = boto3.client('s3') # Utilty function for rendering the nodes from Workflowy (should be made memory save (with an iterator?)) def render_nested_json(root, indent=0): node = { "name": root.name, "uuid": root.projectid, "last_modified": str(root.last_modified) } if root.children: node['children'] = [] indent += 1
import os import json import util import s3_handler import ddb_handler from chalice import Chalice, BadRequestError, NotFoundError from chalice import CognitoUserPoolAuthorizer app = Chalice(app_name='source-of-truth-api') app.debug = True logging.basicConfig() logging.getLogger().setLevel(logging.INFO) authorizer = CognitoUserPoolAuthorizer( 'SourceOfTruthUserPool', provider_arns=[os.environ['COGNITO_USER_POOL']]) @app.route('/upload', methods=['POST'], content_types=['application/json'], authorizer=authorizer, cors=True) def upload_s3_file(): request_body = json.loads(app.current_request.raw_body) return ddb_handler.handle_upload_file_req(request_body, app.current_request.context) @app.route('/download', methods=['POST'], content_types=['application/json'], authorizer=authorizer, cors=True) def download_s3_file(): request_body = json.loads(app.current_request.raw_body) return ddb_handler.handle_download_file_req(request_body, app.current_request.context) @app.route('/', methods=['GET'], authorizer=authorizer, cors=True) def get_s3_ddb_data(): queryParams = app.current_request.query_params return s3_handler.get_s3_ddb_data(bucket_name=queryParams.get('bucketName'), next_token=queryParams.get('nextIdToken'), keyPrefix=queryParams.get('prefix'), req_cxt=app.current_request.context)
from urllib.parse import urlparse, parse_qs import json app = Chalice(app_name='aws-chalice-example') app.debug = True cors_config = CORSConfig( allow_origin = '*', allow_headers = ['X-Special-Header'], max_age = 600, expose_headers = ['X-Special-Header'], allow_credentials = True ) authorizer = CognitoUserPoolAuthorizer( 'Users', header = 'Authorization', provider_arns = ['arn:aws:cognito-idp:eu-west-1:009127507915:userpool/eu-west-1_yFwbkCuMn'] ) @app.route('/test', methods=['GET'], cors=cors_config, authorizer=authorizer) def get_all(): request = app.current_request.to_dict() if request.get('query_params'): return request_handler.handle_get_company(request['query_params']['Company']) else: return request_handler.handle_get_all() @app.route('/test', methods=['POST'], content_types=['application/json'], cors=cors_config, authorizer=authorizer) def post_item(): data = app.current_request.json_body print("log: app.current_request.json_body = ")
import boto3 import re import uuid import datetime import json import hashlib from .script_generator import ScriptGenerator from .upload import S3Uploader app = Chalice(app_name="open_tag_manager") app.debug = bool(os.environ.get('DEBUG')) app.experimental_feature_flags.update(['BLUEPRINTS']) authorizer = CognitoUserPoolAuthorizer( 'UserPool', provider_arns=[str(os.environ.get('OTM_COGNITO_USER_POOL_ARN'))]) cognito_idp_client = boto3.client('cognito-idp') s3 = boto3.resource('s3') s3_client = boto3.client('s3') batch_client = boto3.client('batch') athena_client = boto3.client('athena') def get_cognito_user_pool_id(): return re.search(r"/(.+)$", os.environ.get('OTM_COGNITO_USER_POOL_ARN'))[1]
# app.log.setLevel(logging.DEBUG) # Enable this if every response has to be logged in Cloudwatch. # app.debug = True # Enable this only for developement. # Configuration to enable CORS for API gateway. # Note : This will automatically add OPTIONS request handler in API gateway. cors_config = CORSConfig(allow_origin='*', allow_headers=[ 'Content-Type', 'Authorization', 'X-Amz-Date', 'X-Api-Key', 'X-Amz-Security-Token' ], max_age=600, allow_credentials=True) authorizer = CognitoUserPoolAuthorizer( 'MyPool', header='Authorization', provider_arns=[ 'arn:aws:cognito-idp:ap-south-1:190911038733:userpool/ap-south-1_yIyVbDlc9' ]) @app.route('/channels', methods=['GET'], authorizer=authorizer, cors=cors_config) def getChannels(): user_id = utils.get_user_id(app) channels = dynamodb_utils.get_channels(user_id) response = [] for channel in channels: response.append( utils.dict_underscore_to_camelcase(