Beispiel #1
0
def get_available_sensors():
    headers = request.headers or {}

    # Check request
    if 'Authorization' not in headers:
        return bad_request("Missing 'Authorization' header in request")

    # Parse auth
    try:
        login, password = parse_authorization_header(
            headers.get('Authorization'))
    except Exception as e:
        return server_error(
            f"Exception occurred during parsing user credentials: {str(e)}")

    try:
        user = User.query.filter_by(login=login).first()
    except Exception as e:
        return server_error(
            f"Exception occurred during loading user: {str(e)}")

    if user and authorize(login, password, user):
        sensors = Sensor.query.filter_by(token=user.token).all()
        return create_response_from_data_with_code(
            [x.serial_number for x in sensors], 200)
    else:
        return unauthorized(login)
Beispiel #2
0
def get_flower_active_recommendations(id):
    logging.info("Called getting flower recommendations endpoint ...")

    headers = request.headers or {}
    alarms = list()

    # Check request
    if 'Authorization' not in headers:
        return bad_request("Missing 'Authorization' header in request")

    # Parse auth
    try:
        login, password = parse_authorization_header(
            headers.get('Authorization'))
    except Exception as e:
        return server_error(
            f"Exception occurred during parsing user credentials: {str(e)}")

    try:
        user = User.query.filter_by(login=login).first()
    except Exception as e:
        return server_error(
            f"Exception occurred during loading user: {str(e)}")

    if user and authorize(login, password, user):
        return create_response_from_data_with_code(
            _get_alarms_for_flower(user, id, 2), 200)
    else:
        return unauthorized(login)
Beispiel #3
0
def get_flower_by_id(id):
    """ Return list of user flowers """
    logging.info("Called getting flowers endpoint ...")

    headers = request.headers or {}

    # Check request
    if 'Authorization' not in headers:
        return bad_request("Missing 'Authorization' header in request")

    # Parse auth
    try:
        login, password = parse_authorization_header(
            headers.get('Authorization'))
    except Exception as e:
        return server_error(
            f"Exception occurred during parsing user credentials: {str(e)}")

    try:
        user = User.query.filter_by(login=login).first()
    except Exception as e:
        return server_error(
            f"Exception occurred during loading user: {str(e)}")

    if user and authorize(login, password, user):
        flower = user.flowers.filter_by(id=id).first()
        resp_data = flower.to_dict() or {}
        resp_data['recommendations'] = _get_alarms_for_flower(user, id, 2)
        resp_data['warnings'] = _get_alarms_for_flower(user, id, 1)
        resp_data['problems'] = _get_alarms_for_flower(user, id, 0)
        return create_response_from_data_with_code(resp_data, 200)
    else:
        return unauthorized(login)
def create_user_or_return_token():
    """ Create user and return it's token if user doesn't exists otherwise return user token """
    resp_data = {}  # response data
    headers = request.headers or {}

    # Check request
    if 'Authorization' not in headers:
        return bad_request("Missing 'Authorization' header in request")

    # Parse auth
    try:
        login, password = parse_authorization_header(headers.get('Authorization'))
    except Exception as e:
        return server_error(f"Exception occurred during parsing user credentials: {str(e)}")

    try:
        user = User.query.filter_by(login=login).first()
    except Exception as e:
        return server_error(f"Exception occurred during loading user: {str(e)}")

    # Return token if user already exists
    if user:
        # Check credentials
        try:
            if authorize(login, password, user):
                resp_data['token'] = user.token
                resp = create_response_from_data_with_code(resp_data, 200)
            else:
                return unauthorized(login)
        except Exception as e:
            return server_error(f"Exception occurred during authorization: {str(e)}")
    else:
        # Create user
        user = User()
        user.login = login
        user.password_hash = user.generate_password_hash(password)
        user.token = user.generate_token()
        resp_data['token'] = user.token

        # Commit changes to db
        db.session.add(user)
        db.session.commit()

        resp = create_response_from_data_with_code(resp_data, 200)

    return resp
Beispiel #5
0
def create_flower():
    """ Create flower if it doesn't exists """
    logging.info("Called creating flower endpoint ...")

    headers = request.headers or {}

    # Check request
    if 'Authorization' not in headers:
        return bad_request("Missing 'Authorization' header in request")

    # Parse auth
    try:
        login, password = parse_authorization_header(
            headers.get('Authorization'))
    except Exception as e:
        return server_error(
            f"Exception occurred during parsing user credentials: {str(e)}")

    try:
        user = User.query.filter_by(login=login).first()
    except Exception as e:
        return server_error(
            f"Exception occurred during loading user: {str(e)}")

    if user and authorize(login, password, user):
        data = request.get_json() or {}
        logging.info(data)
        if 'name' not in data or 'type' not in data or 'sensor' not in data:
            return bad_request(
                f"Request must includes name, sensor and type fields. Request: "
                f"{data}")

        if Flower.query.filter_by(name=data.get('name')).first():
            return error_response(
                500, f"Flower with name {data.get('name')} already exists for "
                f"user {login}")

        sensor = Sensor.query.filter_by(
            serial_number=data.get('sensor')).first()

        if not sensor or sensor.token != user.token:
            bad_request("Incorrect sensor serial number")

        flower = Flower()
        flower.name = data.get('name')
        flower.flower_type = data.get('type')
        flower.user = user.id
        flower.sensor = sensor.id
        flower.last_transplantation_year = data.get('last_transplantation_year') or \
                                           datetime.datetime.now().year

        # Commit changes to db
        db.session.add(flower)
        db.session.commit()

        for recommendation_class in recommendation_classes():
            recom = RecommendationItem()
            recom.r_class = recommendation_class.__name__
            recom.flower = flower.id

            db.session.add(recom)
            db.session.commit()

            RecommendationBackGroundTask(
                recommendation_class.create_from_db(t_id=recom.id,
                                                    flower=flower))

        resp_data = flower.to_dict()
        resp_data['recommendations'] = _get_alarms_for_flower(user, id, 2)
        resp_data['warnings'] = _get_alarms_for_flower(user, id, 1)
        resp_data['problems'] = _get_alarms_for_flower(user, id, 0)
        return create_response_from_data_with_code(resp_data, 201)
    else:
        return unauthorized(login)