Exemple #1
0
def handler(doc):
    from pathlib import Path
    from chalice import Blueprint, Response, NotFoundError

    cur_dir = Path(__file__).resolve().parent
    static_dir = cur_dir.parent.joinpath("static")

    bp = Blueprint(__name__)

    @bp.route(doc.root_uri_relative(slashes=True), methods=["GET"])
    def bp_doc_handler():
        return Response(
            body=doc.doc_html,
            status_code=200,
            headers={"Content-Type": "text/html"},
        )

    @bp.route(doc.swagger_json_uri_relative, methods=["GET"])
    def bp_config_handler():
        request = doc.app.current_request
        return doc.get_config(request.headers["host"])

    if doc.editor:

        @bp.route(doc.editor_uri_relative(slashes=True), methods=["GET"])
        def bp_editor_handler():
            return Response(
                body=doc.editor_html,
                status_code=200,
                headers={"Content-Type": "text/html"},
            )

    @bp.route(doc.static_uri_relative + r"/{path}", methods=["GET"])
    def bp_static_handler(path):
        static_file_path = static_dir.joinpath(path)
        if static_file_path.is_file():
            content_type = "application/json"
            if static_file_path.suffix in [".png", ".ico"]:
                content_type = "image/png"
            if static_file_path.suffix in [".jpg", ".jpeg"]:
                content_type = "image/jpeg"
            if static_file_path.suffix in [".css"]:
                content_type = "text/css"
            if static_file_path.suffix in [".js"]:
                content_type = "text/javascript"
            return Response(
                body=static_file_path.read_bytes(),
                status_code=200,
                headers={"Content-Type": content_type},
            )
        return NotFoundError(path)

    doc.app.register_blueprint(bp, url_prefix=doc.url_prefix)
Exemple #2
0
def test_can_invoke_handler_from_blueprint():
    bp = Blueprint('testblueprint')

    @bp.lambda_function()
    def my_foo(event, context):
        return {'event': event}

    app = Chalice('myapp')
    app.register_blueprint(bp)

    with Client(app) as client:
        response = client.lambda_.invoke('my_foo', {'hello': 'world'})
        assert response.payload == {'event': {'hello': 'world'}}
Exemple #3
0
from chalice import Blueprint
from ...libs.models.mpc.Cms.Banners import Banners
from ...libs.core.authorizer import cognito_authorizer

banners_blueprint = Blueprint(__name__)


@banners_blueprint.route('/add-banner', methods=['POST'], cors=True)
def addBanner():
    banners = Banners()
    request = banners_blueprint.current_request
    banners.insert(request.json_body)
    return {'result': 'success'}


@banners_blueprint.route('/update-banner/{banner_id}',
                         methods=['PUT'],
                         cors=True)
def updateBanner(banner_id):
    banners = Banners()
    request = banners_blueprint.current_request
    banners.update(banner_id, request.json_body)
    return {'result': 'success'}


@banners_blueprint.route('/get-banner/{banner_id}', cors=True)
def getBanner(banner_id):
    banners = Banners()
    item = banners.get(banner_id)
    return item
from chalice import Blueprint
from chalicelib.twentyone.model import Session
from chalice.app import Response
twentyone = Blueprint(__name__)


@twentyone.route('/start', methods=['POST'])
def start():
    request_body = twentyone.current_request.json_body
    if request_body:
        session = Session()
        session.start(request_body['player'], request_body['amount'])
        return Response(status_code=201,
                        headers={'Content-Type': 'application/json'},
                        body=session.state)


@twentyone.route('/hit/{sessionId}', methods=['POST', 'PUT'])
def hit(sessionId):
    request_body = twentyone.current_request.json_body
    if request_body:
        session = Session(sessionId)
        session.hit()
    return Response(status_code=201,
                    headers={'Content-Type': 'application/json'},
                    body=session.state)


@twentyone.route('/stand/{sessionId}', methods=['POST', 'PUT'])
def stand(sessionId):
    request_body = twentyone.current_request.json_body
Exemple #5
0
"""API layer for the authentication service."""
# pylint: disable=no-member
from typing import Optional

from chalice import Blueprint

from restless_services.authentication import business
from restless_services.authentication.api_schemas import (
    GetAuthenticationQuerySchema,
    PostAuthenticationBodySchema,
)
from utils.api_handler import api_handler

api = Blueprint(__name__)


@api_handler(
    api=api,
    path='/authentication',
    methods=['POST'],
    api_key_required=False,
    body_schema=PostAuthenticationBodySchema,
)
def authorize_user() -> Optional[dict]:
    """Authorizes a user with the users service using the given params.

    Returns:
        A dict containing an access token and auth results else None.
    """
    return business.authorize_user(
        email=api.handled_request.body.get('email'),
Exemple #6
0
from chalice import Blueprint
from treys import Card, Deck, Evaluator
import json

noauth = Blueprint(__name__)


@noauth.route('/treys')
def index():
    evaluator = Evaluator()
    deck = Deck()
    card = Card.new('Qh')
    board = deck.draw(5)
    player_names = ("player 1", "player 2", "player 3", "player 4", "player 5",
                    "player 6", "player 7", "player 8")
    players = {}
    output = {}
    # this is procedural programming, not functional programming :(
    for p in player_names:
        hand = deck.draw(2)
        score = evaluator.evaluate(board, hand)
        text = evaluator.class_to_string(evaluator.get_rank_class(score))
        players[p] = score
        output[p] = {'score': score, 'text': text}
    # What about a tie?
    tie = (len(players.values()) == len(set(players.values())))
    winner = min(
        players,
        key=players.get)  # always 1 result :( Don't forget to fix the TEST!
    # does the tie involve the winning hand though?
    # TODO https://stackoverflow.com/questions/17821079/how-to-check-if-two-keys-in-dictionary-hold-the-same-value
Exemple #7
0
from chalice import Blueprint, AuthResponse
from os import environ
from chalicelib.model.models import EventTable, LockTable
from chalicelib.lib import db_v2

v1_routes = Blueprint(__name__)

api_key = environ["CHALICE_API_KEY"]


@v1_routes.authorizer()
def api_key_auth(auth_request):
    """
    Custom auth function.
    The client need to provide the header Authorization with value of api_key.
    """

    if auth_request.token == api_key:
        return AuthResponse(routes=["/*"], principal_id="user")

    return AuthResponse(routes=[], principal_id="user")


@v1_routes.route("/v1/table-names", cors=True, authorizer=api_key_auth)
def table_names():
    """
    :return: table name
    """
    return {"name": [EventTable.Meta.table_name, LockTable.Meta.table_name]}

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 damian <damian@damian-desktop>
#
# Distributed under terms of the MIT license.

from chalice import Blueprint

lambda_function_3_blueprint = Blueprint(__name__)


@lambda_function_3_blueprint.lambda_function()
def lambda_function_3(event, context):
    app.log.info("trigger lambda_function_3")
Exemple #9
0
from chalice import Blueprint, Response
from chalicelib import global_db_handler, global_auth
from uuid import uuid4
import logging
from datetime import datetime

log = logging.getLogger("audit-feedback")

feedback_app = Blueprint(__name__)


@feedback_app.route('/feedbackcontroller')
def index():
    return {"feedback": "controller"}


@feedback_app.route('/api/feedback',
                    methods=['POST'],
                    cors=global_auth.cors_config,
                    authorizer=global_auth.authorizer)
def update_feedback():
    body = feedback_app.current_request.json_body
    if not body:
        return Response(body={"message": "no required details"},
                        status_code=422)
    if not body.get("rating", False) or not body.get("note", False):
        return Response(
            body={"message": "rating and note fields are mandatory"},
            status_code=422)
    log.info(feedback_app.current_request.context)
    body['uid'] = str(uuid4())
from chalicelib import global_db_handler, global_auth
from uuid import uuid4
from chalice import Blueprint, Response
import logging
import json
log = logging.getLogger("audit-feedback")

audit_app = Blueprint(__name__)


@audit_app.route('/auditcontroller')
def index():
    return {'audit': 'controller'}


@audit_app.route('/api/audit/user/{user_id}',
                 methods=['GET'],
                 cors=global_auth.cors_config)
def get_user_audit(user_id):
    log.info(f"getting user audit event for userId {user_id}")
    response = global_db_handler.get_user_audit_db().get_user_item(
        str(user_id))

    if len(response) == 0:
        return Response(body={"message": "user not found"}, status_code=400)
    response = global_db_handler.replace_decimals(response)
    return Response(body=response, status_code=200)


@audit_app.route('/api/audit/session/{session_id}',
                 methods=['GET'],
Exemple #11
0
from chalice import Blueprint, Response
from chalicelib import app, authorizer, s3_client, batch_client
from chalicelib.decorator import check_org_permission, check_json_body
from chalicelib.dynamodb import get_container_table
import os
import uuid

plugin_app = Blueprint(__name__)


@plugin_app.route('/', methods=['GET'], cors=True, authorizer=authorizer)
@check_org_permission('read')
def get_container_goals(org, name):
    container_info = get_container_table().get_item(Key={'tid': name})
    if 'Item' not in container_info:
        return Response(body={'error': 'not found'}, status_code=404)
    if not container_info['Item']['organization'] == org:
        return Response(body={'error': 'not found'}, status_code=404)
    if 'goals' not in container_info['Item']:
        return Response(body=[], status_code=200)

    bucket = os.environ.get('OTM_STATS_BUCKET')
    prefix = (os.environ.get('OTM_STATS_PREFIX') or '')
    if not org == 'root':
        prefix += org + '/'

    result = []
    for r in container_info['Item']['goals']:
        goal = r.copy()
        goal['result_url'] = s3_client.generate_presigned_url(
            ClientMethod='get_object',
Exemple #12
0
 def __init__(self):
     self.router = Blueprint(__name__)
Exemple #13
0
    def create_blueprint(self, name, authorizer, lifecycle, cors=False):
        if name in vars(sys.modules[__name__]):
            raise InvalidAuthHandlerNameError(name)

        routes = Blueprint('%s' % __name__)

        extra_kwargs = {}
        if cors is True:
            extra_kwargs['cors'] = True

        @routes.authorizer(name=name)
        @self._rename_fn(name)
        def auth(auth_request):
            return authorizer.auth_handler(auth_request)

        @routes.route('/register', methods=['POST'], **extra_kwargs)
        @handle_client_errors
        def register():
            body = routes.current_request.json_body
            username = get_param(body, 'username', required=True)
            password = get_param(body, 'password', required=True)
            body.pop('username')
            body.pop('password')
            return lifecycle.register(username, password, body)

        @routes.route('/confirm_registration',
                      methods=['POST'],
                      **extra_kwargs)
        @handle_client_errors
        def confirm():
            body = routes.current_request.json_body
            username = get_param(body, 'username', required=True)
            code = get_param(body, 'code', required=True)
            lifecycle.confirm(username, code)

        @routes.route('/login', methods=['POST'], **extra_kwargs)
        @handle_client_errors
        def login():
            body = routes.current_request.json_body
            username = get_param(body, 'username', required=True)
            password = get_param(body, 'password', required=True)
            try:
                return lifecycle.login(username, password)
            except ChallengeError as e:
                return Response(body=e.params,
                                status_code=401,
                                headers={
                                    'Challenge': e.challenge,
                                    'Session': e.session,
                                })

        @routes.route('/auth_challenge', methods=['POST'], **extra_kwargs)
        @handle_client_errors
        def auth_challenge():
            body = routes.current_request.json_body
            challenge = get_param(body, 'challenge', required=True)
            session = get_param(body, 'session', required=True)
            params = get_param(body, 'params', required=True)
            return lifecycle.auth_challenge(challenge, session, params)

        @routes.route('/refresh', methods=['POST'], **extra_kwargs)
        @handle_client_errors
        def refresh():
            body = routes.current_request.json_body
            refresh_token = get_param(body, 'refresh_token', required=True)
            return lifecycle.refresh(refresh_token)

        setattr(sys.modules[__name__], name, auth)
        return routes, auth
from chalice import Blueprint
from . import app, authorizer, s3, s3_client, athena_client, execute_athena_query, save_athena_usage_report
from .decorator import check_org_permission, check_json_body
from urllib.parse import urlparse
import pandas as pd
import os
import json
import datetime

stats_routes = Blueprint(__name__)


def normalize_url(url):
    if isinstance(url, str):
        if url and url.lower() == 'undefined':
            return url

        if url:
            parsedurl = urlparse(url)
            return "{0}://{1}{2}".format(parsedurl.scheme, parsedurl.netloc,
                                         parsedurl.path)

    return None


def generate_base_criteria(org, tid, stime, etime):
    q = ''
    q += " org = '%s'" % org
    q += " AND tid = '%s'" % tid
    q += ' AND year * 10000 + month * 100 + day >= %s' % stime.strftime(
        '%Y%m%d')
Exemple #15
0
from chalice import Blueprint

from chalicelib.jinja_templates import render_to_response

dashboards_routes = Blueprint(__name__)


@dashboards_routes.route("/dashboard", methods=["GET", "POST"])
def dashboard():
    context = {"hello": "world"}
    return render_to_response("base.html", **context)
from chalice import Blueprint
from chalicelib.libs.models.mpc.user import User
from chalicelib.extensions import *
from chalicelib.libs.credit.sqs import CreditCashOutSqsSenderEvent, CreditCashOutRequest
from chalicelib.libs.core.sqs_sender import SqsSenderImplementation
from chalicelib.libs.credit.storage import CreditStorageImplementation

credit_blueprint = Blueprint(__name__)


def __get_current_user() -> User:
    user = credit_blueprint.current_request.current_user
    if user.is_anyonimous:
        raise HttpAuthenticationRequiredException()

    return user


@credit_blueprint.route('/credit_cash_out', methods=['POST'], cors=True)
def credit_cash_out():
    credit_storage = CreditStorageImplementation()

    try:
        user = __get_current_user()
        request_data = credit_blueprint.current_request.json_body

        amount = float(request_data.get('amount', 0))
        if amount == 0:
            raise HttpIncorrectInputDataException()

        account_holder_name = str(request_data.get('account_holder_name',
Exemple #17
0
from chalice import Blueprint
from chalicelib.libs.models.mpc.invite_friends import InviteFriends
from chalicelib.libs.models.mpc.user import User
from chalicelib.libs.core.chalice.request import MPCRequest
from chalicelib.extensions import *

invite_friends_blueprint = Blueprint(__name__)

def __get_request() -> MPCRequest:
    return invite_friends_blueprint.current_request

def __get_current_user() -> User:
    user = __get_request().current_user
    if user.is_anyonimous:
        raise HttpAuthenticationRequiredException()

    return user
    
@invite_friends_blueprint.route('/send_invitation', methods=['POST'], cors=True)
def validate_user():
    # user = __get_current_user()
    # request = __get_request()
    # to_email = request.json_body['email']
    # invite_friends = InviteFriends(user.profile.informations['first_name'])
    # invite_friends.send_invite_email(to_email)
    # return {'status': True}
    try:
        user = __get_current_user()
        request = __get_request()
        to_email = request.json_body['email']
        invite_friends = InviteFriends(user.profile.informations['first_name'])
Exemple #18
0
#
#  You should have received a copy of the GNU Affero General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
from functools import cmp_to_key
from http import HTTPStatus
from re import sub
from typing import Dict

import semver
from chalice import Blueprint, Response, ChaliceViewError
from pynamodb.exceptions import DoesNotExist

from .config import *
from .models import ModuleName, ModuleModel

bp = Blueprint(__name__)


@bp.route("/")
def list_all() -> Response:
    """
    Lists all modules in the registry
    ref: https://www.terraform.io/docs/registry/api.html#list-modules
    """
    bp.current_request.query_params["q"] = "*"
    return search()


@bp.route("/{namespace}")
def list_namespace(namespace) -> Response:
    """
from chalicelib import global_db_handler,global_auth
from chalice import Blueprint, Response
import logging
log = logging.getLogger("audit-feedback")
roles_app = Blueprint(__name__)

_SESSION_ROLES = None
_USER_ROLES = None
#invokeLambda = client("lambda", region_name="us-east-2")


@roles_app.route('/api/rolescontroller')
def index():
    return {"roles": "controller"}


def user_roles():
    global _USER_ROLES
    if _USER_ROLES is None:
        log.info("cache miss for user roles, connecting to db")
        _USER_ROLES = global_db_handler.get_user_roles_db().list_all_items()
        _USER_ROLES = global_db_handler.replace_decimals(_USER_ROLES)

    return _USER_ROLES


def session_types():
    global _SESSION_ROLES
    if _SESSION_ROLES is None:
        log.info("cache miss for session roles, connecting to db")
        _SESSION_ROLES = global_db_handler.get_session_roles_db().list_all_items()
from chalice import Blueprint
from chalicelib.extensions import *
from chalicelib.libs.contactus.sqs import ContactusSqsSenderEvent, ContactusRequest
from chalicelib.libs.core.sqs_sender import SqsSenderImplementation
from chalicelib.libs.core.file_storage import FileStorageImplementation
import os
import uuid
import hashlib

contactus_blueprint = Blueprint(__name__)
    
@contactus_blueprint.route('/contact', methods=['POST'], cors=True)
def contactus_cash_out():
    file_storage = FileStorageImplementation()

    try:
        request_data = contactus_blueprint.current_request.json_body

        issue = request_data.get('issue', '')
        if not issue:
            raise ValueError('Please select issue')

        issue_detail = request_data.get('issue_detail', '')
        if not issue_detail:
            raise ValueError('Please select issue in detail')

        first_name = request_data.get('first_name', '')
        if not first_name:
            raise ValueError('Please input first name')

        last_name = request_data.get('last_name', '')
Exemple #21
0
from chalice import Blueprint, Response

from chalicelib.auth.decorators import protected
from chalicelib.core.exceptions import APIError
from chalicelib.core.shared import g
from chalicelib.user.schema import User as UserSchema

blueprint = Blueprint(__name__)


# TODO: better way of handling path parameters? (Flask does it)
@blueprint.route('/user/{user_id}')
@protected
def get_user(user_id):
    if int(user_id) != g.current_user.user_id:
        raise APIError(status=403)

    return Response(body=UserSchema().dump(g.current_user), status_code=200)


@blueprint.route('/user/me')
@protected
def get_current_user():
    return Response(body=UserSchema().dump(g.current_user), status_code=200)


Exemple #22
0
import boto3
import logging
import os
import requests
import tablib
from chalice import Blueprint
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from . import common


fixtures = Blueprint(__name__)

LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)

s3 = boto3.resource('s3')


@fixtures.schedule('cron(0 18 * * ? *)')
def get_fixtures(event):

    # Set up the requests Session with retries
    s = requests.Session()
    retries = Retry(total=5, backoff_factor=1, status_forcelist=[ 500, 502, 503, 504 ])
    s.mount('http://', HTTPAdapter(max_retries=retries))
    s.mount('https://', HTTPAdapter(max_retries=retries))

    # Retrieve the fixtures from the web api
    num_days = None
    if 'FIXTURES_DAYS' in os.environ:
Exemple #23
0
from chalice import Blueprint
from chalicelib.libs.models.mpc.brands import Brand

brands_blueprint = Blueprint(__name__)


@brands_blueprint.route('/list-brands', methods=['GET'], cors=True)
def list_brands():
    brands = Brand()
    return brands.get_all_brands()
Exemple #24
0
from chalice import Blueprint, Response
from . import app, authorizer
from .dynamodb import get_org_table
from .decorator import check_org_permission, check_json_body
from decimal import Decimal
import os
import stripe
import time

payment_routes = Blueprint(__name__)

stripe.api_key = os.environ.get('STRIPE_SK')


@payment_routes.route('/', methods=['GET'], cors=True, authorizer=authorizer)
@check_org_permission('admin')
def get_payment_customer(org):
    org_info = get_org_table().get_item(Key={'name': org})
    if 'Item' not in org_info:
        return Response(body={'error': 'not found'}, status_code=404)

    if 'payment' in org_info['Item']:
        data = org_info['Item']['payment']
        customer = stripe.Customer.retrieve(data['id'])
        pm_id = customer['invoice_settings']['default_payment_method']
        pm = stripe.PaymentMethod.retrieve(pm_id)

        return {
            'id': data['id'],
            'name': customer['name'],
            'email': customer['email'],
import datetime
from uuid import uuid4
import jwt
import logging
from chalice import Blueprint, AuthResponse, Response, UnauthorizedError
log = logging.getLogger('sessions-app')
_SECRET = b'\xf7\xb6k\xabP\xce\xc1\xaf\xad\x86\xcf\x84\x02\x80\xa0\xe0'
auth_app = Blueprint(__name__)


def get_jwt_token(session_details):
    log.info('in auth, generating jwt token {}'.format(session_details))
    now = datetime.datetime.utcnow()
    unique_id = str(uuid4())
    payload = {
        'sessionId': session_details['sessionId'],
        'email': session_details['email'],
        'firstName': session_details['firstName'],
        'lastName': session_details['lastName'],
        'token': session_details['token'],
        'role': session_details['role'],
        'iat': now,
        'nbf': now,
        'jti': unique_id,
        'userId': session_details['userId']
        # NOTE: We can also add 'exp' if we want tokens to expire.
    }
    return jwt.encode(payload, _SECRET, algorithm='HS256').decode('utf-8')


def decode_jwt_token(token):
"""

__author__ = "Glücks GmbH - Frederik Glücks"
__email__ = "*****@*****.**"
__copyright__ = "Frederik Glücks - Glücks GmbH"

# Generic/Built-in Imports

# External libs/modules
from chalice import Blueprint

# Own libs/modules
from luckywood import DataCaching


data_caching_routes = Blueprint(__name__)


@data_caching_routes.route('/cache', methods=['DELETE'])
def cache_clear():
    """
    Clear the complete data cache and returns the number of
    deleted objects

    :return: json
    """

    return {
        "cleared": DataCaching.clear()
    }
Exemple #27
0
 def __init__(self):
     self.bluePrintIns = Blueprint(__name__)
import os
from uuid import uuid4
from chalicelib import auth, global_auth
from chalicelib.validationslib import session_validation
from chalicelib import global_db_handler
from requests.auth import HTTPBasicAuth
from chalicelib.audit_app import audit_controller
from datetime import datetime
from chalice import Blueprint, Response
import json
import logging
import requests

session_app = Blueprint(__name__)

log = logging.getLogger('sessions-app')

OPENVIDU_URL = os.environ['OPENVIDU_URL']
ROCKETCHAT_URL = os.environ['ROCKETCHAT_URL']


@session_app.route('/api/session_controller', cors=global_auth.cors_config)
def index():
    return Response(body={"session": "controller"}, status_code=200)


@session_app.route('/api/session/join',
                   methods=['POST'],
                   cors=global_auth.cors_config)
def login():
    """"
Exemple #29
0
from chalice import Blueprint
from chalicelib.libs.models.mpc.Admin.Magento import Magento
from chalicelib.libs.purchase.cart.service import CartAppService

magento_blueprint = Blueprint(__name__)


@magento_blueprint.route('/validate', methods=['POST'], cors=True)
def validate_user():
    request = magento_blueprint.current_request
    params = request.json_body
    email = params.get('email')
    passwd_to_validate = params.get('password')

    mage = Magento()
    found, created, msg = mage.validate_user(email, passwd_to_validate)

    return {'created': created, 'found': found, 'message': msg}


@magento_blueprint.route('/sync', methods=['POST'], cors=True)
def sync_user_data():
    request = magento_blueprint.current_request
    user_attributes = request.current_user.profile.sync_user_data()
    response = request.current_user.sync_user_attributes(user_attributes)

    return {'status': response}


# @todo : move login and logout actions from the frontend side, and then remove on-* endpoints
import json
import logging
import numpy as np
import os
import textwrap
from . import common
# from . import over_under_predictions
from chalice import Blueprint
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from collections import Counter, defaultdict


predictions = Blueprint(__name__)

LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)

main_leagues = os.environ['MAIN_LEAGUES']
new_leagues = os.environ['NEW_LEAGUES']

Classifier = LinearRegression


@predictions.on_s3_event(bucket=os.environ['S3_BUCKET'], prefix='fixtures/',
                 suffix='.csv', events=['s3:ObjectCreated:*'])
def make_predictions(event):
    LOGGER.info("Looks like there's a new fixtures file: %s/%s", event.bucket, event.key)

    match_predictions(event)