Exemplo n.º 1
0
def get_games():
    options = dict()
    if "offset" in request.args:
        options["offset"] = request.args.get("offset", type=int)
    if "count" in request.args:
        options["count"] = request.args.get("count", type=int)

    if ("offset" in options and options["offset"] < 0
            or options.get("count", 0) > constants.values.MAX_ELEMENT_COUNT):
        status = constants.statuses["request"]["badArguments"]
        return (
            jsonify(
                create_error(status,
                             "Offset cann't be negative",
                             offset=options["offset"])),
            constants.responses[status],
        )

    games, status = Storage.get_games(**options)
    http_status = constants.responses[status]
    total_count = Storage.get_games_count()
    count = len(games)
    if len(options) != 0 or count != total_count:
        options["count"] = count
        options["offset"] = options.get("offset", 0)
    return (
        jsonify(games=games, total_count=total_count, status=status,
                **options),
        http_status,
    )
Exemplo n.º 2
0
 def __init__(self,
              serializer: BaseSerializer,
              central_authority: CentralAuthority,
              public_key_scheme: BasePublicKey,
              storage_path: str = None) -> None:
     self.central_authority = central_authority
     self.storage = Storage(serializer, storage_path)
     self.public_key_scheme = public_key_scheme
     self.authorities = dict()  # type: Dict[str, AttributeAuthority]
Exemplo n.º 3
0
def get_game(prod_id=None):
    prod_id = prod_id or request.args.get("id")
    game, status = Storage.get_game(prod_id)
    rating, rt_status = Storage.get_game_rating(prod_id)
    http_status = constants.responses[status]

    if status == constants.statuses["game"]["returned"]:
        body = dict(game=game, rating=rating, status=status)
    else:
        body = create_error(status, "no such game id: {{ID}}", ID=prod_id)
    return jsonify(body), http_status
class StorageUploader(object):

    def __init__(self, config_file='app.ini'):
        self.storage_service = Storage(config_file)

    def upload_files(self, input_dir, extension, now_time):
        """
        ファイル転送
        :param input_dir: input_dir
        :param extension: ext
        :param now_time: timestamp(string)
        :return: None
        """
        self.storage_service.upload_files(input_dir, extension, now_time)
Exemplo n.º 5
0
def patch_score(game_id=None):
    if game_id is None:
        game_id = request.json.get("game_id")
    if game_id is None:
        status = constants.statuses["rating"]["missingData"]
        http_status = constants.responses[status]
        return jsonify(create_error(status, "missing score data")), http_status

    current_app.logger.info(
        f"Updating score by {request.environ['user_email']} and game id {game_id}"
    )

    request.json["user_id"] = request.environ["user_id"]
    request.json["game_id"] = game_id

    score, status = Storage.update_score(request.json, request.method)
    http_status = constants.responses[status]

    if status == constants.statuses["rating"]["modified"]:
        body = dict(score=score, status=status)
    elif status == constants.statuses["rating"]["notExists"]:
        body = create_error(status, "no such score")
    elif status == constants.statuses["rating"]["missingData"]:
        body = create_error(status, "missing score data")
    else:  # status == constants.statuses["rating"]["replacingData"]:
        body = create_error(status, "replacing score IDs")
    return jsonify(body), http_status
Exemplo n.º 6
0
def delete_all_games():
    current_app.logger.info(
        f"Deleting all games by {request.environ['user_email']}")

    count, status = Storage.delete_all_games()
    http_status = constants.responses[status]

    return jsonify(dict(deleted=count, status=status)), http_status
Exemplo n.º 7
0
def get_game_rating(game_id):
    game, status = Storage.get_game_rating(game_id)
    http_status = constants.responses[status]

    if status == constants.statuses["rating"]["returned"]:
        body = dict(rating=game, status=status)
    else:
        body = create_error(status, "no such game id: {{ID}}", ID=game_id)
    return jsonify(body), http_status
Exemplo n.º 8
0
def delete_game(prod_id=None):
    prod_id = prod_id or request.args.get("id")
    current_app.logger.info(
        f"Deleting game by {request.environ['user_email']} and game id {prod_id}"
    )

    game, status = Storage.delete_game(prod_id)
    http_status = constants.responses[status]

    if status == constants.statuses["game"]["deleted"]:
        body = dict(game=game, status=status)
    else:
        body = create_error(status, "no such game id: {{ID}}", ID=prod_id)
    return jsonify(body), http_status
Exemplo n.º 9
0
def add_game():
    current_app.logger.info(f"Creating game by {request.environ['user_email']}")

    new_id, status = Storage.add_game(**request.json)
    http_status = constants.responses[status]

    if status == constants.statuses["game"]["created"]:
        body = dict(id=new_id, status=status)
    elif status == constants.statuses["game"]["missingData"]:
        body = create_error(status, "missing game data")
    elif status == constants.statuses["game"]["extraFields"]:
        body = create_error(status, "Extra fields in data")
    else:  # status == constants.statuses["game"]["invalidData"]:
        body = create_error(status, "Game data is invalid")
    return jsonify(body), http_status
Exemplo n.º 10
0
def delete_score(game_id=None):
    current_app.logger.info(
        f"Deleting score by {request.environ['user_email']} and game id {game_id}"
    )

    game, status = Storage.delete_score(game_id, request.environ["user_id"])
    http_status = constants.responses[status]

    if status == constants.statuses["rating"]["deleted"]:
        body = dict(game=game, status=status)
    else:  # status == constants.statuses["rating"]["notExists"]:
        body = create_error(status,
                            "no your score for game id: {{ID}}",
                            ID=game_id)
    return jsonify(body), http_status
Exemplo n.º 11
0
def get_user_scores(user_id=None):
    if user_id is None:
        user_id = request.environ.get("user_id")
    if user_id is None:
        return (
            jsonify(
                create_error(
                    constants.statuses["user"]["unauthorized"], "No token detected"
                )
            ),
            constants.common_responses["No auth"],
        )
    scores, status = Storage.get_user_scores(user_id=user_id)
    http_status = constants.responses[status]
    return jsonify(scores=scores, status=status), http_status
Exemplo n.º 12
0
def patch_game(prod_id=None):
    prod_id = prod_id or request.args.get("id")
    current_app.logger.info(
        f"Updating game by {request.environ['user_email']} and game id {prod_id}"
    )

    game, status = Storage.update_game(prod_id, request.method, **request.json)
    http_status = constants.responses[status]

    if status == constants.statuses["game"]["modified"]:
        body = dict(game=game, status=status)
    elif status == constants.statuses["game"]["notExists"]:
        body = create_error(status, "no such game id: {{ID}}", ID=prod_id)
    elif status == constants.statuses["game"]["missingData"]:
        body = create_error(status, "missing game data")
    elif status == constants.statuses["game"]["extraFields"]:
        body = create_error(status, "Extra fields in data")
    elif status == constants.statuses["game"]["invalidData"]:
        body = create_error(status, "Game data is invalid")
    else:  # status == constants.statuses["game"]["replacingData"]:
        body = create_error(status, "replacing game ID")
    return jsonify(body), http_status
Exemplo n.º 13
0
def add_score():
    current_app.logger.info(
        f"Add score to game {request.json.get('game_id')} by {request.environ['user_email']}"
    )

    request.json["user_id"] = request.environ["user_id"]
    score, status = Storage.add_score(request.json)
    http_status = constants.responses[status]

    if status == constants.statuses["rating"]["created"]:
        body = dict(score=score, status=status)
    elif status == constants.statuses["rating"]["missingData"]:
        body = create_error(status, "missing score data")
    elif status == constants.statuses["rating"]["extraFields"]:
        body = create_error(status, "Extra fields in data")
    elif status == constants.statuses["rating"]["invalidData"]:
        body = create_error(status, "Rating data is invalid")
    else:  # status == constants.statuses["rating"]["invalidGameId"]:
        body = create_error(status,
                            "No game with such {{id}}",
                            id=request.json.get("game_id"))
    return jsonify(body), http_status
Exemplo n.º 14
0
class InsuranceService(object):
    """
    The insurance service is the main portal for the clients and is responsible for validating
    signatures and storing the data records.
    """
    def __init__(self,
                 serializer: BaseSerializer,
                 central_authority: CentralAuthority,
                 public_key_scheme: BasePublicKey,
                 storage_path: str = None) -> None:
        self.central_authority = central_authority
        self.storage = Storage(serializer, storage_path)
        self.public_key_scheme = public_key_scheme
        self.authorities = dict()  # type: Dict[str, AttributeAuthority]

    @property
    def global_parameters(self):
        return self.central_authority.global_parameters

    def add_authority(self, attribute_authority: AttributeAuthority):
        """
        Add an attribute authority.
        :param attribute_authority: The attribute authority to add.
        """
        self.authorities[attribute_authority.name] = attribute_authority

    def create(self, create_record: CreateRecord) -> str:
        """
        Create a new data record
        :param create_record: The data record to create.
        :return: The location of the record.
        """
        # In future possibly adapt and check the record

        location = InsuranceService.determine_record_location(create_record)
        self.storage.store(location, create_record)
        return location

    def update(self, location: str, update_record: UpdateRecord):
        """
        Update the data on the given location
        :param location: The location of the record to update the data of
        :param update_record: The UpdateRecord containing the updated data
        """
        current_record = self.load(location)
        assert current_record is not None, 'Only existing records can be updated'
        assert self.public_key_scheme.verify(
            current_record.write_public_key, update_record.signature,
            update_record.data), 'Signature should be valid'
        current_record.update(update_record)
        self.storage.store(location, current_record)

    def policy_update(self, location: str,
                      policy_update_record: PolicyUpdateRecord):
        """
        Update the data on the given location
        :param location: The location of the record to update the policies of
        :param policy_update_record: The PolicyUpdateRecord containing the updated policies
        """
        current_record = self.load(location)
        assert current_record is not None, 'Only existing records can be updated'
        assert self.public_key_scheme.verify(
            current_record.owner_public_key, policy_update_record.signature,
            pickle.dumps((policy_update_record.read_policy,
                          policy_update_record.write_policy,
                          policy_update_record.time_period
                          ))), 'Signature should be valid'
        current_record.update_policy(policy_update_record)
        self.storage.store(location, current_record)

    @staticmethod
    def determine_record_location(record: DataRecord) -> str:
        """
        Determine a unique location for a data record
        :param record: The data record
        :type record: records.data_record.DataRecord
        :return: A unique location
        """
        return SHA.new(record.info).hexdigest()

    def load(self, location: str) -> DataRecord:
        return self.storage.load(location)
 def __init__(self, config_file='app.ini'):
     self.storage_service = Storage(config_file)