示例#1
0
    def test_can_change_admin_without_feature(self):
        iuser = InstanceUser(user=self.user2, instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        body = {'users':
                {iuser.pk: {'admin': False}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander),
            self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.admin, False)

        body = {'users':
                {iuser.pk: {'admin': True}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander),
            self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.admin, True)
    def setUp(self):
        self.instance = make_instance()

        self.user = make_user(username='******', password='******')

        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.user_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)

        iuser = InstanceUser(instance=self.instance, user=self.user,
                             role=self.role)
        iuser.save_with_user(self.user)

        inst_role = Role(name='inst def role',
                         instance=self.instance,
                         rep_thresh=0)
        inst_role.save()

        self.inst_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=inst_role, instance=self.instance)

        self.instance.default_role = inst_role
        self.instance.save()

        self.plot = Plot(instance=self.instance)
    def setUp(self):
        self.instance = make_instance()

        self.user = make_user(username='******', password='******')

        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.user_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)

        iuser = InstanceUser(instance=self.instance, user=self.user,
                             role=self.role)
        iuser.save_with_user(self.user)

        inst_role = Role(name='inst def role',
                         instance=self.instance,
                         rep_thresh=0)
        inst_role.save()

        self.inst_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=inst_role, instance=self.instance)

        self.instance.default_role = inst_role
        self.instance.save()

        self.plot = Plot(instance=self.instance)
示例#4
0
    def test_user_roles_updated(self):
        iuser = InstanceUser(user=self.user2,
                             instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        new_role = Role(name='Ambassador',
                        instance=self.instance,
                        rep_thresh=0)
        new_role.save()

        body = {'users': {iuser.pk: {'role': new_role.pk, 'admin': False}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, False)

        body = {'users': {iuser.pk: {'role': new_role.pk, 'admin': True}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, True)
示例#5
0
    def test_can_change_admin_without_feature(self):
        iuser = InstanceUser(user=self.user2,
                             instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        body = {'users': {iuser.pk: {'admin': False}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.admin, False)

        body = {'users': {iuser.pk: {'admin': True}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.admin, True)
示例#6
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        instance = Instance.objects.get(pk=options['instance'])

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role(name='global', rep_thresh=0, instance=instance)
            r.save()
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r)
            instance_user.save_with_user(user)
            self.stdout.write('Added system user to instance with global role')

        for field in Plot._meta.get_all_field_names():
            _, c = FieldPermission.objects.get_or_create(
                model_name='Plot',
                field_name=field,
                role=instance_user.role,
                instance=instance,
                permission_level=FieldPermission.WRITE_DIRECTLY)
            if c:
                self.stdout.write('Created plot permission for field "%s"'
                                  % field)

        for field in Tree._meta.get_all_field_names():
            _, c = FieldPermission.objects.get_or_create(
                model_name='Tree',
                field_name=field,
                role=instance_user.role,
                instance=instance,
                permission_level=FieldPermission.WRITE_DIRECTLY)
            if c:
                self.stdout.write('Created tree permission for field "%s"'
                                  % field)

        dt = 0
        dp = 0
        if options.get('delete', False):
            for t in Tree.objects.all():
                t.delete_with_user(user)
                dt += 1
            for p in Plot.objects.all():
                p.delete_with_user(user)
                dp += 1

            self.stdout.write("Deleted %s trees and %s plots" % (dt, dp))

        return instance, user
示例#7
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        dt = 0
        dp = 0
        if options.get('delete', False):
            for t in Tree.objects.all():
                t.delete_with_user(user)
                dt += 1
            for p in Plot.objects.all():
                p.delete_with_user(user)
                dp += 1

            self.stdout.write("Deleted %s trees and %s plots" % (dt, dp))

        dr = 0
        if options.get('delete_resources', False):
            for f in MapFeature.objects.all():
                if f.feature_type != 'Plot':
                    f.delete_with_user(user)
                    dr += 1

            self.stdout.write("Deleted %s resources" % dr)

        return instance, user
示例#8
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        dt = 0
        dp = 0
        if options.get('delete', False):
            for t in Tree.objects.all():
                t.delete_with_user(user)
                dt += 1
            for p in Plot.objects.all():
                p.delete_with_user(user)
                dp += 1

            self.stdout.write("Deleted %s trees and %s plots" % (dt, dp))

        dr = 0
        if options.get('delete_resources', False):
            for f in MapFeature.objects.all():
                if f.feature_type != 'Plot':
                    f.delete_with_user(user)
                    dr += 1

            self.stdout.write("Deleted %s resources" % dr)

        return instance, user
示例#9
0
    def test_email_already_bound(self):
        iuser = InstanceUser(user=self.user1,
                             instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        body = {'email': self.user1.email}
        self.assertRaises(
            ValidationError, create_user_role,
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)
示例#10
0
    def test_email_already_bound(self):
        iuser = InstanceUser(user=self.user1, instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        body = {'email': self.user1.email}
        self.assertRaises(ValidationError,
                          create_user_role,
                          make_request(method='POST',
                                       body=json.dumps(body),
                                       user=self.commander),
                          self.instance)
示例#11
0
def make_user(instance=None, username='******', make_role=None,
              admin=False, password='******'):
    """
    Create a User with the given username, and an InstanceUser for the
    given instance. The InstanceUser's role comes from calling make_role()
    (if provided) or from the instance's default role.
    """
    user = make_plain_user(username, password)
    if instance:
        role = make_role(instance) if make_role else instance.default_role
        iuser = InstanceUser(instance=instance, user=user,
                             role=role, admin=admin)
        iuser.save_with_user(user)
    return user
示例#12
0
def make_user(instance=None, username='******', make_role=None,
              admin=False, password='******'):
    """
    Create a User with the given username, and an InstanceUser for the
    given instance. The InstanceUser's role comes from calling make_role()
    (if provided) or from the instance's default role.
    """
    user = make_plain_user(username, password)
    if instance:
        role = make_role(instance) if make_role else instance.default_role
        iuser = InstanceUser(instance=instance, user=user,
                             role=role, admin=admin)
        iuser.save_with_user(user)
    return user
示例#13
0
文件: test_audit.py 项目: gapb/OTM2
    def setUp(self):
        self.p1 = Point(0, 0)
        self.p2 = Point(5, 5)

        self.instance1 = make_instance(point=self.p1)
        self.user = make_user_with_default_role(self.instance1, 'auser')
        self.global_role = self.instance1.default_role

        self.instance2 = make_instance(name='i2')
        self.instance2.save()

        iuser = InstanceUser(instance=self.instance2,
                             user=self.user,
                             role=self.global_role)
        iuser.save_with_user(self.user)

        for i in [self.instance1, self.instance2]:
            FieldPermission(model_name='Plot',
                            field_name='geom',
                            permission_level=FieldPermission.WRITE_DIRECTLY,
                            role=self.global_role,
                            instance=i).save()
            FieldPermission(model_name='Tree',
                            field_name='plot',
                            permission_level=FieldPermission.WRITE_DIRECTLY,
                            role=self.global_role,
                            instance=i).save()

        self.plot1 = Plot(geom=self.p1, instance=self.instance1)

        self.plot1.save_with_user(self.user)

        self.plot2 = Plot(geom=self.p2, instance=self.instance2)

        self.plot2.save_with_user(self.user)

        tree_combos = [
            (self.plot1, self.instance1, True),
            (self.plot1, self.instance1, False),
            (self.plot2, self.instance2, True),
            (self.plot2, self.instance2, False),
        ]

        for tc in tree_combos:
            plot, instance, readonly = tc
            t = Tree(plot=plot, instance=instance, readonly=readonly)

            t.save_with_user(self.user)
示例#14
0
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance, "comm")

        # Note unicode '⅀' is on purpose
        self.user1 = User(username='******',
                          password='******',
                          email='*****@*****.**',
                          organization='org111',
                          first_name='therem',
                          last_name='⅀straven')

        self.user1.save_with_user(self.commander)

        self.user2 = User(username='******',
                          password='******',
                          email='*****@*****.**',
                          first_name='genly',
                          last_name='ai',
                          allow_email_contact=True)
        self.user2.save_with_user(self.commander)

        self.user3 = User(username='******',
                          password='******',
                          email='*****@*****.**')
        self.user3.save_with_user(self.commander)

        role = make_commander_role(self.instance)
        iuser1 = InstanceUser(instance=self.instance,
                              user=self.user1,
                              role=role)
        iuser1.save_with_user(self.user1)
        iuser2 = InstanceUser(instance=self.instance,
                              user=self.user2,
                              role=role)
        iuser2.save_with_user(self.user2)

        pt = Point(0, 0)

        self.plot = Plot(geom=pt,
                         readonly=False,
                         instance=self.instance,
                         width=4)
        self.plot.save_with_user(self.user1)

        self.tree = Tree(instance=self.instance, plot=self.plot, diameter=3)
        self.tree.save_with_user(self.user2)
示例#15
0
def add_user_to_instance(request, user, instance, admin_user):
    iuser_already_exists = (InstanceUser.objects.filter(
        user_id=user.pk, instance=instance).exists())

    if iuser_already_exists:
        raise ValidationError(
            _("A user with email address '%s' has already "
              "joined this map.") % user.email)

    iuser = InstanceUser(user_id=user.pk,
                         instance=instance,
                         role=instance.default_role)
    iuser.save_with_user(admin_user)

    ctxt = {'request': request, 'instance': instance}

    send_email('invite_to_existing_user', ctxt, (user.email, ))
示例#16
0
    def setUp(self):
        self.p1 = Point(0, 0)
        self.p2 = Point(5, 5)

        self.instance1 = make_instance(point=self.p1)
        self.user = make_user_with_default_role(self.instance1, 'auser')
        self.global_role = self.instance1.default_role

        self.instance2 = make_instance(name='i2')
        self.instance2.save()

        iuser = InstanceUser(instance=self.instance2, user=self.user,
                             role=self.global_role)
        iuser.save_with_user(self.user)

        for i in [self.instance1, self.instance2]:
            FieldPermission(model_name='Plot', field_name='geom',
                            permission_level=FieldPermission.WRITE_DIRECTLY,
                            role=self.global_role,
                            instance=i).save()
            FieldPermission(model_name='Tree', field_name='plot',
                            permission_level=FieldPermission.WRITE_DIRECTLY,
                            role=self.global_role,
                            instance=i).save()

        self.plot1 = Plot(geom=self.p1, instance=self.instance1)

        self.plot1.save_with_user(self.user)

        self.plot2 = Plot(geom=self.p2, instance=self.instance2)

        self.plot2.save_with_user(self.user)

        tree_combos = [
            (self.plot1, self.instance1, True),
            (self.plot1, self.instance1, False),
            (self.plot2, self.instance2, True),
            (self.plot2, self.instance2, False),
        ]

        for tc in tree_combos:
            plot, instance, readonly = tc
            t = Tree(plot=plot, instance=instance, readonly=readonly)

            t.save_with_user(self.user)
示例#17
0
def add_user_to_instance(request, user, instance, admin_user):
    iuser_already_exists = (InstanceUser.objects
                            .filter(user_id=user.pk,
                                    instance=instance).exists())

    if iuser_already_exists:
        raise ValidationError(_("A user with email address '%s' has already "
                              "joined this map.") % user.email)

    iuser = InstanceUser(user_id=user.pk,
                         instance=instance,
                         role=instance.default_role)
    iuser.save_with_user(admin_user)

    ctxt = {'request': request,
            'instance': instance}

    send_email('invite_to_existing_user', ctxt, (user.email,))
示例#18
0
def create_instance_users_from_invites(request, user, invites):
    ctxt = {'user': user,
            'request': request}
    for invite in invites:
        instance = invite.instance
        iuser = InstanceUser(user=user,
                             instance=instance,
                             role=invite.role,
                             admin=invite.admin)
        iuser.save_with_user(user)
        invite.accepted = True
        invite.save()

        emails_to_notify = InstanceUser.objects \
            .filter(instance=instance, admin=True) \
            .values_list('user__email', flat=True)

        send_email('user_joined_instance', ctxt, emails_to_notify)
示例#19
0
def create_instance_users_from_invites(request, user, invites):
    ctxt = {'user': user, 'request': request}
    for invite in invites:
        instance = invite.instance
        iuser = InstanceUser(user=user,
                             instance=instance,
                             role=invite.role,
                             admin=invite.admin)
        iuser.save_with_user(user)
        invite.accepted = True
        invite.save()

        # The user who created the invitation is always notified when the
        # invitation is accepted. A plugin function provides additional email
        # addresses. The concatenation of the two lists is wrapped with `set()`
        # to remove duplicates.
        emails_to_notify = set([invite.created_by.email] +
                               invitation_accepted_notification_emails(invite))

        send_email('user_joined_instance', ctxt, emails_to_notify)
示例#20
0
文件: tests.py 项目: nvh3010/otm-core
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance, "comm")

        # Note unicode '⅀' is on purpose
        self.user1 = User(
            username="******",
            password="******",
            email="*****@*****.**",
            organization="karhide",
            first_name="therem",
            last_name="⅀straven",
        )

        self.user1.save_with_user(self.commander)

        self.user2 = User(
            username="******",
            password="******",
            email="*****@*****.**",
            first_name="genly",
            last_name="ai",
            allow_email_contact=True,
        )
        self.user2.save_with_user(self.commander)

        self.user3 = User(username="******", password="******", email="*****@*****.**")
        self.user3.save_with_user(self.commander)

        role = make_commander_role(self.instance)
        iuser1 = InstanceUser(instance=self.instance, user=self.user1, role=role)
        iuser1.save_with_user(self.user1)
        iuser2 = InstanceUser(instance=self.instance, user=self.user2, role=role)
        iuser2.save_with_user(self.user2)

        self.plot = Plot(geom=self.instance.center, readonly=False, instance=self.instance, width=4)
        self.plot.save_with_user(self.user1)

        self.tree = Tree(instance=self.instance, plot=self.plot, diameter=3)
        self.tree.save_with_user(self.user2)
示例#21
0
    def setUp(self):
        self.p1 = Point(0, 0)
        self.p2 = Point(5, 5)

        self.instance1 = make_instance(point=self.p1)
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.user = make_user_with_default_role(self.instance1, 'auser')
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.instance2 = make_instance(name='i2')
        self.instance2.save()

        iuser = InstanceUser(instance=self.instance2,
                             user=self.user,
                             role=self.instance1.default_role)
        iuser.save_with_user(self.user)

        self.plot1 = Plot(geom=self.p1, instance=self.instance1)

        self.plot1.save_with_user(self.user)

        self.plot2 = Plot(geom=self.p2, instance=self.instance2)

        self.plot2.save_with_user(self.user)

        tree_combos = [
            (self.plot1, self.instance1, True),
            (self.plot1, self.instance1, False),
            (self.plot2, self.instance2, True),
            (self.plot2, self.instance2, False),
        ]

        for plot, instance, readonly in tree_combos:
            t = Tree(plot=plot, instance=instance, readonly=readonly)

            t.save_with_user(self.user)
示例#22
0
    def setUp(self):
        self.p1 = Point(0, 0)
        self.p2 = Point(5, 5)

        self.instance1 = make_instance(point=self.p1)
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.user = make_user_with_default_role(self.instance1, 'auser')
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.instance2 = make_instance(name='i2')
        self.instance2.save()

        iuser = InstanceUser(instance=self.instance2, user=self.user,
                             role=self.instance1.default_role)
        iuser.save_with_user(self.user)

        self.plot1 = Plot(geom=self.p1, instance=self.instance1)

        self.plot1.save_with_user(self.user)

        self.plot2 = Plot(geom=self.p2, instance=self.instance2)

        self.plot2.save_with_user(self.user)

        tree_combos = [
            (self.plot1, self.instance1, True),
            (self.plot1, self.instance1, False),
            (self.plot2, self.instance2, True),
            (self.plot2, self.instance2, False),
        ]

        for plot, instance, readonly in tree_combos:
            t = Tree(plot=plot, instance=instance, readonly=readonly)

            t.save_with_user(self.user)
示例#23
0
文件: tests.py 项目: cgarrard/OTM2
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance, "comm")

        # Note unicode '⅀' is on purpose
        self.user1 = User(username='******', password='******',
                          email='*****@*****.**',
                          organization='org111',
                          first_name='therem', last_name='⅀straven')

        self.user1.save_with_user(self.commander)

        self.user2 = User(username='******', password='******',
                          email='*****@*****.**',
                          first_name='genly', last_name='ai',
                          allow_email_contact=True)
        self.user2.save_with_user(self.commander)

        self.user3 = User(username='******', password='******',
                          email='*****@*****.**')
        self.user3.save_with_user(self.commander)

        role = make_commander_role(self.instance)
        iuser1 = InstanceUser(instance=self.instance, user=self.user1,
                              role=role)
        iuser1.save_with_user(self.user1)
        iuser2 = InstanceUser(instance=self.instance, user=self.user2,
                              role=role)
        iuser2.save_with_user(self.user2)

        pt = Point(0, 0)

        self.plot = Plot(geom=pt, readonly=False, instance=self.instance,
                         width=4)
        self.plot.save_with_user(self.user1)

        self.tree = Tree(instance=self.instance, plot=self.plot, diameter=3)
        self.tree.save_with_user(self.user2)
示例#24
0
def create_instance_users_from_invites(request, user, invites):
    ctxt = {'user': user,
            'request': request}
    for invite in invites:
        instance = invite.instance
        iuser = InstanceUser(user=user,
                             instance=instance,
                             role=invite.role,
                             admin=invite.admin)
        iuser.save_with_user(user)
        invite.accepted = True
        invite.save()

        # The user who created the invitation is always notified when the
        # invitation is accepted. A plugin function provides additional email
        # addresses. The concatenation of the two lists is wrapped with `set()`
        # to remove duplicates.
        emails_to_notify = set(
            [invite.created_by.email]
            + invitation_accepted_notification_emails(invite)
        )

        send_email('user_joined_instance', ctxt, emails_to_notify)
示例#25
0
    def test_user_roles_updated(self):
        iuser = InstanceUser(user=self.user2, instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        new_role = Role(name='Ambassador', instance=self.instance,
                        rep_thresh=0)
        new_role.save()

        body = {'users':
                {iuser.pk:
                 {'role': new_role.pk, 'admin': False}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander),
            self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, False)

        body = {'users':
                {iuser.pk: {'role': new_role.pk, 'admin': True}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander),
            self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, True)
示例#26
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission_level=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        if options.get('delete', False):
            # Can't delete through the ORM because it will pull all the data
            # into memory for signal handlers, then run out of memory and crash
            # BUT... cascading delete is not handled at the DB level, so we
            # need to delete from all related tables in the right order

            n_photo = MapFeaturePhoto.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_treephoto t
                    WHERE t.mapfeaturephoto_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeaturephoto p
                         WHERE p.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeaturephoto t WHERE t.instance_id = %s',  # NOQA
                    (instance.pk, ))
            self.stdout.write("Deleted %s photos" % n_photo)

            n_trees = Tree.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_tree t WHERE t.instance_id = %s',
                    (instance.pk, ))
            self.stdout.write("Deleted %s trees" % n_trees)

            n_favorites = Favorite.objects \
                .filter(map_feature__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_favorite f
                    WHERE f.map_feature_id IN
                        (SELECT id
                         FROM treemap_mapfeature m
                         WHERE m.instance_id = %s)
                    """, (instance.pk, ))
            self.stdout.write("Deleted %s favorites" % n_favorites)

            n_comments = EnhancedThreadedComment.objects \
                .filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcommentflag f
                    WHERE f.comment_id IN
                        (SELECT threadedcomment_ptr_id
                         FROM otm_comments_enhancedthreadedcomment c
                         WHERE c.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcomment c
                    WHERE c.instance_id = %s
                    """, (instance.pk, ))
            self.stdout.write("Deleted %s comments" % n_comments)

            n_rows = TreeImportRow.objects \
                .filter(plot__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    UPDATE importer_treeimportrow r
                    SET plot_id = NULL
                    WHERE r.import_event_id IN
                        (SELECT id
                         FROM importer_treeimportevent e
                         WHERE e.instance_id = %s)
                    """, (instance.pk, ))
            self.stdout.write("Nulled out plot in %s import rows" % n_rows)

            n_features = MapFeature.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_plot p
                    WHERE p.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_bioswale b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_raingarden b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_rainbarrel b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_polygonalmapfeature b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeature f WHERE f.instance_id = %s',  # NOQA
                    (instance.pk, ))
            self.stdout.write("Deleted %s map features" % n_features)

            n_audits = Audit.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
    DELETE FROM treemap_audit a
    WHERE a.instance_id = %s
    AND a.model NOT IN
    ('InstanceUser', 'Species', 'ITreeCodeOverride', 'EnhancedInstance')
                    """, (instance.pk, ))
            self.stdout.write("Deleted %s audits" % n_audits)

        instance.update_revs('geo_rev', 'eco_rev', 'universal_rev')

        return instance, user
示例#27
0
文件: util.py 项目: RickMohr/otm-core
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        if options.get('delete', False):
            # Can't delete through the ORM because it will pull all the data
            # into memory for signal handlers, then run out of memory and crash
            # BUT... cascading delete is not handled at the DB level, so we
            # need to delete from all related tables in the right order

            n_photo = MapFeaturePhoto.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_treephoto t
                    WHERE t.mapfeaturephoto_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeaturephoto p
                         WHERE p.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeaturephoto t WHERE t.instance_id = %s',  # NOQA
                    (instance.pk,))
            self.stdout.write("Deleted %s photos" % n_photo)

            n_trees = Tree.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_tree t WHERE t.instance_id = %s',
                    (instance.pk,))
            self.stdout.write("Deleted %s trees" % n_trees)

            n_favorites = Favorite.objects \
                .filter(map_feature__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_favorite f
                    WHERE f.map_feature_id IN
                        (SELECT id
                         FROM treemap_mapfeature m
                         WHERE m.instance_id = %s)
                    """,
                    (instance.pk,))
            self.stdout.write("Deleted %s favorites" % n_favorites)

            n_comments = EnhancedThreadedComment.objects \
                .filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcommentflag f
                    WHERE f.comment_id IN
                        (SELECT threadedcomment_ptr_id
                         FROM otm_comments_enhancedthreadedcomment c
                         WHERE c.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcomment c
                    WHERE c.instance_id = %s
                    """,
                    (instance.pk,))
            self.stdout.write("Deleted %s comments" % n_comments)

            n_rows = TreeImportRow.objects \
                .filter(plot__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    UPDATE importer_treeimportrow r
                    SET plot_id = NULL
                    WHERE r.import_event_id IN
                        (SELECT id
                         FROM importer_treeimportevent e
                         WHERE e.instance_id = %s)
                    """,
                    (instance.pk,))
            self.stdout.write("Nulled out plot in %s import rows" % n_rows)

            n_features = MapFeature.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_plot p
                    WHERE p.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_bioswale b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_raingarden b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_rainbarrel b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_polygonalmapfeature b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeature f WHERE f.instance_id = %s',  # NOQA
                    (instance.pk,))
            self.stdout.write("Deleted %s map features" % n_features)

            n_audits = Audit.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
    DELETE FROM treemap_audit a
    WHERE a.instance_id = %s
    AND a.model NOT IN
    ('InstanceUser', 'Species', 'ITreeCodeOverride', 'EnhancedInstance')
                    """,
                    (instance.pk,))
            self.stdout.write("Deleted %s audits" % n_audits)

        return instance, user
示例#28
0
def make_instance_user(instance, user):
    iu = InstanceUser(instance=instance, user=user, role=instance.default_role)
    iu.save_with_user(User._system_user)
示例#29
0
def make_instance_user(instance, user):
    iu = InstanceUser(instance=instance, user=user, role=instance.default_role)
    iu.save_with_user(User._system_user)