示例#1
0
    def test_can_have_same_custom_cors_configurations(self, sample_app):
        custom_cors = CORSConfig(allow_origin='https://foo.example.com',
                                 allow_headers=['X-Special-Header'],
                                 max_age=600,
                                 expose_headers=['X-Special-Header'],
                                 allow_credentials=True)

        @sample_app.route('/cors', methods=['GET'], cors=custom_cors)
        def cors():
            pass

        same_custom_cors = CORSConfig(allow_origin='https://foo.example.com',
                                      allow_headers=['X-Special-Header'],
                                      max_age=600,
                                      expose_headers=['X-Special-Header'],
                                      allow_credentials=True)

        @sample_app.route('/cors', methods=['PUT'], cors=same_custom_cors)
        def same_cors():
            pass

        try:
            validate_routes(sample_app.routes)
        except ValueError:
            pytest.fail('A ValueError was unexpectedly thrown. Applications '
                        'may have multiple view functions that share the same '
                        'route and CORS configuration.')
示例#2
0
    def test_cant_have_differing_cors_configurations(self, sample_app):
        custom_cors = CORSConfig(allow_origin='https://foo.example.com',
                                 allow_headers=['X-Special-Header'],
                                 max_age=600,
                                 expose_headers=['X-Special-Header'],
                                 allow_credentials=True)

        @sample_app.route('/cors', methods=['GET'], cors=True)
        def cors():
            pass

        @sample_app.route('/cors', methods=['PUT'], cors=custom_cors)
        def different_cors():
            pass

        with pytest.raises(ValueError):
            validate_routes(sample_app.routes)
示例#3
0
from chalice import Chalice, CORSConfig

from chalicelib.trie import TrieBase
from chalicelib.wordbase import WordBase

app = Chalice(app_name='wordbase-helper-backend')
cors = CORSConfig()
app.debug = True
dictionary = TrieBase()


@app.route('/', methods=['POST'], cors=cors)
def index():
    request = app.current_request.json_body

    wb = WordBase(request['cellsString'], request['markedMap'], dictionary)

    return wb.get_answers()
示例#4
0
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}
示例#5
0
    def test_can_add_preflight_cors(self, sample_app, swagger_gen):
        @sample_app.route('/cors',
                          methods=['GET', 'POST'],
                          cors=CORSConfig(
                              allow_origin='http://foo.com',
                              allow_headers=['X-ZZ-Top', 'X-Special-Header'],
                              expose_headers=['X-Exposed', 'X-Special'],
                              max_age=600,
                              allow_credentials=True))
        def cors_request():
            pass

        doc = swagger_gen.generate_swagger(sample_app)
        view_config = doc['paths']['/cors']
        # We should add an OPTIONS preflight request automatically.
        assert 'options' in view_config, (
            'Preflight OPTIONS method not added to CORS view')
        options = view_config['options']
        expected_response_params = {
            'method.response.header.Access-Control-Allow-Methods':
            mock.ANY,
            'method.response.header.Access-Control-Allow-Headers':
            ("'Authorization,Content-Type,X-Amz-Date,X-Amz-Security-Token,"
             "X-Api-Key,X-Special-Header,X-ZZ-Top'"),
            'method.response.header.Access-Control-Allow-Origin':
            ("'http://foo.com'"),
            'method.response.header.Access-Control-Expose-Headers':
            ("'X-Exposed,X-Special'"),
            'method.response.header.Access-Control-Max-Age': ("'600'"),
            'method.response.header.Access-Control-Allow-Credentials':
            ("'true'"),
        }
        assert options == {
            'consumes': ['application/json'],
            'produces': ['application/json'],
            'responses': {
                '200': {
                    'description': '200 response',
                    'schema': {
                        '$ref': '#/definitions/Empty'
                    },
                    'headers': {
                        'Access-Control-Allow-Origin': {
                            'type': 'string'
                        },
                        'Access-Control-Allow-Methods': {
                            'type': 'string'
                        },
                        'Access-Control-Allow-Headers': {
                            'type': 'string'
                        },
                        'Access-Control-Expose-Headers': {
                            'type': 'string'
                        },
                        'Access-Control-Max-Age': {
                            'type': 'string'
                        },
                        'Access-Control-Allow-Credentials': {
                            'type': 'string'
                        },
                    }
                }
            },
            'x-amazon-apigateway-integration': {
                'responses': {
                    'default': {
                        'statusCode': '200',
                        'responseParameters': expected_response_params,
                    }
                },
                'requestTemplates': {
                    'application/json': '{"statusCode": 200}'
                },
                'passthroughBehavior': 'when_no_match',
                'type': 'mock',
            },
        }

        allow_methods = self.get_access_control_methods(view_config)
        # Typically the header will follow the form of:
        # "METHOD,METHOD,...OPTIONS"
        # The individual assertions is needed because there is no guarantee
        # on the order of these methods in the string because the order is
        # derived from iterating through a dictionary, which is not ordered
        # in python 2.7. So instead assert the correct methods are present in
        # the string.
        assert 'GET' in allow_methods
        assert 'POST' in allow_methods
        assert 'OPTIONS' in allow_methods
示例#6
0
es_indexer = None

# module level settings used as flags for lazy initialisers in functions
search_flow_verified = False

# load the cors config
cors_config = None
cors = None
try:
    with open("chalicelib/cors.json", "r") as f:
        cors_config = json.load(f)

    if cors_config.get("AllowAllCORS") == "True":
        cors = True
    else:
        cors = CORSConfig(**cors_config.get("custom"))
except FileNotFoundError:
    pass


# using a functools wrapper here as normal python decorators aren't compatible with the call signature of chalice
def chalice_function(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        headers = {'Content-Type': 'text/json'}
        try:
            log.debug(f"Function: {f.__name__}")
            log.debug(f"ARGS: {args}")
            log.debug(f"KWARGS: {kwargs}")
            log.debug(f"Query Params: {app.current_request.query_params}")
            log.debug(f"Raw Body: {app.current_request.raw_body}")
示例#7
0
import boto3, json
from chalice import Chalice, CORSConfig

app = Chalice(app_name='remote-control')
cors_config = CORSConfig(allow_origin='*')

ec2 = boto3.client('ec2')
data = ec2.describe_instances()

def get_ec2_instances():    
    return [insta['Instances'][0]['InstanceId'] for insta in data['Reservations']]

def start_instances(instance_id):       
    response = ec2.start_instances( InstanceIds=[instance_id], DryRun=False)
    return response 

def stop_instances(instance_id):    
    response = ec2.stop_instances(
    InstanceIds=[instance_id],
    Force=True)
    return response 

@app.route('/{instance_id}', cors=True)
def toggle_instance_status(instance_id):
    instanceMapping = {insta['Instances'][0]['InstanceId']:insta['Instances'][0]['State']['Name'] \
         for insta in data['Reservations']}

    if instanceMapping[instance_id] == 'running':
        stop_instances(instance_id)
    else:
        print('need to start instance')
示例#8
0
from chalice import Chalice, BadRequestError, CORSConfig, Response
from robot import run
import boto3
from botocore.exceptions import ClientError
import io
import json
import uuid
from os import environ
import re

app = Chalice(app_name='rf-runner')
cors_config = CORSConfig(allow_origin=environ.get('FRONTEND_URL'),
                         allow_credentials=True)

FRONTEND_URL = environ.get('FRONTEND_URL')
RF_REPORTS_BUCKET = environ.get('REPORT_BUCKET')

ALLOWED_LIBRARIES = [
    'Builtin', 'String', 'Dialogs', 'DateTime', 'Collections', 'XML',
    'RequestsLibrary'
]

REPORTS = ['output.xml', 'log.html', 'report.html']


@app.middleware('http')
def validation_middleware(event, get_response):
    libraries = re.findall("Library\s{2,}(.*)", event.raw_body.decode("utf-8"))
    for library in libraries:
        if library not in ALLOWED_LIBRARIES:
            response = {
示例#9
0
def test_can_add_preflight_cors(sample_app, swagger_gen):
    @sample_app.route('/cors',
                      methods=['GET', 'POST'],
                      cors=CORSConfig(
                          allow_origin='http://foo.com',
                          allow_headers=['X-ZZ-Top', 'X-Special-Header'],
                          expose_headers=['X-Exposed', 'X-Special'],
                          max_age=600,
                          allow_credentials=True))
    def cors_request():
        pass

    doc = swagger_gen.generate_swagger(sample_app)
    view_config = doc['paths']['/cors']
    # We should add an OPTIONS preflight request automatically.
    assert 'options' in view_config, (
        'Preflight OPTIONS method not added to CORS view')
    options = view_config['options']
    expected_response_params = {
        'method.response.header.Access-Control-Allow-Methods':
        ("'GET,POST,OPTIONS'"),
        'method.response.header.Access-Control-Allow-Headers':
        ("'Authorization,Content-Type,X-Amz-Date,X-Amz-Security-Token,"
         "X-Api-Key,X-Special-Header,X-ZZ-Top'"),
        'method.response.header.Access-Control-Allow-Origin':
        ("'http://foo.com'"),
        'method.response.header.Access-Control-Expose-Headers':
        ("'X-Exposed,X-Special'"),
        'method.response.header.Access-Control-Max-Age': ("'600'"),
        'method.response.header.Access-Control-Allow-Credentials': ("'true'"),
    }
    assert options == {
        'consumes': ['application/json'],
        'produces': ['application/json'],
        'responses': {
            '200': {
                'description': '200 response',
                'schema': {
                    '$ref': '#/definitions/Empty'
                },
                'headers': {
                    'Access-Control-Allow-Origin': {
                        'type': 'string'
                    },
                    'Access-Control-Allow-Methods': {
                        'type': 'string'
                    },
                    'Access-Control-Allow-Headers': {
                        'type': 'string'
                    },
                    'Access-Control-Expose-Headers': {
                        'type': 'string'
                    },
                    'Access-Control-Max-Age': {
                        'type': 'string'
                    },
                    'Access-Control-Allow-Credentials': {
                        'type': 'string'
                    },
                }
            }
        },
        'x-amazon-apigateway-integration': {
            'responses': {
                'default': {
                    'statusCode': '200',
                    'responseParameters': expected_response_params,
                }
            },
            'requestTemplates': {
                'application/json': '{"statusCode": 200}'
            },
            'passthroughBehavior': 'when_no_match',
            'type': 'mock',
        },
    }
示例#10
0
from pprint import pprint
from chalice import Chalice
from chalice import NotFoundError
from chalice import CORSConfig
from chalicelib.db import db_conn, db_query
from chalicelib.aws import s3, boto3
from chalicelib.models.doc import Doc
from chalicelib.models.issuer import Issuer

app = Chalice(app_name='sinfiltrar-input')
app.log.setLevel(logging.INFO)
app.debug = True

cors_config = CORSConfig(allow_origin=os.environ["ALLOW_ORIGIN"],
                         allow_headers=['X-Special-Header'],
                         max_age=600,
                         expose_headers=['X-Special-Header'],
                         allow_credentials=True)


@app.route('/latest', cors=cors_config)
def latest():
    query = "SELECT * FROM docs ORDER BY issued_at DESC LIMIT 20"
    result = db_query(query)

    response = [{
        "title": doc['title'],
        "slug": doc['slug'],
        "short_text": doc['short_text'],
        "content": doc['body_plain'],
        "date": doc['issued_at'].__str__(),
示例#11
0
from chalice import CustomAuthorizer, CORSConfig
import logging
from boto3 import client
import os
log = logging.getLogger("audit-feedback")

invokeLambda = client("lambda", region_name=f"{os.environ['CURRENT_REGION']}")

cors_config = CORSConfig(allow_origin='*',
                         max_age=600,
                         expose_headers=['X-Special-Header'],
                         allow_credentials=False)

authorizer = CustomAuthorizer(
    'MyCustomAuth',
    header='Authorization',
    authorizer_uri=
    (f"arn:aws:apigateway:{os.environ['CURRENT_REGION']}:lambda:path/2015-03-31"
     "/functions/arn:aws:lambda:us-east-2:886064876783:function:sessions-app-dev-jwt_auth/invocations"
     ))


def get_authorized_session_id(current_request):
    log.info("current request session_id", current_request.context)
    return current_request.context['authorizer']['sessionId']


def get_authorized_email(current_request):
    log.info("current request email", current_request.context)
    return current_request.context['authorizer']['principalId']
示例#12
0
from chalice import BadRequestError
from chalice import NotFoundError
from chalice import ChaliceViewError

app = Chalice(app_name='mygame_app')
app.debug = True

print('Loading function')

dynamodb_client = boto3.client('dynamodb')

cors_config = CORSConfig(
    #    allow_origin='http://localhost:63342',
    #    allow_origin='http://mygame.jimhough.com.s3-website-us-east-1.amazonaws.com',
    allow_origin='http://mygame.jimhough.com',
    allow_headers=['Access-Control-Allow-Origin', 'X-Special-Header', 'User'],
    max_age=600,
    expose_headers=['X-Special-Header'],
    allow_credentials=True)

# For Authentication:
# from http://chalice.readthedocs.io/en/latest/api.html#authorization
#authorizer = CognitoUserPoolAuthorizer(
#    'MyPool', header='Authorization',
#    provider_arns=['arn:aws:cognito:...:userpool/name'])

#authorizer = CognitoUserPoolAuthorizer(
#    name='MyPool',
#    provider_arns=['arn:aws:cognito-idp:us-east-1:1234567890:userpool/us-east-1_SDqT99999'],
#    header='Authorization'
#    )
示例#13
0
    CORSConfig,
    AuthResponse,
    AuthRoute,
)
from chalice import NotFoundError, BadRequestError

# from operationsresearch.prepaid import PrepaidSolver
from ortools.linear_solver import pywraplp
import os

app = Chalice(app_name="solver")

# Configure CORS Routes
# cors_allow_origin = os.getenv("CORS_ALLOW_ORIGIN", "*")
cors_allow_origin = "*"
cors_config = CORSConfig(allow_origin=cors_allow_origin)

# Configure debug output
environment = os.getenv("CHALICE_ENVIRONMENT", "development")
if environment == "development":
    app.debug = True


class PrepaidSolver:
    def __init__(self, tiers: dict, target: float):
        self.solver = pywraplp.Solver(
            "TierSolver", pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING
        )
        self.tiers = tiers
        self.target = target
示例#14
0
from chalice import Chalice, CORSConfig, Response

from chalicelib.aws_sdk import BotoWrapper
from chalicelib.youtube import youtube_cards
from chalicelib.instagram import gallery

cors_config = CORSConfig(
    allow_origin='https://fingerstyle.jongwony.com',
    allow_headers=['Cross-Origin-Resource-Policy'],
    max_age=3600,
)
app = Chalice(app_name='fingerstyle')
aws_api = BotoWrapper()
instagram_cache_key = 'fingerstyle/instagram/gallery.json'
youtube_cache_key = 'fingerstyle/youtube/playlist.json'


@app.route('/', cors=cors_config)
def index():
    return {}


@app.route('/instagram', cors=cors_config)
def instagram():
    return Response(
        body=aws_api.json_deserialize(instagram_cache_key),
        headers={'Cross-Origin-Resource-Policy': 'cross-origin'},
    )


@app.route('/youtube', cors=cors_config)
示例#15
0
import json
from chalice import Chalice, CORSConfig
from datetime import datetime, timedelta, date, time
from chalicelib import data_funcs

app = Chalice(app_name='data-dashboard')

cors_config = CORSConfig(allow_origin='https://dashboard.transitmatters.org',
                         max_age=3600)


def destructure_date(date):
    date_split = date.split('-')
    return {
        'year': int(date_split[0]),
        'month': int(date_split[1]),
        'day': int(date_split[2])
    }


@app.route("/headways/{user_date}", cors=cors_config)
def headways_route(user_date):
    station = app.current_request.query_params.get('station')
    parsed_date = destructure_date(user_date)
    return data_funcs.headways(
        date(year=parsed_date['year'],
             month=parsed_date['month'],
             day=parsed_date['day']), {"stop": station})


@app.route("/dwells/{user_date}", cors=cors_config)
示例#16
0
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.
示例#17
0
import os

from chalice import Chalice, CORSConfig

from chalicelib import auth, core, task, time_entry, user

app = Chalice(app_name='chalicarian')
app.api.cors = CORSConfig(
    allow_origin=os.environ.get('TASKAFARIAN_ALLOWED_ORIGIN'))

core.init_app(app)
auth.init_app(app)
user.init_app(app)
task.init_app(app)
time_entry.init_app(app)
示例#18
0
import json
import os
import subprocess
from chalice import Chalice, Cron, CORSConfig, ConflictError, Response
from datetime import date, timedelta
from chalicelib import data_funcs, aggregation, s3_alerts, secrets

app = Chalice(app_name="data-dashboard")

# will run on localhost if TM_FRONTEND_HOST is not set in env
TM_FRONTEND_HOST = os.environ.get("TM_FRONTEND_HOST", "localhost")

cors_config = CORSConfig(allow_origin=f"https://{TM_FRONTEND_HOST}",
                         max_age=3600)


# Every day at 10am UTC: store alerts from the past
# It's called yesterday for now but it's really two days ago!!
@app.schedule(Cron(0, 10, '*', '*', '?', '*'))
def store_two_days_ago_alerts(event):
    # Only do this on the main site
    if TM_FRONTEND_HOST == "dashboard.transitmatters.org":
        two_days_ago = date.today() - timedelta(days=2)
        s3_alerts.store_alerts(two_days_ago)


def parse_user_date(user_date):
    date_split = user_date.split("-")
    [year, month, day] = [int(x) for x in date_split[0:3]]
    return date(year=year, month=month, day=day)
示例#19
0
def lambda_login(event):
    body = event.json_body
    login_res = login(body["username"], body["password"])
    # Clear out the password from the dict, to avoid accidentally logging it
    body["password"] = ""
    if IS_LOCAL:
        cookie = f"grapl_jwt={login_res}; HttpOnly"
    else:
        cookie = f"grapl_jwt={login_res}; Domain=.amazonaws.com; secure; HttpOnly; SameSite=None"

    if login_res:
        return cookie


cors_config = CORSConfig(
    allow_origin=ORIGIN_OVERRIDE or ORIGIN,
    allow_credentials="true",
)


def requires_auth(path):
    if not IS_LOCAL:
        path = "/{proxy+}" + path

    def route_wrapper(route_fn):
        @app.route(path, methods=["OPTIONS", "POST"])
        def inner_route():
            if app.current_request.method == "OPTIONS":
                return respond(None, {})

            if not check_jwt(app.current_request.headers):
                LOGGER.warn("not logged in")
示例#20
0
from chalice import Chalice, CORSConfig
import boto3
import uuid
from chalicelib import utils
from secrets import token_urlsafe
import time
import bcrypt
from dynamodb_json import json_util
from urllib.parse import urlparse, parse_qs

app = Chalice(app_name='file-hosting-apis')

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
)


S3 = boto3.client('s3')
DYNAMODB = boto3.client('dynamodb')

BUCKET_NAME = 'file-hosting-app'
TABLE_NAME = 'file-hosting-app'


@app.route('/signed-url-upload/{key}', methods=['GET'], cors=cors_config)
def upload_url(key):
    key = token_urlsafe(32) + key
示例#21
0
import smtplib
from chalice import Chalice, CORSConfig
from chalicelib.tools import send_email, format_profile, format_slider_results, \
    format_feedback, format_contact
from chalicelib.utils import TEST_MESSAGE

app = Chalice(app_name='lambda_survey')
smtp_server = smtplib.SMTP()
cors_config = CORSConfig(
    allow_origin="*",
    allow_headers=["X-Special-Header", "X-Requested-With"],
    max_age=600,
    expose_headers=["X-Special-Header"],
    allow_credentials=True)


@app.route('/', cors=cors_config, methods=['GET'])
def index():
    return {'message': 'Survey notification service online'}


@app.route('/notify', cors=cors_config, methods=['POST'])
def post_survey():
    body = app.current_request.json_body
    print(body)
    message = format_profile(body['profile']) + format_slider_results(body['results']) \
              + format_feedback(body['feedback']) + format_contact(body['contact'])
    return send_email(smtp_server, message)


@app.route('/test', cors=cors_config, methods=['POST'])
示例#22
0
from chalice import Chalice, CORSConfig

import re
from datetime import datetime

from requests_toolbelt.multipart import decoder
from fitparse import FitFile

from pprint import pprint

app = Chalice(app_name='fit-convert')
app.debug = True
app.api.binary_types = ['multipart/form-data']

cors_config = CORSConfig(allow_origin='http://fit-converter.com', )


def semicircles_to_degrees(semicircle):
    # 2147483648 = 2^31
    return float(semicircle) * (180.0 / 2147483648.0)


def string_to_datetime(txt):
    # 2018-03-01 02:43:52
    return datetime.strptime(txt, '%Y-%m-%d %H:%M:%S')


def datetime_to_string(dt):
    # 2018-03-01T05:04:39.000Z
    return dt.isoformat() + ".000Z"
示例#23
0
def sample_app():
    demo = app.Chalice('demo-app')
    demo.debug = True

    @demo.route('/index', methods=['GET'])
    def index():
        return {'hello': 'world'}

    @demo.route('/names/{name}', methods=['GET'])
    def name(name):
        return {'provided-name': name}

    @demo.route('/put', methods=['PUT'])
    def put():
        return {'body': demo.current_request.json_body}

    @demo.route('/cors', methods=['GET', 'PUT'], cors=True)
    def cors():
        return {'cors': True}

    @demo.route('/custom_cors', methods=['GET', 'PUT'], cors=CORSConfig(
        allow_origin='https://foo.bar',
        allow_headers=['Header-A', 'Header-B'],
        expose_headers=['Header-A', 'Header-B'],
        max_age=600,
        allow_credentials=True
    ))
    def custom_cors():
        return {'cors': True}

    @demo.route('/options', methods=['OPTIONS'])
    def options():
        return {'options': True}

    @demo.route('/delete', methods=['DELETE'])
    def delete():
        return {'delete': True}

    @demo.route('/patch', methods=['PATCH'])
    def patch():
        return {'patch': True}

    @demo.route('/badrequest')
    def badrequest():
        raise BadRequestError('bad-request')

    @demo.route('/decimals')
    def decimals():
        return decimal.Decimal('100')

    @demo.route('/query-string')
    def query_string():
        return demo.current_request.query_params

    @demo.route('/custom-response')
    def custom_response():
        return Response(body='text',
                        status_code=200,
                        headers={'Content-Type': 'text/plain'})

    @demo.route('/binary', methods=['POST'],
                content_types=['application/octet-stream'])
    def binary_round_trip():
        return Response(body=demo.current_request.raw_body,
                        status_code=200,
                        headers={'Content-Type': 'application/octet-stream'})

    return demo
示例#24
0
def invalidate_cache(object):
    client = boto3.client('cloudfront')
    response = client.create_invalidation(
        DistributionId=os.environ['PROFILE_DISTRIBUTION_NAME'],
        InvalidationBatch={
            'Paths': {
                'Quantity': 2,
                'Items': [f'/{object}', f'/{object}.html'],
            },
            'CallerReference': str(time()).replace(".", "")
        })


app = Chalice(app_name='form-service')
app.api.cors = CORSConfig(allow_origin="https://uandi.cc")


def write_to_cdn(pid, file):
    client = boto3.client('s3')
    client.put_object(Body=file,
                      Bucket=os.environ['PROFILE_BUCKET_NAME'],
                      Key=f"{pid}.html",
                      ContentType='text/html')
    client.put_object(Body=file,
                      Bucket=os.environ['PROFILE_BUCKET_NAME'],
                      Key=f"{pid}",
                      ContentType='text/html')
    invalidate_cache(pid)

示例#25
0
from chalice import Chalice
from datetime import datetime
import smtplib
from chalice import CORSConfig

cors_config = CORSConfig(
    allow_origin='https://foo.example.com',
    allow_headers=['X-Special-Header'],
    max_age=600,
    expose_headers=['X-Special-Header'],
    allow_credentials=True
)

# APP_EMAIL = '*****@*****.**'
# DEFUALT_RESPONSE='Exception sent'

app = Chalice(app_name='teamsite-chalice')


@app.route('/')
def index():
    return {'hello': 'world'}

@app.route('/test/{form}', methods=['POST'], cors=cors_config)
def test(form):
    return {'name: ':form.name}


@app.route('/sendex', methods=['POST'])
def sendexception(agent='Bob', supervisor="Tyler"):
    gmail_user = '******'
示例#26
0
############## 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)

########################################


@app.route('/docs', methods=['GET'], authorizer=authorizer, cors=CORS_CONFIG)
def show_documents():
    """
    Shows all available documents for the current authorized users

    :return: an array of document objects or an ampty array if not documents are available
示例#27
0
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
示例#28
0
@app.route('/json-only', content_types=['application/json'])
def json_only():
    return {'success': True}


@app.route('/cors', methods=['GET', 'POST', 'PUT'], cors=True)
def supports_cors():
    # It doesn't really matter what we return here because
    # we'll be checking the response headers to verify CORS support.
    return {'cors': True}


@app.route('/custom_cors', methods=['GET', 'POST', 'PUT'], cors=CORSConfig(
    allow_origin='https://foo.example.com',
    allow_headers=['X-Special-Header'],
    max_age=600,
    expose_headers=['X-Special-Header'],
    allow_credentials=True))
def supports_custom_cors():
    return {'cors': True}


@app.route('/todict', methods=['GET'])
def todict():
    return app.current_request.to_dict()


@app.route('/multifile')
def multifile():
    from chalicelib import MESSAGE
    return {"message": MESSAGE}
示例#29
0
import uuid
import boto3
from boto3.dynamodb.conditions import Key, Attr
from chalice import Chalice
from chalice import CORSConfig
from chalice import Response

app = Chalice(app_name='assignment_newsbytes')

cors_config = CORSConfig(allow_origin='*',
                         allow_headers=['X-Special-Header', 'Authorization'],
                         max_age=600,
                         expose_headers=['X-Special-Header'],
                         allow_credentials=True)

SECRET_KEY = "4f58135e-2af4-4c48-8d70-9fdbba9b7f26"  # Generated using uuid

dynamodb = boto3.resource('dynamodb')
hashedUrlTable = dynamodb.Table('hashedUrlTable')


def make_response(status, data_type, msg, data, code):
    response = {
        'status': status,
        'data_type': data_type,
        'message': msg,
        "data": data,
        'code': code
    }
    return response
示例#30
0
文件: app.py 项目: cbonoz/contract-sv

def get_wallet_key_header():
    wallet_key = app.current_request.headers.get('wallet_key', None)
    if not wallet_key:
        raise BadRequestError('No wallet_key provided')
    return wallet_key


app = Chalice(app_name='contract-sv')

ORIGIN_URL = os.environ.get('ORIGIN_URL', 'http://*****:*****@app.route('/', cors=cors_config)
def index():
    return {'hello': 'world', 'origin': ORIGIN_URL}


@app.route('/documents', cors=cors_config)
def get_docs():
    wallet_key = get_wallet_key_header()
    return doc_repo.fetch_documents(wallet_key)


@app.route('/document/history/{document_name}', cors=cors_config)
def get_doc_history(document_name):