示例#1
0
 def create_organization(self, user, name):
     if Organization.objects.filter(mnemonic=name).count() < 1:
         org = Organization(mnemonic=name, name=name, company=name, members=[user.id],
                            created_by='root', updated_by='root')
         org.full_clean()
         org.save()
     else:
         org = Organization.objects.get(mnemonic=name)
     return org
示例#2
0
    def test_org_num_members(self):
        org = Organization(mnemonic='org1', name='My Organization', created_by='user1', updated_by='user1')
        org.full_clean()
        org.save()

        self.assertEquals(0, org.num_members)
        org.members.append(1)
        self.assertEquals(1, org.num_members)
        org.members.remove(1)
        self.assertEquals(0, org.num_members)
示例#3
0
 def create_organization(self, user):
     org = None
     if Organization.objects.filter(mnemonic='OCL').count() < 1:
         org = Organization(mnemonic='OCL', name='Open Concept Lab', company="Open Concept Lab", members=[user.id],
                            created_by='root', updated_by='root')
         org.full_clean()
         org.save()
     else:
         org = Organization.objects.get(mnemonic='OCL')
     return org
示例#4
0
    def ready(self):
        from orgs.models import Organization
        from orgs.utils import set_current_org
        set_current_org(Organization.root())

        super().ready()
        from .celery import signal_handler
示例#5
0
    def test_organization_delete(self):
        org = Organization(mnemonic='org1', name='My Organization', created_by='user1', updated_by='user1')
        org.full_clean()
        org.save()
        org_id = org.id

        self.assertTrue(org.is_active)
        self.assertTrue(Organization.objects.filter(id=org_id).exists())
        org.soft_delete()
        self.assertFalse(org.is_active)
        self.assertTrue(Organization.objects.filter(id=org_id).exists())
        org.delete()
        self.assertFalse(Organization.objects.filter(id=org_id).exists())
示例#6
0
 def restore_object(self, attrs, instance=None):
     request_user = self.context['request'].user
     mnemonic = attrs.get('mnemonic', None)
     if Organization.objects.filter(mnemonic=mnemonic).exists():
         self._errors['mnemonic'] = 'Organization with mnemonic %s already exists.' % mnemonic
         return None
     organization = Organization(name=attrs.get('name'), mnemonic=mnemonic)
     organization.created_by = request_user
     organization.updated_by = request_user
     organization.public_access = attrs.get('public_access', DEFAULT_ACCESS_TYPE)
     organization.company = attrs.get('company', None)
     organization.website = attrs.get('website', None)
     organization.location = attrs.get('location', None)
     organization.extras = attrs.get('extras', None)
     return organization
示例#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 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)
示例#9
0
 def create_root_node(cls):
     # 如果使用current_org 在set_current_org时会死循环
     _current_org = get_current_org()
     with transaction.atomic():
         if not _current_org.is_real():
             return cls.default_node()
         set_current_org(Organization.root())
         org_nodes_roots = cls.objects.filter(key__regex=r'^[0-9]+$')
         org_nodes_roots_keys = org_nodes_roots.values_list('key', flat=True) or ['1']
         key = max([int(k) for k in org_nodes_roots_keys])
         key = str(key + 1) if key != 0 else '2'
         set_current_org(_current_org)
         root = cls.objects.create(key=key, value=_current_org.name)
         return root
示例#10
0
文件: node.py 项目: ahhqlrg/kayuan
 def create_root_node(cls):
     # 如果使用current_org 在set_current_org时会死循环
     _current_org = get_current_org()
     with transaction.atomic():
         if _current_org.is_default():
             key = '0'
         else:
             set_current_org(Organization.root())
             org_nodes_roots = cls.objects.filter(key__regex=r'^[0-9]+$')
             org_nodes_roots_keys = org_nodes_roots.values_list('key', flat=True) or [0]
             key = max([int(k) for k in org_nodes_roots_keys]) + 1
             set_current_org(_current_org)
         root = cls.objects.create(key=key, value=_current_org.name)
         return root
示例#11
0
 def create_root_node(cls):
     # 如果使用current_org 在set_current_org时会死循环
     _current_org = get_current_org()
     with transaction.atomic():
         if not _current_org.is_real():
             return cls.default_node()
         set_current_org(Organization.root())
         org_nodes_roots = cls.objects.filter(key__regex=r'^[0-9]+$')
         org_nodes_roots_keys = org_nodes_roots.values_list('key', flat=True) or ['1']
         key = max([int(k) for k in org_nodes_roots_keys])
         key = str(key + 1) if key != 0 else '2'
         set_current_org(_current_org)
         root = cls.objects.create(key=key, value=_current_org.name)
         return root
示例#12
0
def on_org_user_changed_refresh_cache(sender, action, instance, reverse,
                                      pk_set, **kwargs):
    if not action.startswith(POST_PREFIX):
        return

    if reverse:
        orgs = Organization.objects.filter(id__in=pk_set)
    else:
        orgs = [instance]

    for org in orgs:
        org_cache = OrgResourceStatisticsCache(org)
        org_cache.expire('users_amount')
    OrgResourceStatisticsCache(Organization.root()).expire('users_amount')
示例#13
0
文件: node.py 项目: xbd666/jumpserver
 def default_node(cls):
     with tmp_to_org(Organization.default()):
         defaults = {'value': cls.default_value}
         try:
             obj, created = cls.objects.get_or_create(
                 defaults=defaults, key=cls.default_key,
             )
         except IntegrityError as e:
             logger.error("Create default node failed: {}".format(e))
             cls.modify_other_org_root_node_key()
             obj, created = cls.objects.get_or_create(
                 defaults=defaults, key=cls.default_key,
             )
         return obj
示例#14
0
 def test_create_organization_positive(self):
     self.assertFalse(Organization.objects.filter(mnemonic='org1').exists())
     org = Organization(mnemonic='org1',
                        name='My Organization',
                        created_by='user1',
                        updated_by='user1')
     org.full_clean()
     org.save()
     self.assertTrue(Organization.objects.filter(mnemonic='org1').exists())
示例#15
0
    def test_public_sources(self):
        user = User.objects.create(
            username='******',
            email='*****@*****.**',
            last_name='One',
            first_name='User'
        )

        org = Organization(mnemonic='org1', name='My Organization', created_by='user1', updated_by='user1')
        org.full_clean()
        org.save()

        self.assertEquals(0, org.public_sources)
        Source.objects.create(
            mnemonic='source1',
            parent=org,
            name='Source One',
        )
        self.assertEquals(1, org.public_sources)

        org2 = Organization(mnemonic='org2', name='Your Organization', created_by='user1', updated_by='user1')
        org2.full_clean()
        org2.save()

        Source.objects.create(
            mnemonic='source1',
            parent=org2,
            name='Source One',
        )
        self.assertEquals(1, org.public_sources)
        Source.objects.create(
            mnemonic='source2',
            parent=org,
            name='Source Two',
        )
        self.assertEquals(2, org.public_sources)
示例#16
0
    def test_org_num_members(self):
        org = Organization(mnemonic='org1', name='My Organization', created_by='user1', updated_by='user1')
        org.full_clean()
        org.save()

        self.assertEquals(0, org.num_members)
        org.members.append(1)
        self.assertEquals(1, org.num_members)
        org.members.remove(1)
        self.assertEquals(0, org.num_members)
示例#17
0
 def create_organization(self, user):
     org = None
     if Organization.objects.filter(mnemonic='OCL').count() < 1:
         org = Organization(mnemonic='OCL', name='Open Concept Lab', company="Open Concept Lab", members=[user.id],
                            created_by='root', updated_by='root')
         org.full_clean()
         org.save()
     else:
         org = Organization.objects.get(mnemonic='OCL')
     return org
示例#18
0
 def create_organization(self, user, name):
     if Organization.objects.filter(mnemonic=name).count() < 1:
         org = Organization(mnemonic=name,
                            name=name,
                            company=name,
                            members=[user.id],
                            created_by='root',
                            updated_by='root')
         org.full_clean()
         org.save()
     else:
         org = Organization.objects.get(mnemonic=name)
     return org
示例#19
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:
             host = self.hosts.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
示例#20
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
示例#21
0
    def test_create_org_special_characters(self):
        # period in mnemonic
        org = create_organization(name='test', mnemonic='org.1')
        self.assertEquals('org.1', org.mnemonic)

        # hyphen in mnemonic
        org = create_organization(name='test', mnemonic='org-1')
        self.assertEquals('org-1', org.mnemonic)

        # underscore in mnemonic
        org = create_organization(name='test', mnemonic='org_1')
        self.assertEquals('org_1', org.mnemonic)

        # all characters in mnemonic
        org = create_organization(name='test', mnemonic='org.1_2-3')
        self.assertEquals('org.1_2-3', org.mnemonic)

        # test validation error
        with self.assertRaises(ValidationError):
            org = Organization(name='test', mnemonic='org@1')
            org.full_clean()
            org.save()
示例#22
0
 def org(self):
     from orgs.models import Organization
     org = Organization.get_instance(self.org_id)
     return org
示例#23
0
 def __init__(self):
     super().__init__()
     self.current_org = Organization.get_instance(current_org.id)
示例#24
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
示例#25
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
示例#26
0
def _refresh_session_org_resource_statistics_cache(instance: Session):
    cache_field_name = ['total_count_online_users', 'total_count_online_sessions']

    org_cache = OrgResourceStatisticsCache(instance.org)
    org_cache.expire(*cache_field_name)
    OrgResourceStatisticsCache(Organization.root()).expire(*cache_field_name)
示例#27
0
def refresh_user_amount_on_user_create_or_delete(user_id):
    orgs = Organization.objects.filter(m2m_org_members__user_id=user_id).distinct()
    for org in orgs:
        org_cache = OrgResourceStatisticsCache(org)
        org_cache.expire('users_amount')
    OrgResourceStatisticsCache(Organization.root()).expire('users_amount')
示例#28
0
文件: node.py 项目: zhoudl/jumpserver
 def ungrouped_node(cls):
     with tmp_to_org(Organization.system()):
         defaults = {'value': cls.ungrouped_key}
         obj, created = cls.objects.get_or_create(defaults=defaults,
                                                  key=cls.ungrouped_key)
         return obj
示例#29
0
 def keep_subscribe_org_mapping():
     orgs_mapping_for_memory_pub_sub.subscribe(
         lambda org_id: Organization.expire_orgs_mapping())
示例#30
0
def on_user_created_set_default_org(sender, instance, created, **kwargs):
    if not created:
        return
    if instance.orgs.count() > 0:
        return
    Organization.default().members.add(instance)
示例#31
0
 def org(self):
     from orgs.models import Organization
     org = Organization.get_instance(self.org_id)
     return org
示例#32
0
 def test_create_organization_negative__no_mnemonic(self):
     with self.assertRaises(ValidationError):
         org = Organization(name='My Organization', created_by='user1', updated_by='user1')
         org.full_clean()
         org.save()
示例#33
0
def on_user_create_refresh_cache(sender, instance, created, **kwargs):
    if created:
        default_org = Organization.default()
        default_org.members.add(instance)
示例#34
0
    def test_resource_type(self):
        org = Organization(mnemonic='org1', name='My Organization', created_by='user1', updated_by='user1')
        org.full_clean()
        org.save()

        self.assertEquals(ORG_OBJECT_TYPE, org.resource_type())
示例#35
0
 def user_orgs(self):
     from orgs.models import Organization
     return Organization.get_user_user_orgs(self)
示例#36
0
 def admin_or_audit_orgs(self):
     from orgs.models import Organization
     return Organization.get_user_admin_or_audit_orgs(self)
示例#37
0
 def test_create_organization_positive(self):
     self.assertFalse(Organization.objects.filter(mnemonic='org1').exists())
     org = Organization(mnemonic='org1', name='My Organization', created_by='user1', updated_by='user1')
     org.full_clean()
     org.save()
     self.assertTrue(Organization.objects.filter(mnemonic='org1').exists())
示例#38
0
 def refresh_if_need(cls, instance):
     cache_field_name = cls.model_cache_field_mapper.get(type(instance))
     if cache_field_name:
         org_cache = OrgResourceStatisticsCache(instance.org)
         org_cache.expire(*cache_field_name)
         OrgResourceStatisticsCache(Organization.root()).expire(*cache_field_name)
示例#39
0
    def test_public_sources(self):
        user = User.objects.create(username='******',
                                   email='*****@*****.**',
                                   last_name='One',
                                   first_name='User')

        org = Organization(mnemonic='org1',
                           name='My Organization',
                           created_by='user1',
                           updated_by='user1')
        org.full_clean()
        org.save()

        self.assertEquals(0, org.public_sources)
        Source.objects.create(
            mnemonic='source1',
            parent=org,
            name='Source One',
        )
        self.assertEquals(1, org.public_sources)

        org2 = Organization(mnemonic='org2',
                            name='Your Organization',
                            created_by='user1',
                            updated_by='user1')
        org2.full_clean()
        org2.save()

        Source.objects.create(
            mnemonic='source1',
            parent=org2,
            name='Source One',
        )
        self.assertEquals(1, org.public_sources)
        Source.objects.create(
            mnemonic='source2',
            parent=org,
            name='Source Two',
        )
        self.assertEquals(2, org.public_sources)
示例#40
0
 def favorite_node(cls):
     with tmp_to_org(Organization.system()):
         defaults = {'value': cls.favorite_value}
         obj, created = cls.objects.get_or_create(defaults=defaults,
                                                  key=cls.favorite_key)
         return obj
示例#41
0
文件: node.py 项目: zornil/jumpserver
 def default_node(cls):
     default_org = Organization.default()
     with tmp_to_org(default_org):
         defaults = {'value': default_org.name}
         obj, created = cls.objects.get_or_create(defaults=defaults, key=cls.default_key)
         return obj
示例#42
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])
示例#43
0
 def admin_orgs(self):
     from orgs.models import Organization
     return Organization.get_user_admin_orgs(self)