예제 #1
0
def get_rules(valid_users_list, valid_teams_list):
    # Audit log attributes needs to meet the following rules.
    rules = {
        constant.USER_ATTRIBUTE: [Required, In(valid_users_list), Length(5, maximum=100)],
        constant.TEAM_ATTRIBUTE: [Required, In(valid_teams_list), Length(5, maximum=100)],
        constant.COMPONENT_ATTRIBUTE:[Required, Length(5, maximum=100), Pattern(name_regex)],
        constant.SUB_COMPONENT_ATTRIBUTE:[Required, Length(5, maximum=100), Pattern(name_regex)]
    }

    return rules
예제 #2
0
def paramsvalidator(payload):
    rules = {
        "name": [InstanceOf(str)],
        "uuid": [
            If(
                InstanceOf(str),
                Then(
                    Pattern(
                        "\w\w\w\w\w\w\w\w-\w\w\w\w-\w\w\w\w-\w\w\w\w-\w\w\w\w\w\w\w\w\w\w\w\w"
                    )))
        ],  # Example UUID = 8243c413-2575-461e-87e8-5f203c611223 
        "rarity": [
            If(InstanceOf(str),
               Then(In(["Epic", "Legendary", "Rare", "Uncommon", "Common"])))
        ],
        "hex_type":
        [If(InstanceOf(str), Then(In(["Card", "Equipment", "Pack"])))],
        "hex_set": [
            If(
                InstanceOf(str),
                Then(
                    In([
                        "AI Only Cards", "Armies of Myth", "AZ1", "AZ2",
                        "Dead of Winter", "Frostheart",
                        "Frostheart Core Commons", "Herofall", "Primal Dawn",
                        "PvE 01 Universal Card Set", "Scars of War",
                        "Set01 Kickstarter", "Set01 PvE Arena",
                        "Set01 PvE Holiday", "Set03 PvE Promo",
                        "Set04 PvE Promo", "Set05 PvE Promo",
                        "Set06 PvE Promo", "Set07 PvE Promo",
                        "Set08 PvE Promo", "Shards of Fate",
                        "Shattered Destiny"
                    ])))
        ],
        "limit":
        [If(InstanceOf(int), Then(InstanceOf(int)))
         ],  # teger - Limits the quantity of returned results (default: 25)
        "offset":
        [If(InstanceOf(int), Then(InstanceOf(int)))
         ],  #Integer - Skips offset articles before returning (default: 0) 
        "contains": [If(InstanceOf(str), Then(InstanceOf(bool)))],
        "currency": [If(InstanceOf(str),
                        Then(In(["Gold", "Platinum"])))],  # In Game currency
        "start": [
            Pattern("\d\d\d\d-\d\d-\d\d")
        ],  # String - A valid date representation, such as "2016-01-01" (default: the date for the time of the request in CET timezone - 31 days)
        "end": [
            Pattern("\d\d\d\d-\d\d-\d\d")
        ]  # String - same as above (default: the date of the time of the request in CET timezone)
    }

    results = validate(rules, payload)
    return results.valid
예제 #3
0
    def is_ws_msg_valid(self, from_user_id, data):
        obj = json.loads(data)
        if 'type' not in obj:
            LOG.error("user {0} ###is_ws_msg_valid### type is not existed".format(self.client_id))
            return False
        rules = {
            "target": [Required, Pattern('[\S]{1,300}')],
            "payload": [Required, Pattern('[\s]{0,}[\S]{1,}')],
            "type": [In(["txt", "audio", "img"])]
        }
        if obj['type'] == 'img':
            rules.update({
                "width": [Range(1, 10000)],
                "height": [Range(1, 10000)],
            })
        validate_result = validate(rules, obj)
        if not validate_result.valid:
            LOG.error("user {0} ###is_ws_msg_valid #### msg format is not valid, {1}".format(self.client_id, obj))
            return False

        if obj['target']:
            try:
                t = obj['target'].split(':')
                if t[0] == 'user':
                    # check target user is friend
                    user_key = "{0}:friendlist".format(from_user_id)
                    f = self.r.zscan(user_key, 0, t[1], 1)
                    if not f and len(f[1]) == 0:
                        LOG.error("user {0} ###is_ws_msg_valid###sender and receiver is not friend.".format(
                            self.client_id))
                        return False
                elif t[0] == 'room':
                    # check is member of group
                    room_key = "room:{0}".format(t[1])
                    f = self.r.sscan_iter(room_key, from_user_id, 1)
                    if not f and len(f[1]) == 0:
                        LOG.error("user {0} ###is_ws_msg_valid###sender is not member of group".format(self.client_id))
                        return False
                else:
                    LOG.error("user {0} ###is_ws_msg_valid### target is not correct".format(self.client_id))
                    return False
            except ValueError:
                LOG.error("user {0} ###is_ws_msg_valid### target content error".format(self.client_id))
                return False
        else:
            LOG.error("user {0} ###is_ws_msg_valid### target is not exist".format(self.client_id))
            return False

        return True
예제 #4
0
def validate_item(item,sources=None,verbose=True):
    '''validate_item will validate a single item objects, intended to go in as a field to
    a POST. For more than one item, use validate_items wrapper
    :param item: the item object. Must include the following:
    :param sources: a list of valid item sources (eg ["pacs"])
    :param verbose: if True, prints out valid True messages. False (errors) always printed

    :: notes

    {
        # generic attribute/values just to store, not interpreted
        "id":"123123123123123", // mandatory

        # the issuer for the above id
        # mandatory, or maybe optional with default of "stanford" or "unspecified"
        "id_source":"pacs",

        # when the id was looked up, to help with changed/merged ids
        # optional with default of current timestamp?
        "id_timestamp":"2016-01-30T17:15:23.123Z",

        # optional key/value attributes, will be stored as-is if provided, but not used or interpreted
        # values will be updated/replaced if sent multiple times (last received wins)
        # any existing values will be preserved if not explicitly set here; set empty string to remove
        "custom_fields":{
          "image_type":"x-ray",
          "resolution":"high"
    }
    '''
    if sources == None:
        sources = item_sources

    # These are the rules for an item
    rules = {
        "id": [Required, Pattern("^[A-Za-z0-9_-]*$")], # pattern
        "id_source": [Required, In(sources)],      # must be in item sources
        "id_timestamp": [Required,Pattern(timestamp)], 
    }

    valid,message = validate(rules, item)
    if verbose == True:
        bot.debug("identifier %s data structure valid: %s" %(item['id'],valid))
    if valid == False:
        bot.error(message)
        if verbose == True:
            print(item)
    return valid
예제 #5
0
def receive_items(items):
    '''receive items will validate reception of an items list.
    :param items: the items list from a response

     HTTP 200

        'items': [
                   {
                    'id_source': 'GE PACS', 
                    'jittered_timestamp': '2016-01-15T17:15:23.123Z', 
                    'id': 'A654321', 
                    'suid': '103e'
                    }
         ]

    '''
    expected_fields = [
        'id_source', 'jittered_timestamp', 'suid', 'id', 'custom_fields'
    ]

    if not isinstance(items, list):
        bot.error("Items must be a list")
        return False

    # These are the rules for each uidEntity
    rules = {
        "id": [Required, Pattern("^[A-Za-z0-9_-]*$")],  # pattern
        "suid": [Required, Pattern("^[A-Za-z0-9_-]*$")],  # the suid
        "id_source": [Required, In(item_sources)],  # must be in person sources
        "jittered_timestamp": [Required, Pattern(timestamp)]
    }

    for item in items:

        # Validate required fields
        valid, message = validate(rules, item)
        if valid == False:
            bot.error(message)
            return valid

        # Validate fields returned in response
        if not validate_fields(expected_fields, item.keys()):
            return False

    return valid
def get_rules(valid_users_list, valid_teams_list, valid_component_list,
              valid_sub_component_list):
    # Audit log attributes needs to meet the following rules.
    rules = {
        constant.USER_ATTRIBUTE: [Required, In(valid_teams_list)],
        constant.TEAM_ATTRIBUTE: [Required, In(valid_users_list)],
        constant.COMPONENT_ATTRIBUTE: [Required,
                                       In(valid_sub_component_list)],
        constant.SUB_COMPONENT_ATTRIBUTE: [
            Required,
            Pattern(alpha_numeric_regex),
            Not(In(valid_component_list))
        ]
    }

    return rules
예제 #7
0
def validate_identifiers(identifiers,id_sources=None,item_sources=None,verbose=True):
    '''validate_identifiers will validate one or more identifier objects, 
    intended to go in as a field to a POST
    :param identifiers: the identifiers object.
    :param verbose: verbose output for items
    :param identifier_sources: a list of one or more identifier sources. 
    :param item_sources: a list of one or more item sources
    If either not defined, default to use standards

    :: notes
       {
        # mandatory key for uniquely identifying the person
        "id":"1234567-8",
       
        # the issuer for the above id
        # mandatory, or maybe optional with default of "stanford" or "unspecified"
        
        "id_source":"stanford",
        # when the id was looked up, to help with changed/merged ids
        # optional with default of current timestamp?
        
        "id_timestamp":"2016-01-30T17:15:23.123Z",
        # optional key/value attributes, will be stored as-is if provided, but not used or interpreted
        # values will be updated/replaced if sent multiple times (last received wins)
        # any existing values will be preserved if not explicitly set here; set empty string to remove
        
        "custom_fields":{
          "first_name":"Joe",
          "last_name":"Smith",
          "dob":"1970-02-28"
        }
    '''
    if id_sources == None:
        id_sources = identifier_sources

    # These are the rules for a person
    rules = {
        "id": [Required, Pattern("^[A-Za-z0-9_-]*$")], # pattern
        "id_source": [Required, In(id_sources)],   # must be in person sources
        "id_timestamp": [Required,Pattern(timestamp)], 
    }

    if not isinstance(identifiers,dict):
        bot.error("Identifiers data structure must be dictionary.")
        return False

    if "identifiers" not in identifiers:
        bot.error("identifiers key not found in data structure.")

    items = identifiers['identifiers']

    if not isinstance(items,list):
        bot.error("Items in identifiers data structure must be list.")
        return False  

    for item in items:

        valid,message = validate(rules, item)
        if valid == False:
            bot.error(message)
            return valid

        if "items" in item:
            validate_items(item['items'],sources=item_sources)

    bot.debug("Identifiers data structure valid: %s" %valid)
    return valid
예제 #8
0
 def test_validator_errors_returns_false(self):
     email_validator = Validator()
     email_validator.validate({'id': [Required, Pattern(r'\d+')]})
     assert email_validator.check({'id': '4'}) is True
     assert email_validator.errors() is None
예제 #9
0
 def test_validator_check_matches_without_request(self):
     email_validator = Validator()
     email_validator.validate({'id': [Required, Pattern(r'\d+')]})
     assert email_validator.check({'id': '4'}) is True
예제 #10
0
 def test_validator_check_matches(self):
     email_validator = Validator(self.request)
     email_validator.validate({'id': [Required, Pattern(r'\d+')]})
     assert email_validator.check() is True
예제 #11
0
 def test_validator_check_does_not_match(self):
     email_validator = Validator(self.request)
     email_validator.validate({'id': [Required, Pattern('[a-zA-Z]')]})
     assert email_validator.check() is False
예제 #12
0
import json
'''
Equals, Truthy,  Range(1, 11),Pattern("\d\d\%"), In([]), Not(In([])
InstanceOf, SubclassOf,  [Length(0, maximum=5)], url, GreaterThan, LessThan
https://validatorpy.readthedocs.io/en/latest/index.html
'''
rules = {
    "test": {
        "POST": {
            "ab": [Required, InstanceOf(str)],
            "id": [Required, InstanceOf(int)]
        }
    },
    "reg": {
        "POST": {
            "name": [Required, Pattern(r"\w+")],
            "password": [Required,
                         InstanceOf(str),
                         Length(6, maximum=30)],
        }
    },
    "login": {
        "GET": {
            "name": [Required, Pattern(r"\w+")],
            "password": [Required,
                         InstanceOf(str),
                         Length(6, maximum=30)],
        }
    },
    "vote/add": {
        "POST": {
예제 #13
0
def receive_identifiers(response):
    '''receive identifiers will validate reception of an identifiers response.
    This should be a list
    :param response: the response list of identifiers

    :: notes
     successful response:

     HTTP 200

    [
       {'jittered_timestamp': '2016-01-30T17:15:23.123Z', 
        'id': '12345678', 
        'suid': '103e', 
        'id_source': 'Stanford MRN', 
        'custom_fields': [
             {'key': 'studySiteID', 'value': '78329'}], 
        'items': [
                   {
                    'id_source': 'GE PACS', 
                    'jittered_timestamp': '2016-01-15T17:15:23.123Z', 
                    'id': 'A654321', 
                    'suid': '103e'}
                   ]}

    ]

    '''
    # These fields are expected, but not required. We will error
    # if any fields are present outside this scope
    expected_fields = [
        'items', 'id_source', 'jittered_timestamp', 'suid', 'id',
        'custom_fields'
    ]

    if not isinstance(response, list):
        bot.error("Response must be a list")
        return False

    # These are the rules for each uidEntity
    rules = {
        "id": [Required, Pattern("^[A-Za-z0-9_-]*$")],  # pattern
        "suid": [Required, Pattern("^[A-Za-z0-9_-]*$")],  # the suid
        "id_source": [Required,
                      In(identifier_sources)],  # must be in identifer sources
        "jittered_timestamp": [Required, Pattern(timestamp)]
    }

    for item in response:

        # Validate required fields
        valid, message = validate(rules, item)
        if valid == False:
            bot.error(message)
            return valid

        # Validate fields returned in response
        if not validate_fields(expected_fields, item.keys()):
            return False

        # Validate items
        if "items" in item:
            if not receive_items(item['items']):
                return False

    bot.debug("Identifiers data structure valid: %s" % valid)
    return valid
예제 #14
0
def test_validator_check_matches():
    email_validator = Validator(REQUEST)
    email_validator.validate({'id': [Required, Pattern(r'\d+')]})
    assert email_validator.check() is True
예제 #15
0
 def validate_resolver(data):
     rules = {
         "resolver_name": [Required, Pattern('^\S*$')],
         "nameserver_address": [Required, ValidHost()]
     }
     return validate(rules, data)