Exemplo n.º 1
0
def queryParametersValidation(current_request):
    queryParametersDict = current_request.query_params
    
    if (queryParametersDict==None):
        app.log.error("Query parameters not passed")
        #print("Query parameters not passed") 
        raise BadRequestError("""
                Query parameters are not passed 
                Send query as below example: 
                 https://ciq51uqa3d.execute-api.us-east-2.amazonaws.com/api/urlLookUp?url=http://www.google.co.in/news 
             """)
        
    else :
        if( ('url' not in queryParametersDict)):
            #print("Query parameters does not contain query key 'url' below is the dict of queryParameters")
            app.log.error("Query parameters does not contain query key 'url' below is the dict of queryParameters")
            #print(queryParametersDict)
            app.log.info(queryParametersDict)
            raise BadRequestError("""
                Query parameters does not contain query key 'url'
                Send query as below example: 
                 https://ciq51uqa3d.execute-api.us-east-2.amazonaws.com/api/urlLookUp?url=http://www.google.co.in/news 
             """)
        else : 
            return True
Exemplo n.º 2
0
def verify(address):
    # Validate input
    if not address or len(address) == 0:
        raise BadRequestError("Address not set")
    if len(address) != 40 and len(address) != 42:
        raise BadRequestError("Malformed address %s" % (address, ))

    app.log.info("Request %s" % (address, ))

    # Get source from etherscan
    name, source, compiler = get_name_and_source(address)

    # Get path to solc
    workdir = getcwd()
    solcdir = path.join(workdir, "vendor") if LOCAL else workdir

    if compiler.startswith("v0.4"):
        solc = path.join(solcdir, "solc-0.4.25")
    elif compiler.startswith("v0.5"):
        solc = path.join(solcdir, "solc-0.5.12")
    else:
        raise BadRequestError("Unsupported compiler version %s" % (compiler, ))

    # Write down contract
    filename = path.join("/tmp", "%s.sol" % (address, ))
    with open(filename, "w") as contractfile:
        contractfile.write(source)

    # Capture stdout and run slither
    output = StringIO()
    with redirect_stdout(output):
        erc20.run(filename, name, solc=solc)

    return {"name": name, "output": output.getvalue(), "source": source}
Exemplo n.º 3
0
def get_ssh_key(uuid):
    baisc = get_authorized_username(app.current_request)
    splited = baisc.split('@', 1)
    if len(splited) != 2:
        raise BadRequestError("Invalid authorization")

    user, secret = splited[0], splited[1]
    item = get_task_db().get_item(uuid, user=user)
    if not item:
        raise NotFoundError("Task doesn't exist")
    if len(secret) < 8:
        raise BadRequestError("Invalid secret_key|access_token")

    access = user.rsplit('-', 1)[1]
    session = boto3.Session(aws_access_key_id=access,
                            aws_secret_access_key=secret)
    client = session.client('sts')
    try:
        client.get_caller_identity()
    except:
        raise ForbiddenError("Invalid secret_key")

    extend = item.get('extend', {})
    key = extend.get('key')
    if not key:
        raise NotFoundError("SSH key doesn't exist")

    s3_client = get_s3_client()
    params = {'Bucket': os.environ['OCTOUP_BUCKET'], 'Key': key}
    url = s3.generate_presigned_url(s3_client, 'get_object', params, 3600)
    return Response(body='', headers={'Location': url}, status_code=301)
Exemplo n.º 4
0
def upload():
    try:
        hello = dict(app.current_request.headers)
        print hello['authorization']
        if hello.has_key('authorization'):
            decoded = jwt.decode(str(hello['authorization']),
                                 HMAC_PASSWORD_2,
                                 algorithms=['HS256'])
            print "decoded", decoded
            details = is_valid_jwt(decoded)
            # print "details",details[]
        s3 = boto3.client('s3')
        files = _get_parts()
        try:
            for k, v in files.items():
                file_key = '{}.xml'.format(str(uuid4()))
                s3.upload_fileobj(BytesIO(v[0]), 'training-cv-uploader',
                                  file_key)

            table = dynamo.Table('cv_data')
            table.put_item(
                Item={
                    'filename': file_key,
                    'email': details[0]['email'],
                    'username': details[0]['username']
                })
            sleep(2)
            return {'uploaded': True}
        except Exception as e:
            print(e)
            return BadRequestError(e)
    except Exception as e:
        raise BadRequestError(e)
Exemplo n.º 5
0
def match_post(match_id):
    api_key = app.current_request.context['identity']['apiKey']
    match = sdb.get_match(api_key, match_id)
    if not match.is_active():
        return match.get_state()

    request = app.current_request
    data = request.json_body
    try:
        row = int(data['row'])
        col = int(data['col'])
    except (
            KeyError,
            TypeError,
            ValueError,
    ):
        raise BadRequestError('row or col is missing or not int')

    if not 0 <= row < settings.BOARD_SIZE or not 0 <= col < settings.BOARD_SIZE:
        raise BadRequestError('row or col is out of range')

    match.start_move(row, col)
    sdb.update_match(api_key, match_id, match)
    if not match.is_active():
        sdb.increment_total_score(match.user_id, match.score)
        s3.update_hof(sdb.get_hof_data())

    if app.debug:
        print(data)
        utils.print_match_state(match.get_state())

    return match.get_state()
Exemplo n.º 6
0
def sqs_add_job():
    json_data = app.current_request.json_body
    keys = ['action', 'input', 'output']
    for key in keys:
        if key not in json_data:
            raise BadRequestError('Data json must contains all keys: ' +
                                  ','.join(keys))

    keys_input = ['picture_0', 'picture_1', 'picture_2', 'picture_3']
    for key in keys_input:
        if key not in json_data['input']:
            raise BadRequestError('Input json must contains all keys: ' +
                                  ','.join(keys_input))

    # Add bucket
    json_data['s3_bucket'] = S3_BUCKET
    print(json.dumps(json_data))

    sqs = boto3.resource('sqs')
    queue_name = SQS_QUEUE
    try:
        queue = sqs.get_queue_by_name(QueueName=queue_name)
    except:
        # Create new queue if it does not exist
        queue = sqs.create_queue(QueueName=queue_name)

    str = json.dumps(json_data)
    response = queue.send_message(MessageBody=str)
    return response
Exemplo n.º 7
0
def validate_params(jira_server_name, api_key):
    if not jira_server_name:
        raise BadRequestError("'jira_server_name' is required.")
    if not api_key:
        raise BadRequestError("'api_key' was not provided.")
    if not validate_api_key(api_key):
        raise UnauthorizedError("'api_key' is not valid")
Exemplo n.º 8
0
def add_joke():
    joke = app.current_request.json_body.get('joke', '')
    punchline = app.current_request.json_body.get('punchline', '')

    if not joke or not punchline:
        raise BadRequestError(
            "You must provide an object with keys of 'joke' and 'punchline'")
    joke_uuid = str(uuid.uuid4())
    response = client.put_item(TableName=os.environ['APP_TABLE_NAME'],
                               Item={
                                   'uuid': {
                                       'S': joke_uuid
                                   },
                                   'votes': {
                                       'N': '0'
                                   },
                                   'joke': {
                                       'S': joke
                                   },
                                   'punchline': {
                                       'S': punchline
                                   }
                               })
    print(response)
    if response['ResponseMetadata']['HTTPStatusCode'] == 200:
        return {"joke_uuid": joke_uuid}
    else:
        raise BadRequestError("Error writing to table")
Exemplo n.º 9
0
def add_transactions():
    incoming_transactions = app.current_request.json_body
    valid_keys = {"payer", "points", "timestamp"}
    valid_value_types = ["<class 'int'>", "<class 'str'>", "<class 'str'>"]
    if type(incoming_transactions) == list:
        for transaction in incoming_transactions:
            ts_unique_keys = set(transaction.keys())
            ts_value_types = sorted(
                [str(type(val)) for val in transaction.values()])

            if ts_unique_keys != valid_keys:
                raise BadRequestError(
                    "Transaction records must only contain payer, points, and timestamp keys"
                )
            elif ts_value_types != valid_value_types:
                raise BadRequestError(
                    "Transaction records must contain valid data types: payer (string), points (integer), timestamp (string as YYYY-MM-DDT00:00:00Z)"
                )

        transaction_store.extend(incoming_transactions)
    else:
        raise BadRequestError(
            "Request body must be of type list and include at least one transaction record"
        )

    return transaction_store
Exemplo n.º 10
0
def reset_password():
    json_body = app.current_request.json_body
    email = json_body['email']
    token = str(json_body['token'])
    password = json_body['password']
    if not (email or password or token):
        raise BadRequestError("Email, password and token mush be supplied.")
    with contextlib.closing(session_factory()) as session:
        user = session.query(User).filter(User.email == email).first()
        user_token = session.query(UserToken).filter(
            UserToken.user_id == user.id).first()
        if not user:
            raise NotFoundError("User not found")
        if datetime.now() > user_token.expire:
            raise BadRequestError("Token is expired.")
        if not user_token:
            raise BadRequestError("Please request for a token first")
        if not verify_password_reset_token(token=token,
                                           salt=user.password_salt,
                                           hashed_token=user_token.token):
            raise BadRequestError("Token is invalid")
        result = encode_password(password=password, salt=user.password_salt)
        session.query(User).filter(User.email == email).update(
            {'password_hash': result['hashed']})
        session.flush()
        session.commit()
        jwt_token = get_jwt_token(
            user.email + "," + str(user.role) + "," + str(user.id), password,
            user.password_salt, user.password_hash, JWT_SECRET)
        info = {'token': jwt_token, 'user': user}
        schema = TokenSchema()
        response = schema.dumps(info)
        if response.errors:
            raise ChaliceViewError(response.errors)
        return response.data
Exemplo n.º 11
0
def create_user():
    try:
        dynamo = boto3.resource('dynamodb', region_name='us-east-1')
        jbody = dict(app.current_request.json_body)
        if jbody.has_key('email') and jbody.has_key(
                'username') and jbody.has_key('password') and jbody.has_key(
                    'repeat_password'):
            if jbody['password'] == jbody['repeat_password']:
                print jbody
                user_table = dynamo.Table('ctf_users')
                response = user_table.put_item(
                    Item={
                        'email': jbody['email'],
                        'username': jbody['username'],
                        'password': hashlib.md5(jbody['password']).hexdigest()
                    })
                print response
                return {'success': True}
            else:
                return BadRequestError('Passwords do not match')
        else:
            return BadRequestError(
                "You need to have the email, username, password and repeat_password fields"
            )
    except Exception as e:
        return BadRequestError(e)
Exemplo n.º 12
0
def index():
    body = app.current_request.json_body

    if 'data' not in body:
        raise BadRequestError('Missing image data')
    if 'ENDPOINT_NAME' not in os.environ:
        raise BadRequestError('Missing endpoint')

    image = base64.b64decode(body['data']) # byte array
    endpoint = os.environ['ENDPOINT_NAME']

    if 'topk' not in body:
        topk = 257
    else:
        topk = body['topk']

    print("%s %d" % (endpoint, topk))

    runtime = boto3.Session().client(service_name='sagemaker-runtime', region_name='us-east-1')
    response = runtime.invoke_endpoint(EndpointName=endpoint, ContentType='application/x-image', Body=image)
    probs = response['Body'].read().decode() # byte array

    probs = ast.literal_eval(probs) # array of floats
    probs = np.array(probs) # numpy array of floats

    topk_indexes = probs.argsort() # indexes in ascending order of probabilities
    topk_indexes = topk_indexes[::-1][:topk] # indexes for top k probabilities in descending order

    topk_categories = []
    for i in topk_indexes:
       topk_categories.append((i+1, probs[i]))

    return {'response': str(topk_categories)}
Exemplo n.º 13
0
def modify_topic(c_id, t_id):
    check_headers()
    req = app.current_request
    uid = req.headers['X-Api-Key']
    body = req.json_body or {}

    if 'field' not in body:
        raise BadRequestError("'field' Required")

    try:
        c = pc.load_coffee(coffee_id=c_id, uid=uid)
    except:
        # TODO fix library to raise better exceptions
        raise NotFoundError("No coffee found for that ID")

    if body['field'] == 'votes':
        if 'op' not in body or body['op'] not in ('add', 'remove'):
            raise BadRequestError("'op' Required and must be add|remove")
        c.vote(t_id, body['op'])
        return format_state(c)

    if 'to' not in body:
        raise BadRequestError("At least a 'to' value is required")

    # TODO you know errors CAN happen, right?
    if 'from' in body:
        rv = c.update_topic(t_id, body['field'], body['to'], body['from'])
    else:
        rv = c.update_topic(t_id, body['field'], body['to'])
    if not rv:
        raise ChaliceViewError("Unknown Error updating the topic")
    return format_state(c)
Exemplo n.º 14
0
def item_set():
    """ Creates an item based on the request body """
    data = app.current_request.json_body
    print(data)

    if data is None:
        raise BadRequestError("Empty request body, requires UUID")

    if "UUID" not in data:
        raise BadRequestError("Invalid request body, missing UUID.")

    # Validate that the UUID fits the UUID v4 model
    try:
        UUID(data.get("UUID"))
    except ValueError as invalid_uuid:
        raise BadRequestError("Invalid UUID.") from invalid_uuid

    # Create a timestamp of when the transaction was completed (the time the call is made to transaction-logging), this will be used as the Sort Key.
    data["Timestamp"] = int(time.time())
    get_table().put_item(Item=data)

    return Response(
        body={
            "message": "Created new transaction log",
            "UUID": data["UUID"],
            "Timestamp": data["Timestamp"],
        },
        status_code=201,
        headers=None,
    )
Exemplo n.º 15
0
def bad_search():
    try:
        jbody = app.current_request.json_body
        if isinstance(jbody, dict):
            if jbody.has_key('db') and jbody.has_key(
                    'search_term') and jbody.has_key(
                        'search_operator') and jbody.has_key('search_field'):
                db = boto3.client('dynamodb')
                response = db.scan(TableName=jbody['db'],
                                   Select='ALL_ATTRIBUTES',
                                   ScanFilter={
                                       jbody['search_field']: {
                                           "AttributeValueList": [{
                                               "S":
                                               jbody['search_term']
                                           }],
                                           "ComparisonOperator":
                                           jbody['search_operator']
                                       }
                                   })
                if response.has_key('Items'):
                    return {"search_results": response['Items']}
                else:
                    return {"search_results": None}
            else:
                return BadRequestError(
                    "All parameters are required to complete the search")
        else:
            return BadRequestError("Seems to be a wrong content type")
    except Exception as e:
        return BadRequestError(e.message)
Exemplo n.º 16
0
def index():
    body = app.current_request.json_body

    if 'data' not in body:
        raise BadRequestError('Missing image data')
    if 'height' not in body:
        raise BadRequestError('Missing image height')
    if 'width' not in body:
        raise BadRequestError('Missing image width')

    h = body['height']
    w = body['width']
    image = base64.b64decode(body['data'])
    L = len(image)

    image = np.fromstring(image, np.uint8)
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    (H, W, _) = image.shape
    image = cv2.resize(image, (
        h,
        w,
    ))
    image = cv2.imencode('.jpeg', image)

    data = base64.b64encode(image[1].tostring())

    print("%d %d %d %d %d " % (L, H, W, h, w))

    return {'data': str(data)}
Exemplo n.º 17
0
def whoami():
    hello = dict(app.current_request.headers)
    print hello['authorization']
    if hello.has_key('authorization'):
        try:
            decoded = jwt.decode(str(hello['authorization']),
                                 HMAC_PASSWORD_2,
                                 algorithms=['HS256'])
            # print "decoded", decoded
            details = is_valid_jwt(decoded)
            if details[0].has_key('role'):
                if details[0]['role'] == 'admin':
                    return {
                        'success': {
                            'user': details[0]['username'],
                            'email': details[0]['email'],
                            'role': details[0]['role']
                        }
                    }
                elif details[0]['role'] == 'user':
                    return {
                        'success': {
                            'user': details[0]['username'],
                            'email': details[0]['email'],
                            'role': details[0]['role']
                        }
                    }
                else:
                    return BadRequestError('Not able to verify user')
            else:
                return BadRequestError('Unable to verify user, based on token')
        except Exception as e:
            return UnauthorizedError(e)
    else:
        return UnauthorizedError('No Token')
Exemplo n.º 18
0
def updateproject(projectid, email):
    i = app.current_request.json_body
    projectname = i['projectname'] if "projectname" in i else None
    description = i['description'] if "description" in i else None
    striker = i['striker'] if "striker" in i else None
    giturl = i['giturl'] if "giturl" in i else None
    updated = datetime.now().replace(microsecond=0).isoformat()

    if projectid is None:
        raise BadRequestError('No Project ID Specified')
    if email is None:
        raise BadRequestError('No Project Email Specified')
    Key = {'projectid': projectid, 'email': striker}
    project = {
        'projectid': projectid,
        'projectname': projectname,
        'description': description,
        'updatedBy': email,
        'giturl': giturl,
        'updated': updated
    }
    res = dynamoHelper.update_doc(dynamo_project_table_name, Key, project)
    return Response(body={
        'response': 'Successfully updated project with id: %s' % projectid,
        'message': res
    },
                    status_code=200,
                    headers={'Content-Type': 'application/json'})
Exemplo n.º 19
0
def new_person():
    logging.info('Request Received: Add New Person')
    g = setup_graph()
    try:
        properties = app.current_request.json_body
        # TODO - Validate the JSON
        logging.info('Adding New Person to Graph')
        # Get the ID from the JSON
        person_id = properties.pop('id')
        if not person_id:
            raise BadRequestError('Missing "id" in body')
        person = get_person(person_id=person_id, g=g)
        if person:
            raise BadRequestError('id "%s" already exists' % person_id)
        # TODO - Validate there is a single unique ID
        person = g.addV('person').property(T.id, person_id).next()
        # Ideally I would roll this into a single call
        logging.info("Received Properties: " + str(properties))
        for prop_name, prop_value in properties.items():
            g.V(person).property(prop_name, prop_value).next()
    except (ValueError, AttributeError, TypeError) as e:
        logging.error(e, exc_info=True)
        raise BadRequestError('Could not insert person.  Error: ' + str(e))
    logging.info("Successfully inserted person")
    return {"id": person_id}
Exemplo n.º 20
0
def contact():
    # Set these in chalice/__init__.py
    to_email = TO_EMAIL
    from_email = FROM_EMAIL
    site = SITE

    parsed = parse_qs(app.current_request.raw_body.decode("utf-8"))

    # Default to [None] to avoid IndexError
    name = parsed.get("name", [None])[0]
    email = parsed.get("email", [None])[0]
    message = parsed.get("message", [None])[0]

    if not name:
        raise BadRequestError("Please enter your name")
    if not email:
        raise BadRequestError("Please enter your email")
    if not message:
        raise BadRequestError("Please enter your message")

    # Don't send if messge, name, or email contains words from IGNORE list
    for ignore in IGNORE:
        if any([
                ignore in message.lower(), ignore in name.lower(), ignore
                in email.lower()
        ]):
            return {
                "status": "OK",
            }

    client = boto3.client("ses")

    client.send_email(
        Source=from_email,
        Destination={
            "ToAddresses": [to_email],
        },
        Message={
            "Subject": {
                "Data": "Message from " + name + " via " + site,
            },
            "Body": {
                "Text": {
                    "Data": message,
                }
            },
        },
        # setting the reply-to header makes means that when you hit
        # reply, the email goes to your visitor, not your from_email
        ReplyToAddresses=[email],
    )

    response = {
        "status": "OK",
    }

    return response
Exemplo n.º 21
0
def getProject(projName):
    try:
        response = projectTable.get_item(Key={'projName': projName})
    except ClientError as e:
        raise BadRequestError(e.response['Error']['Message'])
    else:
        if 'Item' not in response:
            raise BadRequestError("The project doesn't exist")
        else:
            project = response['Item']
            return project
Exemplo n.º 22
0
def spend_points():
    request_body = app.current_request.json_body
    if (type(request_body) != dict or len(request_body) != 1
            or "points" not in request_body):
        raise BadRequestError(
            "Request body must be of type dict and with a single key 'points'")
    elif type(request_body["points"]) != int:
        raise BadRequestError("Points value must be of type int")

    global transaction_store
    sorted_transactions = sorted(transaction_store,
                                 key=lambda ts: ts["timestamp"])

    requested_points = request_body["points"]
    total_points_available = sum([ts["points"] for ts in sorted_transactions])

    if requested_points > total_points_available:
        error_body = {
            "Error": "Not enough points available for this request",
            "Available Points": total_points_available,
        }
        return custom_error(error_body, 409)

    points_spent = {}

    for ts_idx, transaction in enumerate(sorted_transactions):
        ts_points = transaction["points"]
        if requested_points > 0 and ts_points != 0:
            if requested_points >= ts_points:
                points_consumed = ts_points
                requested_points -= points_consumed
                sorted_transactions[ts_idx]["points"] = 0
            else:
                points_consumed = requested_points
                ts_remainder = ts_points - points_consumed
                sorted_transactions[ts_idx]["points"] = ts_remainder
                requested_points = 0

            ts_payer = transaction["payer"]

            if ts_payer in points_spent.keys():
                points_spent[ts_payer] += points_consumed
            else:
                points_spent[ts_payer] = points_consumed
        elif requested_points == 0:
            break

    transaction_store = sorted_transactions
    points_spent_resp = [{
        "payer": payer,
        "points": -points
    } for payer, points in points_spent.items()]

    return points_spent_resp
Exemplo n.º 23
0
def getNode(id):
    try:
        response = nodeTable.get_item(Key={'id': id})
    except ClientError as e:
        raise BadRequestError(e.response['Error']['Message'])
    else:
        if 'Item' not in response:
            raise BadRequestError("The node doesn't exist")
        else:
            node = response['Item']
            return node
Exemplo n.º 24
0
def get_request_jwt():
    try:
        auth_token_value = app.current_request.headers[
            'authorization'].replace('Basic ', '')
        decoded_jwt = jwt.decode(auth_token_value,
                                 PyfightConfig.get('JWT_SECRET'),
                                 algorithm='HS256')
        return decoded_jwt
    except KeyError:
        raise BadRequestError('Authorization header not provided')
    except jwt.exceptions.DecodeError:
        raise BadRequestError('Authorization header not valid')
Exemplo n.º 25
0
def deleteproject(projectid, email):
    if not projectid or projectid is None:
        raise BadRequestError("Please supply Project ID")
    if not email or email is None:
        raise BadRequestError("Please supply Email of striker")
    res = dynamoHelper.delete_doc(dynamo_project_table_name, projectid, email)
    return Response(body={
        'response': 'Successfully deleted project with id %s' % projectid,
        'message': res
    },
                    status_code=200,
                    headers={'Content-Type': 'application/json'})
Exemplo n.º 26
0
    def returns_create_upload_file():
        file_storage = FileStorageImplementation()

        user_id = __get_user().id

        # @todo : create file uploader or so... ???

        max_size_mb = 4
        size_in_bytes = len(blueprint.current_request.raw_body)
        if size_in_bytes > max_size_mb * 1024 * 1024:
            raise BadRequestError(
                'Uploaded file max size is {} Mb!'.format(max_size_mb))
        elif not size_in_bytes:
            raise BadRequestError('Uploaded file cannot be empty!')

        file_id = str(user_id) + str(uuid.uuid4())
        file_id = hashlib.md5(file_id.encode('utf-8')).hexdigest()
        file_content = blueprint.current_request.raw_body

        # save tmp file
        tmp_file_path = '/tmp/' + file_id
        with open(tmp_file_path, 'wb') as tmp_file:
            tmp_file.write(file_content)

        # check tmp file
        import fleep
        with open(tmp_file_path, 'rb') as tmp_file:
            file_info = fleep.get(tmp_file.read(128))

        types_map = {
            'image/png': 'png',
            'image/jpeg': 'jpg',
            'image/pjpeg': 'jpg',
            'image/bmp': 'bmp',
            'image/x-windows-bmp': 'bmp',
            'image/gif': 'gif',
            'application/pdf': 'pdf',
        }
        if not file_info.mime or file_info.mime[0] not in types_map.keys():
            raise BadRequestError('Mime-type is not supported!')

        # upload
        extension = types_map[file_info.mime[0]]
        destination_key = file_id + '.' + extension
        file_storage.upload(tmp_file_path, destination_key)

        # remove tmp file
        if os.path.isfile(tmp_file_path):
            os.remove(tmp_file_path)

        return {
            'key': destination_key,
        }
Exemplo n.º 27
0
def update_storage(id):
    if generate_random_error():
        return _UNAVAILABLE
    username = get_authorized_username(app.current_request)
    body = app.current_request.json_body
    try:
        get_app_db().update_item(id, data=body['data'], username=username)
    except KeyError as e:
        raise BadRequestError("Unknown parameter, expected %s" % e)
    except TypeError as e:
        raise BadRequestError(e)
    return {'id': id, 'data': body['data']}
Exemplo n.º 28
0
def validate(query_params, param):
    if query_params is None:
        error_message = "Missing query params"
        logging.error(error_message)
        raise BadRequestError(error_message)

    if query_params.get(param) is None or str(
            query_params.get(param)).isspace() or str(
                query_params.get(param)) == "":
        error_message = f'The following query param is missing : {param}'
        logging.error(error_message)
        raise BadRequestError(error_message)
Exemplo n.º 29
0
def add_location_by_beacon_info():
    json_body = app.current_request.json_body
    # Load json data into object
    schema = LocationBeaconSchema()
    location, errors = schema.load(json_body)
    # Invalid JSON body
    if errors:
        raise ChaliceViewError(errors)

    with contextlib.closing(session_factory()) as session:
        try:
            beacon = session.query(Beacon).filter(
                Beacon.uuid == location['uuid'],
                Beacon.major == location['major'],
                Beacon.minor == location['minor']).first()
            if not beacon:
                raise BadRequestError("Invalid beacon id")
            if beacon.status != 1:
                raise BadRequestError("Beacon is disabled")
            missing = session.query(Missing).filter(
                Missing.resident_id == beacon.resident_id,
                Missing.status == 1).first()
            if not missing:
                raise BadRequestError("No active missing case")

            location['beacon_id'] = beacon.id
            location.pop('uuid', None)
            location.pop('major', None)
            location.pop('minor', None)
            location = Location(**location)
            location.resident_id = missing.resident_id
            location.missing_id = missing.id
            session.add(location)

            # Send notification on 1st time found
            if not (missing.latitude and missing.longitude):
                notify_found_missing(db_session=session, missing=missing)

            # Update latest location to missing
            missing.latitude = location.latitude
            missing.longitude = location.longitude
            missing.address = location.address
            session.merge(missing)

            # Call flush() to update id value in missing
            session.flush()
            session.commit()
            schema = LocationSchema(exclude=('user', 'locator', 'resident'))
            return schema.dump(location)
        except exc.SQLAlchemyError as e:
            session.rollback()
            raise ChaliceViewError(str(e))
Exemplo n.º 30
0
def contact():
    # Set these in chalice/__init__.py
    to_email = TO_EMAIL
    from_email = FROM_EMAIL
    site = SITE

    parsed = parse_qs(app.current_request.raw_body)

    # Default to [None] to avoid IndexError
    name = parsed.get('name', [None])[0]
    email = parsed.get('email', [None])[0]
    message = parsed.get('message', [None])[0]

    if not name:
        raise BadRequestError("Please enter your name")
    if not email:
        raise BadRequestError("Please enter your email")
    if not message:
        raise BadRequestError("Please enter your message")

    # Don't send message if it contains words from IGNORE list
    for ignore in IGNORE:
        if ignore in message:
            return {
                "status": "OK",
            }

    client = boto3.client('ses')

    client.send_email(
        Source=from_email,
        Destination={
            'ToAddresses': [to_email],
        },
        Message={
            'Subject': {
                'Data': "Message from " + name + " via " + site,
            },
            'Body': {'Text': {
                'Data': message,
            }},
        },
        # setting the reply-to header makes means that when you hit
        # reply, the email goes to your visitor, not your from_email
        ReplyToAddresses=[email],
    )

    response = {
        "status": "OK",
    }

    return response