Ejemplo n.º 1
0
class AssetPermission(BasePermission):
    assets = models.ManyToManyField('assets.Asset',
                                    related_name='granted_by_permissions',
                                    blank=True,
                                    verbose_name=_("Asset"))
    nodes = models.ManyToManyField('assets.Node',
                                   related_name='granted_by_permissions',
                                   blank=True,
                                   verbose_name=_("Nodes"))
    system_users = models.ManyToManyField(
        'assets.SystemUser',
        related_name='granted_by_permissions',
        verbose_name=_("System user"))
    actions = models.IntegerField(choices=Action.DB_CHOICES,
                                  default=Action.ALL,
                                  verbose_name=_("Actions"))

    class Meta:
        unique_together = [('org_id', 'name')]
        verbose_name = _("Asset permission")
        ordering = ('name', )

    @lazyproperty
    def users_amount(self):
        return self.users.count()

    @lazyproperty
    def user_groups_amount(self):
        return self.user_groups.count()

    @lazyproperty
    def assets_amount(self):
        return self.assets.count()

    @lazyproperty
    def nodes_amount(self):
        return self.nodes.count()

    @lazyproperty
    def system_users_amount(self):
        return self.system_users.count()

    @classmethod
    def get_queryset_with_prefetch(cls):
        return cls.objects.all().valid().prefetch_related(
            models.Prefetch('nodes', queryset=Node.objects.all().only('key')),
            models.Prefetch('assets', queryset=Asset.objects.all().only('id')),
            models.Prefetch(
                'system_users',
                queryset=SystemUser.objects.all().only('id'))).order_by()

    def get_all_assets(self):
        from assets.models import Node
        nodes_keys = self.nodes.all().values_list('key', flat=True)
        asset_ids = set(self.assets.all().values_list('id', flat=True))
        nodes_asset_ids = Node.get_nodes_all_asset_ids_by_keys(nodes_keys)
        asset_ids.update(nodes_asset_ids)
        assets = Asset.objects.filter(id__in=asset_ids)
        return assets
Ejemplo n.º 2
0
class LoginConfirmSetting(CommonModelMixin):
    user = models.OneToOneField('users.User',
                                on_delete=models.CASCADE,
                                verbose_name=_("User"),
                                related_name="login_confirm_setting")
    reviewers = models.ManyToManyField(
        'users.User',
        verbose_name=_("Reviewers"),
        related_name="review_login_confirm_settings",
        blank=True)
    is_active = models.BooleanField(default=True, verbose_name=_("Is active"))

    class Meta:
        verbose_name = _('Login Confirm')

    @classmethod
    def get_user_confirm_setting(cls, user):
        return get_object_or_none(cls, user=user)

    @staticmethod
    def construct_confirm_ticket_meta(request=None):
        if request:
            login_ip = get_request_ip(request)
        else:
            login_ip = ''
        login_ip = login_ip or '0.0.0.0'
        login_city = get_ip_city(login_ip)
        login_datetime = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
        ticket_meta = {
            'apply_login_ip': login_ip,
            'apply_login_city': login_city,
            'apply_login_datetime': login_datetime,
        }
        return ticket_meta

    def create_confirm_ticket(self, request=None):
        from tickets import const
        from tickets.models import Ticket
        from orgs.models import Organization
        ticket_title = _('Login confirm') + ' {}'.format(self.user)
        ticket_meta = self.construct_confirm_ticket_meta(request)
        data = {
            'title': ticket_title,
            'type': const.TicketType.login_confirm.value,
            'meta': ticket_meta,
            'org_id': Organization.ROOT_ID,
        }
        ticket = Ticket.objects.create(**data)
        ticket.create_process_map_and_node(self.reviewers.all())
        ticket.open(self.user)
        return ticket

    def __str__(self):
        reviewers = [u.username for u in self.reviewers.all()]
        return _('{} need confirm by {}').format(self.user.username, reviewers)
Ejemplo n.º 3
0
class LoginConfirmSetting(CommonModelMixin):
    user = models.OneToOneField('users.User',
                                on_delete=models.CASCADE,
                                verbose_name=_("User"),
                                related_name="login_confirm_setting")
    reviewers = models.ManyToManyField(
        'users.User',
        verbose_name=_("Reviewers"),
        related_name="review_login_confirm_settings",
        blank=True)
    is_active = models.BooleanField(default=True, verbose_name=_("Is active"))

    @classmethod
    def get_user_confirm_setting(cls, user):
        return get_object_or_none(cls, user=user)

    def create_confirm_ticket(self, request=None):
        from tickets.models import Ticket
        title = _('Login confirm') + ' {}'.format(self.user)
        if request:
            remote_addr = get_request_ip(request)
            city = get_ip_city(remote_addr)
            datetime = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
            body = __("{user_key}: {username}<br>"
                      "IP: {ip}<br>"
                      "{city_key}: {city}<br>"
                      "{date_key}: {date}<br>").format(user_key=__("User"),
                                                       username=self.user,
                                                       ip=remote_addr,
                                                       city_key=_("City"),
                                                       city=city,
                                                       date_key=__("Datetime"),
                                                       date=datetime)
        else:
            body = ''
        reviewer = self.reviewers.all()
        ticket = Ticket.objects.create(
            user=self.user,
            title=title,
            body=body,
            type=Ticket.TYPE.LOGIN_CONFIRM,
        )
        ticket.assignees.set(reviewer)
        return ticket

    def __str__(self):
        return '{} confirm'.format(self.user.username)
Ejemplo n.º 4
0
class LoginConfirmSetting(CommonModelMixin):
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, verbose_name=_("User"), related_name="login_confirm_setting")
    reviewers = models.ManyToManyField('users.User', verbose_name=_("Reviewers"), related_name="review_login_confirm_settings", blank=True)
    is_active = models.BooleanField(default=True, verbose_name=_("Is active"))

    @classmethod
    def get_user_confirm_setting(cls, user):
        return get_object_or_none(cls, user=user)

    @staticmethod
    def construct_confirm_ticket_meta(request=None):
        if request:
            login_ip = get_request_ip(request)
        else:
            login_ip = ''
        login_ip = login_ip or '0.0.0.0'
        login_city = get_ip_city(login_ip)
        login_datetime = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
        ticket_meta = {
            'apply_login_ip': login_ip,
            'apply_login_city': login_city,
            'apply_login_datetime': login_datetime,
        }
        return ticket_meta

    def create_confirm_ticket(self, request=None):
        from tickets import const
        from tickets.models import Ticket
        ticket_title = _('Login confirm') + ' {}'.format(self.user)
        ticket_applicant = self.user
        ticket_meta = self.construct_confirm_ticket_meta(request)
        ticket_assignees = self.reviewers.all()
        data = {
            'title': ticket_title,
            'type': const.TicketTypeChoices.login_confirm.value,
            'applicant': ticket_applicant,
            'meta': ticket_meta,
        }
        ticket = Ticket.objects.create(**data)
        ticket.assignees.set(ticket_assignees)
        return ticket

    def __str__(self):
        return '{} confirm'.format(self.user.username)
Ejemplo n.º 5
0
class AssetPermission(BasePermission):
    assets = models.ManyToManyField('assets.Asset', related_name='granted_by_permissions', blank=True, verbose_name=_("Asset"))
    nodes = models.ManyToManyField('assets.Node', related_name='granted_by_permissions', blank=True, verbose_name=_("Nodes"))
    system_users = models.ManyToManyField('assets.SystemUser', related_name='granted_by_permissions', verbose_name=_("System user"))
    actions = models.IntegerField(choices=Action.DB_CHOICES, default=Action.ALL, verbose_name=_("Actions"))

    class Meta:
        unique_together = [('org_id', 'name')]
        verbose_name = _("Asset permission")
        ordering = ('name',)

    @lazyproperty
    def users_amount(self):
        return self.users.count()

    @lazyproperty
    def user_groups_amount(self):
        return self.user_groups.count()

    @lazyproperty
    def assets_amount(self):
        return self.assets.count()

    @lazyproperty
    def nodes_amount(self):
        return self.nodes.count()

    @lazyproperty
    def system_users_amount(self):
        return self.system_users.count()

    @classmethod
    def get_queryset_with_prefetch(cls):
        return cls.objects.all().valid().prefetch_related(
            models.Prefetch('nodes', queryset=Node.objects.all().only('key')),
            models.Prefetch('assets', queryset=Asset.objects.all().only('id')),
            models.Prefetch('system_users', queryset=SystemUser.objects.all().only('id'))
        ).order_by()

    def get_all_assets(self):
        from assets.models import Node
        nodes_keys = self.nodes.all().values_list('key', flat=True)
        assets_ids = set(self.assets.all().values_list('id', flat=True))
        nodes_assets_ids = Node.get_nodes_all_assets_ids(nodes_keys)
        assets_ids.update(nodes_assets_ids)
        assets = Asset.objects.filter(id__in=assets_ids)
        return assets

    @classmethod
    def generate_fake(cls, count=100):
        from ..hands import User, Node, SystemUser
        import random

        org = get_current_org()
        if not org or not org.is_real():
            Organization.default().change_to()

        nodes = list(Node.objects.all())
        assets = list(Asset.objects.all())
        system_users = list(SystemUser.objects.all())
        users = User.objects.filter(username='******')

        for i in range(count):
            name = "fake_perm_to_admin_{}".format(str(uuid.uuid4())[:6])
            perm = cls(name=name)
            try:
                perm.save()
                perm.users.set(users)
                if system_users and len(system_users) > 3:
                    _system_users = random.sample(system_users, 3)
                elif system_users:
                    _system_users = [system_users[0]]
                else:
                    _system_users = []
                perm.system_users.set(_system_users)

                if nodes and len(nodes) > 3:
                    _nodes = random.sample(nodes, 3)
                else:
                    _nodes = [Node.default_node()]
                perm.nodes.set(_nodes)

                if assets and len(assets) > 3:
                    _assets = random.sample(assets, 3)
                elif assets:
                    _assets = [assets[0]]
                else:
                    _assets = []
                perm.assets.set(_assets)

                logger.debug('Generate fake perm: %s' % perm.name)

            except Exception as e:
                print('Error continue')
                continue