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 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)
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_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
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
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)
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)
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
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)
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, ))
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,))
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)
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)
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)
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)
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)
def wrapper(request, instance, *args, **kwargs): # prevent circular imports from treemap.models import InstanceUser if request.user.get_instance_user(instance) is None: if instance.feature_enabled('auto_add_instance_user'): InstanceUser( instance=instance, user=request.user, role=instance.default_role ).save_with_user(request.user) else: raise PermissionDenied return view_fn(request, instance, *args, **kwargs)
def wrapper(request, instance, *args, **kwargs): # prevent circular imports from treemap.models import InstanceUser if request.user.get_instance_user(instance) is None: if instance.feature_enabled('auto_add_instance_user'): InstanceUser(instance=instance, user=request.user, role=instance.default_role).save_with_user( request.user) else: raise FeatureNotEnabledException( 'Users cannot join this map automatically') return view_fn(request, instance, *args, **kwargs)
def global_settings(request): last_instance = get_last_visited_instance(request) if hasattr(request, 'user') and request.user.is_authenticated(): last_effective_instance_user =\ request.user.get_effective_instance_user(last_instance) _update_last_seen(last_effective_instance_user) else: if hasattr(request, 'instance'): instance = request.instance default_role = instance.default_role last_effective_instance_user = InstanceUser(role=default_role, instance=instance) else: last_effective_instance_user = None if hasattr(request, 'instance') and request.instance.logo: logo_url = request.instance.logo.url else: logo_url = settings.STATIC_URL + "img/logo.png" try: comment_file_path = finders.find('version.txt') with open(comment_file_path, 'r') as f: header_comment = f.read() except: header_comment = "Version information not available\n" term = copy.copy(REPLACEABLE_TERMS) if hasattr(request, 'instance'): term.update(request.instance.config.get('terms', {})) ctx = { 'SITE_ROOT': settings.SITE_ROOT, 'settings': settings, 'last_instance': last_instance, 'last_effective_instance_user': last_effective_instance_user, 'logo_url': logo_url, 'header_comment': header_comment, 'term': term, } return ctx
def setUp(self): super(VisitedInstancesTests, self).setUp() self.instance1 = make_instance(1, is_public=True) self.instance2 = make_instance(2, is_public=True) self.instance3 = make_instance(3, is_public=False) self.instance4 = make_instance(4, is_public=False) self.user = make_user_with_default_role(self.instance, 'joe') self.user.set_password('joe') self.user.save() self.request = make_request(user=self.user) InstanceUser(instance=self.instance4, user=self.user, role=self.instance4.default_role).save_base() middleware = SessionMiddleware() middleware.process_request(self.request) self.request.session.save()
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)
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
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
def handle(self, *args, **options): if len(args) != 1: raise Exception('Expected instance name as the first argument') name = args[0] if not options['user']: raise Exception('An admin user must be specified. with "--user"') if options.get('center', None) and options.get('geojson', None): raise Exception('You must specifiy only one of ' '"center" and "geojson"') elif (not options.get('center', None) and not options.get('geojson', None)): raise Exception('You must specifiy at least one of ' '"center" and "geojson"') if options['center']: center = options['center'].split(',') if len(center) != 2: raise Exception('Center should be a lat,lng pair in SRID 4326') center_pt = Point(float(center[0]), float(center[1]), srid=4326) # Bounding box built in web mercator to have units in meters center_pt.transform(3857) x = center_pt.x y = center_pt.y offset = 50000 bounds = Polygon( ((x - offset, y - offset), (x - offset, y + offset), (x + offset, y + offset), (x + offset, y - offset), (x - offset, y - offset))) bounds = MultiPolygon((bounds, )) else: bounds = GEOSGeometry(open(options['geojson'], srid=4326).read()) if not options.get('url_name', None): raise Exception('You must specify a "url_name" starting with a ' 'lowercase letter and containing lowercase ' 'letters, numbers, and dashes ("-")') url_name = options.get('url_name') instance = Instance(config={}, name=name, bounds=bounds, is_public=True, url_name=url_name) instance.seed_with_dummy_default_role() instance.full_clean() instance.save() instance.boundaries = Boundary.objects.filter(geom__intersects=bounds) role = Role.objects.create( name='user', instance=instance, rep_thresh=0, default_permission=FieldPermission.WRITE_DIRECTLY) add_default_permissions(instance, roles=[role]) instance.default_role = role instance.save() user = User.objects.get(username=options['user']) InstanceUser(instance=instance, user=user, role=role, admin=True).save_with_user(user)
def global_settings(request): last_instance = get_last_visited_instance(request) if hasattr(request, 'user') and request.user.is_authenticated(): last_effective_instance_user =\ request.user.get_effective_instance_user(last_instance) _update_last_seen(last_effective_instance_user) else: if hasattr(request, 'instance'): instance = request.instance default_role = instance.default_role last_effective_instance_user = InstanceUser( role=default_role, instance=instance) else: last_effective_instance_user = None if hasattr(request, 'instance') and request.instance.logo: logo_url = request.instance.logo.url else: logo_url = settings.STATIC_URL + "img/logo.png" try: comment_file_path = finders.find('version.txt') with open(comment_file_path, 'r') as f: header_comment = f.read() except: header_comment = "Version information not available\n" term = copy.copy(REPLACEABLE_TERMS) if hasattr(request, 'instance'): term.update(request.instance.config.get('terms', {})) # config.get('terms') above populates the term context variable with # model terminology provided it has been customized for the treemap # instance, but fails to populate it with the default terminology. The # for loop below ensures that term is populated with model terminology # whether it has been customized or not. # Convertible is the base class where the terminology class property is # defined, so its leaf subclasses are the ones with default terminology # we might care about. # leaf_models_of_class uses recursive descent through the # clz.__subclasses__ attributes, but it only iterates through a total # of around ten nodes at present, so it is unlikely to be a performance # problem. for clz in leaf_models_of_class(Convertible): term.update({ clz.__name__: clz.terminology(request.instance)}) ctx = { 'SITE_ROOT': settings.SITE_ROOT, 'settings': settings, 'last_instance': last_instance, 'last_effective_instance_user': last_effective_instance_user, 'logo_url': logo_url, 'header_comment': header_comment, 'term': term, 'embed': request_is_embedded(request), 'datepicker_start_date': datetime.min.replace(year=1900), } return ctx
def make_instance_user(instance, user): iu = InstanceUser(instance=instance, user=user, role=instance.default_role) iu.save_with_user(User._system_user)
def handle(self, *args, **options): if len(args) != 1: raise Exception('Expected instance name as the first argument') name = args[0] if not options['user']: raise Exception('An admin user must be specified. with "--user"') if options.get('center', None) and options.get('geojson', None): raise Exception('You must specifiy only one of ' '"center" and "geojson"') elif (not options.get('center', None) and not options.get('geojson', None)): raise Exception('You must specifiy at least one of ' '"center" and "geojson"') if options['center']: center = options['center'].split(',') if len(center) != 2: raise Exception('Center should be a lon,lat pair') center_pt = Point(float(center[0]), float(center[1]), srid=4326) # Bounding box built in web mercator to have units in meters center_pt.transform(3857) x = center_pt.x y = center_pt.y instance_bounds = InstanceBounds.create_from_point(x, y) else: geom = GEOSGeometry(open(options['geojson'], srid=4326).read()) instance_bounds = InstanceBounds.objects.create(geom=geom) if not options.get('url_name', None): raise Exception('You must specify a "url_name" starting with a ' 'lowercase letter and containing lowercase ' 'letters, numbers, and dashes ("-")') url_name = options.get('url_name') instance = Instance(config={}, name=name, bounds=instance_bounds, is_public=True, url_name=url_name) instance.seed_with_dummy_default_role() instance.full_clean() instance.save() instance.boundaries = Boundary.objects.filter( geom__intersects=instance_bounds.geom) role = Role.objects.create( name='user', instance=instance, rep_thresh=0, default_permission_level=FieldPermission.WRITE_DIRECTLY) create_stewardship_udfs(instance) add_species_to_instance(instance) add_default_permissions(instance, roles=[role]) add_instance_permissions([role]) eco_benefits_conversion = \ BenefitCurrencyConversion.get_default_for_instance(instance) if eco_benefits_conversion: eco_benefits_conversion.save() instance.eco_benefits_conversion = eco_benefits_conversion instance.default_role = role instance.save() user = User.objects.get(username=options['user']) InstanceUser(instance=instance, user=user, role=role, admin=True).save_with_user(user)
def handle(self, *args, **options): if len(args) != 1: raise Exception('Expected instance name as the first argument') name = args[0] if not options['user']: logger.warning('An admin user was not specified. While not a ' 'problem initially, no users will be able to ' 'modify many parts of this instance. It is ' 'recommended that you create a user first and call ' 'this command with "--user"') if options.get('center', None) and options.get('geojson', None): raise Exception('You must specifiy only one of ' '"center" and "geojson"') elif (not options.get('center', None) and not options.get('geojson', None)): raise Exception('You must specifiy at least one of ' '"center" and "geojson"') if options['center']: center = options['center'].split(',') if len(center) != 2: raise Exception('Center should be an x,y pair in EPSG3857') x = int(center[0]) y = int(center[1]) offset = 50000 bounds = Polygon( ((x - offset, y - offset), (x - offset, y + offset), (x + offset, y + offset), (x + offset, y - offset), (x - offset, y - offset))) bounds = MultiPolygon((bounds, )) else: bounds = GEOSGeometry(open(options['geojson']).read()) if not options.get('url_name', None): raise Exception('You must specify a "url_name" starting with a ' 'lowercase letter and containing lowercase ' 'letters, numbers, and dashes ("-")') url_name = options.get('url_name') # Instances need roles and roles needs instances... crazy # stuff we're going to create the needed role below however, # we'll temporarily use a 'dummy role'. The dummy role has # no instance. dummy_roles = Role.objects.filter(instance__isnull=True) if len(dummy_roles) == 0: dummy_role = Role.objects.create(name='empty', rep_thresh=0) else: dummy_role = dummy_roles[0] instance = Instance(config={}, name=name, bounds=bounds, is_public=True, default_role=dummy_role, url_name=url_name) instance.full_clean() instance.save() instance.boundaries = Boundary.objects.filter(geom__intersects=bounds) role = Role.objects.create( name='user', instance=instance, rep_thresh=0, default_permission=FieldPermission.WRITE_DIRECTLY) add_default_permissions(instance, roles=[role]) instance.default_role = role instance.save() user = User.objects.get(pk=options['user']) InstanceUser(instance=instance, user=user, role=role, admin=True).save_with_user(user)
def create_instance_users(instance): for user in User.objects.all(): iuser = InstanceUser(instance=instance, user=user, role=instance.default_role) iuser.save()