Exemplo n.º 1
0
class PermissionViewRoleModel(PermissionViewRoleBaseModel):
    # TODO: trace the user that modifies the permissions
    __tablename__ = "permission_view"
    __table_args__ = {"extend_existing": True}

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    action_id = db.Column(db.Integer, db.ForeignKey("actions.id"), nullable=False)
    action = db.relationship("ActionModel", viewonly=True)

    api_view_id = db.Column(db.Integer, db.ForeignKey("api_view.id"), nullable=False)
    api_view = db.relationship("ApiViewModel", viewonly=True)

    role_id = db.Column(db.Integer, db.ForeignKey("roles.id"), nullable=False)
    role = db.relationship("RoleModel", viewonly=True)

    def __init__(self, data):
        super().__init__(data)
        self.action_id = data.get("action_id")
        self.api_view_id = data.get("api_view_id")
        self.role_id = data.get("role_id")

    @classmethod
    def get_permission(cls, **kwargs):
        permission = cls.query.filter_by(deleted_at=None, **kwargs).first()
        if permission is not None:
            return True
        else:
            return False

    def __repr__(self):
        return f"<Permission role: {self.role_id}, action: {self.action_id}, view: {self.api_view_id}>"
Exemplo n.º 2
0
class PermissionsDAG(TraceAttributesModel):
    __tablename__ = "permission_dag"
    __table_args__ = (
        {"extend_existing": True},
        # db.UniqueConstraint("dag_id", "user_id"),
    )

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    dag_id = db.Column(
        db.String(128), db.ForeignKey("deployed_dags.id"), nullable=False
    )
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    user = db.relationship("UserModel", viewonly=True)

    def __init__(self, data):
        super().__init__()
        self.dag_id = data.get("dag_id")
        self.user_id = data.get("user_id")

    def __repr__(self):
        return f"<DAG permission user: {self.user_id}, DAG: {self.dag_id}<"

    @classmethod
    def get_user_dag_permissions(cls, user_id):
        return cls.query.filter_by(user_id=user_id).all()

    @staticmethod
    def add_all_permissions_to_user(user_id):
        dags = DeployedDAG.get_all_objects()
        permissions = [
            PermissionsDAG({"dag_id": dag.id, "user_id": user_id}) for dag in dags
        ]
        for permission in permissions:
            permission.save()

    @staticmethod
    def delete_all_permissions_from_user(user_id):
        permissions = PermissionsDAG.get_user_dag_permissions(user_id)
        for perm in permissions:
            perm.delete()

    @staticmethod
    def check_if_has_permissions(user_id, dag_id):
        permission = PermissionsDAG.query.filter_by(
            user_id=user_id, dag_id=dag_id
        ).first()
        if permission is None:
            return False
        return True
Exemplo n.º 3
0
 def user_id(self):
     return db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
Exemplo n.º 4
0
class PermissionViewRoleBaseModel(TraceAttributesModel):
    """
    This model has the permissions that can be defined between an action, a view and a role
    It inherits from :class:`TraceAttributesModel` to have trace fields

    The :class:`PermissionViewRoleBaseModel` has the following fields:

    - **id**: int, the primary key of the table, an integer value that is auto incremented
    - **action_id**: the id of the action
    - **api_view_id**: the id of the api view
    - **role_id**: the id of the role
    - **created_at**: datetime, the datetime when the user was created (in UTC).
      This datetime is generated automatically, the user does not need to provide it.
    - **updated_at**: datetime, the datetime when the user was last updated (in UTC).
      This datetime is generated automatically, the user does not need to provide it.
    - **deleted_at**: datetime, the datetime when the user was deleted (in UTC).
      This field is used only if we deactivate instead of deleting the record.
      This datetime is generated automatically, the user does not need to provide it.

    """

    # TODO: trace the user that modifies the permissions
    __tablename__ = "permission_view"
    __table_args__ = (db.UniqueConstraint("action_id", "api_view_id",
                                          "role_id"), )

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    action_id = db.Column(db.Integer,
                          db.ForeignKey("actions.id"),
                          nullable=False)
    action = db.relationship("ActionBaseModel", viewonly=True)

    api_view_id = db.Column(db.Integer,
                            db.ForeignKey("api_view.id"),
                            nullable=False)
    api_view = db.relationship("ViewBaseModel", viewonly=True)

    role_id = db.Column(db.Integer, db.ForeignKey("roles.id"), nullable=False)
    role = db.relationship("RoleBaseModel", viewonly=True)

    def __init__(self, data):
        super().__init__()
        self.action_id = data.get("action_id")
        self.api_view_id = data.get("api_view_id")
        self.role_id = data.get("role_id")

    @classmethod
    def get_permission(cls, **kwargs: dict) -> bool:
        """
        Method to check if there is permissions with the combination of fields that are in the keyword arguments

        :param dict kwargs: the keyword arguments to search for
        :return: if there are permissions or not
        :rtype: bool
        """
        permission = cls.query.filter_by(deleted_at=None, **kwargs).first()
        if permission is not None:
            return True
        else:
            return False

    def __repr__(self):
        return f"<Permission role: {self.role_id}, action: {self.action_id}, view: {self.api_view_id}>"
Exemplo n.º 5
0
class ExecutionModel(BaseDataModel):
    """
    Model class for the Executions.
    It inherits from :class:`BaseDataModel` to have the trace fields and user field

    - **id**: str, the primary key for the executions, a hash generated upon creation of the execution
      and the id given back to the user.
      The hash is generated from the creation date, the user and the id of the parent instance.
    - **instance_id**: str, the foreign key for the instance (:class:`InstanceModel`). It links the execution to its
      parent instance.
    - **name**: str, the name of the execution given by the user.
    - **description**: str, the description of the execution given by the user. It is optional.
    - **config**: dict (JSON), the configuration to be used in the execution (:class:`ConfigSchema`).
    - **data**: dict (JSON), the results from the execution (:class:`DataSchema`).
    - **log_text**: text, the log generated by the airflow webserver during execution. This log is stored as text.
    - **log_json**: dict (JSON), the log generated by the airflow webserver during execution.
      This log is stored as a dict (JSON).
    - **user_id**: int, the foreign key for the user (:class:`UserModel`). It links the execution to its owner.
    - **created_at**: datetime, the datetime when the execution was created (in UTC).
      This datetime is generated automatically, the user does not need to provide it.
    - **updated_at**: datetime, the datetime when the execution was last updated (in UTC).
      This datetime is generated automatically, the user does not need to provide it.
    - **deleted_at**: datetime, the datetime when the execution was deleted (in UTC). Even though it is deleted,
      actually, it is not deleted from the database, in order to have a command that cleans up deleted data
      after a certain time of its deletion.
      This datetime is generated automatically, the user does not need to provide it.
    - **state**: int, value representing state of the execution (finished, in progress, error, etc.)
    - **state_message**: str, a string value of state with human readable status message.
    - **data_hash**: a hash of the data json using SHA256

    :param dict data: the parsed json got from an endpoint that contains all the required information to
      create a new execution
    """

    # Table name in the database
    __tablename__ = "executions"

    # Model fields
    id = db.Column(db.String(256), nullable=False, primary_key=True)
    instance_id = db.Column(db.String(256),
                            db.ForeignKey("instances.id"),
                            nullable=False)
    config = db.Column(JSON, nullable=False)
    dag_run_id = db.Column(db.String(256), nullable=True)
    log_text = db.Column(TEXT, nullable=True)
    log_json = db.Column(JSON, nullable=True)
    state = db.Column(db.SmallInteger,
                      default=DEFAULT_EXECUTION_CODE,
                      nullable=False)
    state_message = db.Column(
        TEXT,
        default=EXECUTION_STATE_MESSAGE_DICT[DEFAULT_EXECUTION_CODE],
        nullable=True,
    )

    def __init__(self, data):
        super().__init__(data)
        self.user_id = data.get("user_id")
        self.instance_id = data.get("instance_id")
        self.id = hashlib.sha1(
            (str(self.created_at) + " " + str(self.user_id) + " " +
             str(self.instance_id)).encode()).hexdigest()

        self.dag_run_id = data.get("dag_run_id")
        self.state = data.get("state", DEFAULT_EXECUTION_CODE)
        self.state_message = EXECUTION_STATE_MESSAGE_DICT[self.state]
        self.config = data.get("config")
        self.log_text = data.get("log_text")
        self.log_json = data.get("log_json")

    def update_state(self, code, message=None):
        """
        Method to update the state code and message of an execution

        :param int code: State code for the execution
        :param str message: Message for the error
        :return: nothing
        """
        self.state = code
        if message is None:
            self.state_message = EXECUTION_STATE_MESSAGE_DICT[code]
        else:
            self.state_message = message
        super().update({})

    def __repr__(self):
        """
        Method to represent the class :class:`ExecutionModel`

        :return: The representation of the :class:`ExecutionModel`
        :rtype: str
        """
        return f"<Execution {self.id}>"

    def __str__(self):
        """
        Method to print a string representation of the :class:`ExecutionModel`

        :return: The string for the :class:`ExecutionModel`
        :rtype: str
        """
        return self.__repr__()