Ejemplo n.º 1
0
def st():
    client = create_client()
    storage = MongoStorage(client, DB_NAME, collection=COLLECTION)
    for policy_json in POLICIES:
        storage.add(Policy.from_json(policy_json))
    yield storage
    client[DB_NAME][COLLECTION].drop()
    client.close()
Ejemplo n.º 2
0
def add_policy_to_storage(policy: dict, location: str) -> bool:
    #json = request.get_json()
    policy = Policy.from_json(policy)
    client = MongoClient()
    storage = MongoStorage(client, db_name=location)
    try:
        storage.add(policy)
    except:
        return False
    return True
Ejemplo n.º 3
0
 def migration_set(self):
     client = create_client()
     storage = MongoStorage(client, DB_NAME, collection=COLLECTION)
     yield MongoMigrationSet(storage, MIGRATION_COLLECTION)
     client[DB_NAME][COLLECTION].drop()
     client[DB_NAME][MIGRATION_COLLECTION].drop()
     client.close()
Ejemplo n.º 4
0
def st():
    client = create_client()
    storage = MongoStorage(client, DB_NAME, collection=COLLECTION)
    migration_set = MongoMigrationSet(storage)
    migration_set.up()
    yield storage
    migration_set.down()
    client[DB_NAME][COLLECTION].delete_many({})
    client.close()
Ejemplo n.º 5
0
def policy_attr_auth():
    if not is_json_request(request, ["thing_id", "thing_type", "action"]):
        return jsonify(ERROR_JSON), 400

    request_json = request.get_json()
    thing_id = request_json['thing_id']
    policy_location = request_json['location']

    client = MongoClient()
    storage = MongoStorage(client, db_name=policy_location)
    add_user_scope = []
    add_server_scope = []
    add_user_scope_str = ""
    add_server_scope_str = ""
    for p in storage.get_for_target("", str(thing_id), ""):
        subject_rules = get_attr_list(p.rules.subject)
        context_rules = get_attr_list(p.rules.context)
        print("[API] (policy_attr_auth)")
        auth_attributes = get_auth_attributes()
        auth_user_attributes = auth_attributes[0]
        auth_server_attributes = auth_attributes[1]
        # initialize user attributes from profile info, if already exists
        if not auth_user_attributes["address"]:
            set_auth_user_attr("address", user.get_address())
        if not auth_user_attributes["phone_number"]:
            set_auth_user_attr("phone_number", user.get_phone())
        add_user_scope_str = get_auth_scopes(add_user_scope, subject_rules,
                                             auth_user_attributes)
        add_server_scope_str = get_auth_scopes(add_server_scope, context_rules,
                                               auth_server_attributes)
    print("add_user_scope_str: ", add_user_scope_str)
    print("add_server_scope_str: ", add_server_scope_str)

    # authorize and access the required attributes
    if len(add_user_scope_str) > 0 or len(add_server_scope_str) > 0:
        # initialize 'info_authorize' to zero to indicate authorization not yet started
        session['info_authorize'] = 0
        # pass scopes by session
        session['add_user_scope'] = add_user_scope_str
        session['add_server_scope'] = add_server_scope_str
        return url_for("auth.info_authorize"), 300

    return make_response("Request Succeed", 200)
Ejemplo n.º 6
0
def delete_policy_from_storage(request: flask.Request) -> bool:
    """Delete a policy from storage. 

    Args:
        The function uses HTTP request directly. These argument must be contained in the request:
        uid (str): uid of the policy
        location (str): location the policy is stored

    Returns:
        True if the removal is successful. 

    """
    request_json = request.get_json()
    uid = request_json['uid']
    location = request_json['location']
    client = MongoClient()
    storage = MongoStorage(client, db_name=location)
    storage.delete(uid)
    return True
Ejemplo n.º 7
0
 def storage(self):
     client = create_client()
     yield MongoStorage(client, DB_NAME, collection=COLLECTION)
     client[DB_NAME][COLLECTION].drop()
     client.close()
Ejemplo n.º 8
0
def st():
    client = create_client()
    storage = MongoStorage(client, DB_NAME, collection=COLLECTION)
    yield storage
    client[DB_NAME][COLLECTION].delete_many({})
    client.close()
Ejemplo n.º 9
0
def is_request_allowed(request: flask.Request) -> bool:
    """Check whether a request is allowed or not. 
    Attributes are retrieved by the attribute providers and in order of the providers. 

    Args:
        request (JSON): request to the thing with identifications about the thing

    Returns:
        1/0 (int): indicating a request is allowed or not

    """
    class ThingAttributeProvider(AttributeProvider):
        def get_attribute_value(self, ace, attribute_path, ctx):
            if ace == "resource" and attribute_path == "$.thing_type":
                thing_type = request.get_json().get("thing_type", None)
                print("(ThingAttributeProvider) thing_type: ", thing_type)
                return thing_type
            return None

    class UserIdAttributeProvider(AttributeProvider):
        def get_attribute_value(self, ace, attribute_path, ctx):
            if not current_user:
                return None
            if ace == "subject" and attribute_path == "$.id":
                return current_user.get_user_id()
            return None

    class EmailAttributeProvider(AttributeProvider):
        def get_attribute_value(self, ace, attribute_path, ctx):
            user_id = ctx.get_attribute_value("subject", "$.id")
            if not user_id:
                return None
            if ace == "subject" and attribute_path == "$.email":
                user = User.query.filter_by(id=user_id).first()
                user_email = user.get_email()
                return user_email
            return None

    class TimestampAttributeProvider(AttributeProvider):
        def get_attribute_value(self, ace, attribute_path, ctx):
            print(f"accessed 1, timestamp")
            if attribute_path == "$.timestamp":
                print(
                    f"accessed, current timestamp:{datetime.now().timestamp()}"
                )
                return datetime.now().timestamp()
            return None

    class OtherAttributeProvider(AttributeProvider):
        def get_attribute_value(self, ace: str, attribute_path: str, ctx):
            # Assume attribute_path is in the form "$.attribute_name"
            attr_name = re.search("[a-zA-Z_]+", attribute_path).group().lower()
            print("attribute_path: ", attribute_path)
            print("attr_name: ", attr_name)
            auth_attributes = get_auth_attributes()
            auth_user_attributes = auth_attributes[0]
            auth_server_attributes = auth_attributes[1]
            attr_value = auth_user_attributes.get(
                attr_name, None) or auth_server_attributes.get(
                    attr_name, None)
            print("attr_value: ", attr_value)
            return attr_value

    request_json = request.get_json()
    thing_id = request_json['thing_id']
    policy_location = request_json['location']

    client = MongoClient()
    storage = MongoStorage(client, db_name=policy_location)
    pdp = PDP(storage, EvaluationAlgorithm.HIGHEST_PRIORITY, [
        ThingAttributeProvider(),
        EmailAttributeProvider(),
        UserIdAttributeProvider(),
        TimestampAttributeProvider(),
        OtherAttributeProvider()
    ])

    access_request_json = {
        "subject": {
            "id": '',
            "attributes": {}
        },
        "resource": {
            "id": str(thing_id),
            "attributes": {}
        },
        "action": {
            "id": "",
            "attributes": {
                "method": "get"
            }
        },
        "context": {
            "timestamp": {}
        }
    }

    access_request = AccessRequest.from_json(access_request_json)
    if pdp.is_allowed(access_request):
        return 1
    else:
        return 0
Ejemplo n.º 10
0
 def storage(self, client):
     yield MongoStorage(client, DB_NAME, collection=COLLECTION)
     client[DB_NAME][COLLECTION].drop()
     client.close()