예제 #1
0
 def filter_organizations(applications):
     organization_ids = set(applications.values_list('org_id', flat=True))
     organizations = [
         Organization.get_instance(org_id) for org_id in organization_ids
     ]
     organizations.sort(key=lambda x: x.name)
     return organizations
예제 #2
0
    def validate(self, attrs):
        org_id = attrs.get('org_id')
        assignees = attrs.get('assignees')

        instance = self.instance
        if instance is not None:
            if org_id and not assignees:
                assignees = list(instance.assignees.all())
            elif assignees and not org_id:
                org_id = instance.org_id
            elif assignees and org_id:
                pass
            else:
                return attrs

        user = self.context['request'].user
        org = Organization.get_instance(org_id)
        if org is None:
            raise serializers.ValidationError(_('Invalid `org_id`'))

        q = Q(role=User.ROLE.ADMIN)
        if not org.is_default():
            q |= Q(m2m_org_members__role=ORG_ROLE.ADMIN,
                   orgs__id=org_id,
                   orgs__members=user)

        q &= Q(id__in=[assignee.id for assignee in assignees])
        count = User.objects.filter(q).distinct().count()
        if count != len(assignees):
            raise serializers.ValidationError(
                _('Field `assignees` must be organization admin or superuser'))
        return attrs
예제 #3
0
파일: command.py 프로젝트: zwfec/jumpserver
 def run(self):
     print('-' * 10 + ' ' + ugettext('Task start') + ' ' + '-' * 10)
     org = Organization.get_instance(self.run_as.org_id)
     org.change_to()
     self.date_start = timezone.now()
     ok, msg = self.run_as.is_command_can_run(self.command)
     if ok:
         runner = CommandRunner(self.inventory)
         try:
             host = self.hosts.first()
             if host.is_windows():
                 shell = 'win_shell'
             else:
                 shell = 'shell'
             result = runner.execute(self.command, 'all', module=shell)
             self.result = result.results_command
         except SoftTimeLimitExceeded as e:
             print("Run timeout than 60s")
             self.result = {"error": str(e)}
         except Exception as e:
             print("Error occur: {}".format(e))
             self.result = {"error": str(e)}
     else:
         msg = _("Command `{}` is forbidden ........").format(self.command)
         print('\033[31m' + msg + '\033[0m')
         self.result = {"error": msg}
     self.org_id = self.run_as.org_id
     self.is_finished = True
     self.date_finished = timezone.now()
     self.save()
     print('-' * 10 + ' ' + ugettext('Task end') + ' ' + '-' * 10)
     return self.result
예제 #4
0
 def get_org(self):
     org_id = self.request.query_params.get('org_id')
     org = Organization.get_instance(org_id)
     if not org:
         error = ('The organization `{}` does not exist'.format(org_id))
         raise JMSException(error)
     return org
예제 #5
0
def check_node_assets_amount_task(org_id=Organization.ROOT_ID):
    try:
        with tmp_to_org(Organization.get_instance(org_id)):
            check_node_assets_amount()
    except AcquireFailed:
        logger.error(
            _('The task of self-checking is already running and cannot be started repeatedly'
              ))
예제 #6
0
 def validate_assignees(self, assignees):
     org_id = self.initial_data.get('org_id')
     self.validate_org_id(org_id)
     org = Organization.get_instance(org_id)
     admins = User.get_super_and_org_admins(org)
     valid_assignees = list(set(assignees) & set(admins))
     if not valid_assignees:
         error = _('None of the assignees belong to Organization `{}` admins'.format(org.name))
         raise serializers.ValidationError(error)
     return valid_assignees
예제 #7
0
 def validate_reviewers(self, reviewers):
     org_id = self.fields['org_id'].default()
     org = Organization.get_instance(org_id)
     if not org:
         error = _('The organization `{}` does not exist'.format(org_id))
         raise serializers.ValidationError(error)
     users = org.get_members()
     valid_reviewers = list(set(reviewers) & set(users))
     if not valid_reviewers:
         error = _('None of the reviewers belong to Organization `{}`'.format(org.name))
         raise serializers.ValidationError(error)
     return valid_reviewers
예제 #8
0
 def run(self):
     print('-' * 10 + ' ' + ugettext('Task start') + ' ' + '-' * 10)
     org = Organization.get_instance(self.run_as.org_id)
     org.change_to()
     self.date_start = timezone.now()
     ok, msg = self.is_command_can_run(self.command)
     if ok:
         allow_assets = self.allow_assets
         deny_assets = set(list(self.hosts.all())) - set(list(allow_assets))
         for asset in deny_assets:
             print(f'资产{asset}: 命令{self.command}不允许执行')
         if not allow_assets:
             self.result = {
                 "error":
                 'There are currently no assets that can be executed'
             }
             self.save()
             return self.result
         runner = CommandRunner(self.inventory)
         try:
             host = allow_assets.first()
             if host and host.is_windows():
                 shell = 'win_shell'
             elif host and host.is_unixlike():
                 shell = 'shell'
             else:
                 shell = 'raw'
             result = runner.execute(self.command, 'all', module=shell)
             self.result = result.results_command
         except SoftTimeLimitExceeded as e:
             print("Run timeout than 60s")
             self.result = {"error": str(e)}
         except Exception as e:
             print("Error occur: {}".format(e))
             self.result = {"error": str(e)}
     else:
         msg = _("Command `{}` is forbidden ........").format(self.command)
         print('\033[31m' + msg + '\033[0m')
         CommandExecutionAlert({
             'input': self.command,
             'assets': self.hosts.all(),
             'user': str(self.user),
             'risk_level': 5,
         }).publish_async()
         self.result = {"error": msg}
     self.org_id = self.run_as.org_id
     self.is_finished = True
     self.date_finished = timezone.now()
     self.save()
     print('-' * 10 + ' ' + ugettext('Task end') + ' ' + '-' * 10)
     return self.result
예제 #9
0
def check_node_assets_amount_task(org_id=None):
    if org_id is None:
        orgs = Organization.objects.all()
    else:
        orgs = [Organization.get_instance(org_id)]

    for org in orgs:
        try:
            with tmp_to_org(org):
                check_node_assets_amount()
        except AcquireFailed:
            error = _('The task of self-checking is already running '
                      'and cannot be started repeatedly')
            logger.error(error)
예제 #10
0
def import_ldap_user():
    logger.info("Start import ldap user task")
    util_server = LDAPServerUtil()
    util_import = LDAPImportUtil()
    users = util_server.search()
    if settings.XPACK_ENABLED:
        org_id = settings.AUTH_LDAP_SYNC_ORG_ID
        default_org = None
    else:
        # 社区版默认导入Default组织
        org_id = Organization.DEFAULT_ID
        default_org = Organization.default()
    org = Organization.get_instance(org_id, default=default_org)
    errors = util_import.perform_import(users, org)
    if errors:
        logger.error("Imported LDAP users errors: {}".format(errors))
    else:
        logger.info('Imported {} users successfully'.format(len(users)))
예제 #11
0
 def run(self):
     print('-'*10 + ' ' + ugettext('Task start') + ' ' + '-'*10)
     org = Organization.get_instance(self.run_as.org_id)
     org.change_to()
     self.date_start = timezone.now()
     ok, msg = self.run_as.is_command_can_run(self.command)
     if ok:
         runner = CommandRunner(self.inventory)
         try:
             result = runner.execute(self.command, 'all')
             self.result = result.results_command
         except Exception as e:
             print("Error occur: {}".format(e))
             self.result = {"error": str(e)}
     else:
         msg = _("Command `{}` is forbidden ........").format(self.command)
         print('\033[31m' + msg + '\033[0m')
         self.result = {"error":  msg}
     self.is_finished = True
     self.date_finished = timezone.now()
     self.save()
     print('-'*10 + ' ' + ugettext('Task end') + ' ' + '-'*10)
     return self.result
예제 #12
0
 def validate_org_id(org_id):
     org = Organization.get_instance(org_id)
     if not org:
         error = _('The organization `{}` does not exist'.format(org_id))
         raise serializers.ValidationError(error)
     return org_id
예제 #13
0
파일: caches.py 프로젝트: xeooon/jumpserver
 def __init__(self):
     super().__init__()
     self.current_org = Organization.get_instance(current_org.id)
예제 #14
0
 def org(self):
     from orgs.models import Organization
     org = Organization.get_instance(self.org_id)
     return org
예제 #15
0
파일: user.py 프로젝트: ZaXk/jumpserver
 def remove(self):
     if current_org.is_root():
         return
     org = Organization.get_instance(current_org.id)
     OrganizationMember.objects.remove_users(org, [self])
예제 #16
0
 def org(self):
     from orgs.models import Organization
     org = Organization.get_instance(self.org_id)
     return org
예제 #17
0
 def switch_org(self, org_id):
     o = Organization.get_instance(org_id, default=True)
     if o:
         o.change_to()
     print('Current org is: {}'.format(o))
     return o
예제 #18
0
 def filter_organizations(applications):
     organizations_id = set(applications.values_list('org_id', flat=True))
     organizations = [Organization.get_instance(org_id) for org_id in organizations_id]
     return organizations