Example #1
0
def ensure_assignee_is_workflow_member(workflow, assignee):
    """Checks what role assignee has in the context of
  a workflow. If he has none he gets the Workflow Member role."""
    if not assignee:
        return

    # Check if assignee is mapped to the Workflow
    workflow_people = models.WorkflowPerson.query.filter(
        models.WorkflowPerson.workflow_id == workflow.id,
        models.WorkflowPerson.person_id == assignee.id).all()
    if not workflow_people:
        workflow_person = models.WorkflowPerson(person=assignee,
                                                workflow=workflow,
                                                context=workflow.context)
        db.session.add(workflow_person)

    # Check if assignee has a role assignment
    from ggrc_basic_permissions.models import UserRole
    user_roles = UserRole.query.filter(
        UserRole.context_id == workflow.context_id,
        UserRole.person_id == assignee.id).all()
    if not user_roles:
        workflow_member_role = _find_role('WorkflowMember')
        user_role = UserRole(
            person=assignee,
            role=workflow_member_role,
            context=workflow.context,
            modified_by=get_current_user(),
        )
        db.session.add(user_role)
Example #2
0
def ensure_assignee_is_workflow_member(workflow, assignee, assignee_id=None):
    """Checks what role assignee has in the context of
  a workflow. If he has none he gets the Workflow Member role."""
    if not assignee and not assignee_id:
        return
    if assignee_id is None:
        assignee_id = assignee.id
    if assignee and assignee_id != assignee.id:
        raise ValueError("Conflict value assignee and assignee_id")
    if any(assignee_id == wp.person_id for wp in workflow.workflow_people):
        return

    # Check if assignee is mapped to the Workflow
    workflow_people = models.WorkflowPerson.query.filter(
        models.WorkflowPerson.workflow_id == workflow.id,
        models.WorkflowPerson.person_id == assignee_id).count()
    if not workflow_people:
        models.WorkflowPerson(person=assignee,
                              person_id=assignee_id,
                              workflow=workflow,
                              context=workflow.context)

    # Check if assignee has a role assignment
    user_roles = UserRole.query.filter(
        UserRole.context_id == workflow.context_id,
        UserRole.person_id == assignee_id).count()
    if not user_roles:
        workflow_member_role = _find_role('WorkflowMember')
        UserRole(
            person=assignee,
            person_id=assignee_id,
            role=workflow_member_role,
            context=workflow.context,
            modified_by=get_current_user(),
        )
  def test_permissions_for_backlog_workflow(self, mock_get_current_user):  # noqa # pylint: disable=invalid-name
    """Tests whether the creator has all the necessary permissions for
    backlog workflow."""

    my_person = Person(name="kekec", email="*****@*****.**")
    creator_role = Role.query.filter(Role.name == "Creator").one()
    user_role = UserRole(role=creator_role, person=my_person)  # noqa # pylint: disable=unused-variable
    mock_get_current_user.return_value = Person(name="Mojca",
                                                email="*****@*****.**")
    backlog_workflow = db.session\
                         .query(Workflow)\
                         .filter(Workflow.kind == "Backlog").one()
    workflow_ctx = backlog_workflow.context.id
    user_perms = load_permissions_for(my_person)

    actions = ["read", "edit", "update"]
    _types = ["Workflow", "Cycle", "CycleTaskGroup",
              "CycleTaskGroupObjectTask", "TaskGroup"]

    for action in actions:
      for obj_type in _types:
        self.assertTrue(workflow_ctx in
                        user_perms[action][obj_type]['contexts'])
    ctgot_ctxs = user_perms['delete']['CycleTaskGroupObjectTask']['contexts']
    self.assertTrue(workflow_ctx in ctgot_ctxs)
Example #4
0
def add_creator_role(user):
    user_creator_role = UserRole(
        person=user,
        role=basic_roles.creator(),
    )
    db.session.add(user_creator_role)
    db.session.commit()
    log_event(db.session, user_creator_role, user_creator_role.id)
Example #5
0
def handle_workflow_person_post(sender, obj=None, src=None, service=None):
  # add a user_roles mapping assigning the user creating the workflow
  # the WorkflowOwner role in the workflow's context.
  UserRole(
      person=obj.person,
      role=_find_role('WorkflowMember'),
      context=obj.context,
      modified_by=get_current_user(),
  )
Example #6
0
def add_creator_role(user):
    """Add createor role for sent user."""
    user_creator_role = UserRole(
        person=user,
        role=basic_roles.creator(),
    )
    db.session.add(user_creator_role)
    db.session.commit()
    log_event(db.session, user_creator_role, user_creator_role.id)
Example #7
0
 def insert_object(self):
     if self.dry_run or not self.value:
         return
     self.remove_current_roles()
     for owner in self.value:
         user_role = UserRole(role=self.role,
                              context=self.row_converter.obj.context,
                              person=owner)
         db.session.add(user_role)
     self.dry_run = True
Example #8
0
def handle_workflow_person_post(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
    db.session.flush()

    # add a user_roles mapping assigning the user creating the workflow
    # the WorkflowOwner role in the workflow's context.
    workflow_member_role = _find_role('WorkflowMember')
    user_role = UserRole(
        person=obj.person,
        role=workflow_member_role,
        context=obj.context,
        modified_by=get_current_user(),
    )
    db.session.add(user_role)
Example #9
0
def setup_user_role(user):
  """
    Setup Administrator role for test user.
  """
  role = Role.query.filter(
      Role.name == SystemWideRoles.ADMINISTRATOR,
  ).first()

  user_role = UserRole()
  user_role.role = role
  user_role.person = user

  return user_role
Example #10
0
def add_creator_role(user, **kwargs):
    """Add creator role for sent user."""
    if not hasattr(flask.g, "user_creator_roles_cache"):
        flask.g.user_creator_roles_cache = {}

    if user.email in flask.g.user_creator_roles_cache:
        # we have this role in the cache so no need to create it
        return

    user_creator_role = UserRole(person=user,
                                 role=basic_roles.creator(),
                                 **kwargs)
    flask.g.user_creator_roles_cache[user.email] = user_creator_role
    db.session.add(user_creator_role)
Example #11
0
 def insert_object(self):
     if self.dry_run or not self.value:
         return
     self.remove_current_roles()
     context = None
     if self.value.name == "Administrator":
         context = Context.query.filter_by(
             name="System Administration").first()
     user_role = UserRole(
         role=self.value,
         person=self.row_converter.obj,
         context=context,
     )
     db.session.add(user_role)
     self.dry_run = True
Example #12
0
 def insert_object(self):
     if self.dry_run or not self.value:
         return
     super(AuditAuditorColumnHandler, self).insert_object()
     user_roles = set(o.person_id for o in self.get_program_roles())
     context = self.row_converter.obj.program.context
     for auditor in self.value:
         # Check if the role already exists in the database or in the session:
         if auditor.id in user_roles or any(
                 o for o in db.session.new
                 if isinstance(o, UserRole) and o.context.id == context.id
                 and o.person.id == auditor.id):
             continue
         user_role = UserRole(role=self.reader,
                              context=context,
                              person=auditor)
         db.session.add(user_role)
Example #13
0
def handle_program_post(sender, obj=None, src=None, service=None):
  db.session.flush()
  # get the personal context for this logged in user
  user = get_current_user()
  personal_context = _get_or_create_personal_context(user)
  context = obj.build_object_context(
      context=personal_context,
      name='{object_type} Context {timestamp}'.format(
          object_type=service.model.__name__,
          timestamp=datetime.datetime.now()),
      description='',
  )
  context.modified_by = get_current_user()

  db.session.add(obj)
  db.session.flush()
  db.session.add(context)
  db.session.flush()
  obj.contexts.append(context)
  obj.context = context

  # add a user_roles mapping assigning the user creating the program
  # the ProgramOwner role in the program's context.
  program_owner_role = basic_roles.program_owner()
  user_role = UserRole(
      person=get_current_user(),
      role=program_owner_role,
      context=context,
      modified_by=get_current_user())
  # pass along a temporary attribute for logging the events.
  user_role._display_related_title = obj.title
  db.session.add(user_role)
  db.session.flush()

  # Create the context implication for Program roles to default context
  db.session.add(ContextImplication(
      source_context=context,
      context=None,
      source_context_scope='Program',
      context_scope=None,
      modified_by=get_current_user()))

  if not src.get('private'):
    # Add role implication - all users can read a public program
    add_public_program_context_implication(context)
Example #14
0
  def _clone_auditors(self, audit):
    """Clone auditors of specified audit.

    Args:
      audit: Audit instance
    """
    from ggrc_basic_permissions.models import Role, UserRole

    role = Role.query.filter_by(name="Auditor").first()
    auditors = [ur.person for ur in UserRole.query.filter_by(
        role=role, context=audit.context).all()]

    for auditor in auditors:
      user_role = UserRole(
          context=self.context,
          person=auditor,
          role=role
      )
      db.session.add(user_role)
    db.session.flush()
Example #15
0
def handle_workflow_post(sender, obj=None, src=None, service=None):  # noqa pylint: disable=unused-argument
    source_workflow = None

    if src.get('clone'):
        source_workflow_id = src.get('clone')
        source_workflow = models.Workflow.query.filter_by(
            id=source_workflow_id).first()
        source_workflow.copy(obj)
        db.session.add(obj)
        db.session.flush()
        obj.title = source_workflow.title + ' (copy ' + str(obj.id) + ')'

    db.session.flush()
    # get the personal context for this logged in user
    user = get_current_user()
    personal_context = _get_or_create_personal_context(user)
    context = obj.build_object_context(
        context=personal_context,
        name='{object_type} Context {timestamp}'.format(
            object_type=service.model.__name__, timestamp=datetime.now()),
        description='',
    )
    context.modified_by = get_current_user()

    db.session.add(obj)
    db.session.flush()
    db.session.add(context)
    db.session.flush()
    obj.contexts.append(context)
    obj.context = context

    # add a user_roles mapping assigning the user creating the workflow
    # the WorkflowOwner role in the workflow's context.
    workflow_owner_role = _find_role('WorkflowOwner')
    user_role = UserRole(
        person=user,
        role=workflow_owner_role,
        context=context,
        modified_by=get_current_user(),
    )
    db.session.add(
        models.WorkflowPerson(
            person=user,
            workflow=obj,
            context=context,
            modified_by=get_current_user(),
        ))
    # pass along a temporary attribute for logging the events.
    user_role._display_related_title = obj.title
    db.session.add(user_role)
    db.session.flush()

    # Create the context implication for Workflow roles to default context
    db.session.add(
        ContextImplication(
            source_context=context,
            context=None,
            source_context_scope='Workflow',
            context_scope=None,
            modified_by=get_current_user(),
        ))

    if not src.get('private'):
        # Add role implication - all users can read a public workflow
        add_public_workflow_context_implication(context)

    if src.get('clone'):
        source_workflow.copy_task_groups(
            obj,
            clone_people=src.get('clone_people', False),
            clone_tasks=src.get('clone_tasks', False),
            clone_objects=src.get('clone_objects', False))

        if src.get('clone_people'):
            workflow_member_role = _find_role('WorkflowMember')
            for authorization in source_workflow.context.user_roles:
                # Current user has already been added as workflow owner
                if authorization.person != user:
                    db.session.add(
                        UserRole(person=authorization.person,
                                 role=workflow_member_role,
                                 context=context,
                                 modified_by=user))
            for person in source_workflow.people:
                if person != user:
                    db.session.add(
                        models.WorkflowPerson(person=person,
                                              workflow=obj,
                                              context=context))
Example #16
0
def handle_workflow_post(sender, obj=None, src=None, service=None):
  _validate_post_workflow_fields(obj)

  source_workflow = None

  if src.get('clone'):
    source_workflow_id = src.get('clone')
    source_workflow = models.Workflow.query.filter_by(
        id=source_workflow_id
    ).first()
    source_workflow.copy(obj)
    obj.title = source_workflow.title + ' (copy ' + str(obj.id) + ')'

  # get the personal context for this logged in user
  user = get_current_user()
  personal_context = user.get_or_create_object_context(context=1)
  context = obj.get_or_create_object_context(personal_context)
  obj.context = context

  if not obj.workflow_people:
    # add a user_roles mapping assigning the user creating the workflow
    # the WorkflowOwner role in the workflow's context.
    workflow_owner_role = _find_role('WorkflowOwner')
    user_role = UserRole(
        person=user,
        role=workflow_owner_role,
        context=context,
        modified_by=get_current_user(),
    )
    models.WorkflowPerson(
        person=user,
        workflow=obj,
        context=context,
        modified_by=get_current_user(),
    )
    # pass along a temporary attribute for logging the events.
    user_role._display_related_title = obj.title

  # Create the context implication for Workflow roles to default context
  ContextImplication(
      source_context=context,
      context=None,
      source_context_scope='Workflow',
      context_scope=None,
      modified_by=get_current_user(),
  )

  if not src.get('private'):
    # Add role implication - all users can read a public workflow
    add_public_workflow_context_implication(context)

  if src.get('clone'):
    source_workflow.copy_task_groups(
        obj,
        clone_people=src.get('clone_people', False),
        clone_tasks=src.get('clone_tasks', False),
        clone_objects=src.get('clone_objects', False)
    )

    if src.get('clone_people'):
      workflow_member_role = _find_role('WorkflowMember')
      for authorization in source_workflow.context.user_roles:
        # Current user has already been added as workflow owner
        if authorization.person != user:
          UserRole(
              person=authorization.person,
              role=workflow_member_role,
              context=context,
              modified_by=user)
      for person in source_workflow.people:
        if person != user:
          models.WorkflowPerson(
              person=person,
              workflow=obj,
              context=context)