def _do_fake_registration(self): # Create a Zone and DeviceZone to fool the Device into thinking it's registered zone = Zone(name="The Danger Zone", description="Welcome to it.") zone.save() device = Device.get_own_device() deviceZone = DeviceZone(device=device, zone=zone) deviceZone.save()
class ZoneDeletionTestCase(OrganizationManagementTestCase): def setUp(self): super(ZoneDeletionTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() def test_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().accept() self.browser_wait_for_no_element(".zone-delete-link") time.sleep(1) self.browser_check_django_message(message_type="success", contains="successfully deleted") with self.assertRaises(NoSuchElementException): self.assertEqual(self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link no longer exists.") def test_cancel_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().dismiss() self.assertNotEqual(self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link still exists.") self.browser_check_django_message(num_messages=0) def test_issue_697_part1(self): self.facility = Facility(name=self.FACILITY_NAME) self.facility.save() self.test_delete_zone_from_org_admin()
def handle(self, *args, **options): if settings.CENTRAL_SERVER: raise CommandError( "You shouldn't be trying to put the central server on a sharing network!" ) own_device = Device.get_own_device() if DeviceZone.objects.filter(device=own_device).count() > 0: raise CommandError( "This device already belongs to a sharing network.") zone_name = args[0] if len( args) >= 1 else "Sharing network for Device %s" % own_device.name zone_description = args[1] if (len(args) >= 2 and args[1]) else "" # Create the zone self.stdout.write("Generating a sharing network.\n") zone = Zone(name=zone_name, description=zone_description) zone.save() # this will sign the zone with the current device # Create the zone invitation--you're invited to a party of one! self.stdout.write( "Generating a sharing network invitation--from me, to me!\n") invitation = ZoneInvitation.generate(zone=zone, invited_by=own_device) invitation.save() invitation.claim(used_by=own_device) self.stdout.write("Done!\n")
class CentralFacilityUserFormTestCase(OrganizationManagementTestCase): def setUp(self): super(CentralFacilityUserFormTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() self.facility = Facility(name=self.FACILITY_NAME, zone_fallback=self.zone) self.facility.save() self.user.facility = self.facility self.user.save() def test_add_student(self): self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browse_to( '%s?facility=%s' % (self.reverse('add_facility_student'), self.facility.id)) self.browser.find_element_by_id('id_username').send_keys('s') self.browser.find_element_by_id('id_password_first').send_keys( 'password') self.browser.find_element_by_id('id_password_recheck').send_keys( 'password') self.browser.find_elements_by_class_name('submit')[0].click() self.browser_check_django_message(message_type="success", contains="successfully created")
def register_public_key_server(request): if request.method == 'POST': form = RegisteredDevicePublicKeyForm(request.user, data=request.POST) if form.is_valid(): form.save() zone_id = form.data["zone"] org_id = Zone.objects.get(id=zone_id).get_org().id callback_url = form.cleaned_data.get("callback_url", None) if callback_url: # New style: go directly to the origin page, which will force a sync to occur (no reason to ping refresh) # This is better for the current force_job return HttpResponseRedirect(callback_url) else: # Old style, for clients that don't send a callback url messages.success( request, _("The device's public key has been successfully registered. You may now close this window." )) return HttpResponseRedirect( reverse("zone_management", kwargs={ 'org_id': org_id, 'zone_id': zone_id })) else: # This is hackish--we now create default organizations and zones for users, based on their # registration information. For previous users, however, we don't. And we don't # give any links / instructions for creating zones when they get here. # So, rather than block them, let's create an org and zone for them, so that # at least they can proceed directly. if request.user.organization_set.count() == 0: # Localizing central-only import from central.models import Organization org = Organization(name="Your organization", owner=request.user) org.save() org.add_member(request.user) org.save() if not sum( [org.zones.count() for org in request.user.organization_set.all()]): org = request.user.organization_set.all()[0] zone = Zone(name="Default zone") zone.save() org.add_zone(zone) # callback_url: 0.10.3 and higher (distributed server) # prev: 0.10.3 and higher (central server) # # Note: can't use referer, because this breaks if the user is redirected # to the central server login page--gets confusing. form = RegisteredDevicePublicKeyForm( request.user, callback_url=request.REQUEST.get("callback_url") or request.REQUEST.get("prev"), ) return { "form": form, }
def test_valid_trusted(self): """ Chain of trust: 1. Zone created by this device 2. Another device joins (no central server) through an invitation """ own_device = Device.get_own_device() zone = Zone(name="test_zone") zone.save() new_device = Device(name="new_device") # make a new device new_device.set_key(Key()) new_device.save() # get an ID new_device.get_metadata().save() # Now create an invitation, and claim that invitation for the new device. invitation = ZoneInvitation.generate(zone=zone, invited_by=own_device) invitation.claim(used_by=new_device) self.assertEqual( invitation.used_by, new_device, "Invitation should now be used by device %s" % new_device) self.assertEqual( DeviceZone.objects.filter(device=new_device).count(), 1, "There should be a DeviceZone for device %s" % new_device) self.assertEqual( DeviceZone.objects.get(device=new_device).zone, zone, "DeviceZone for device %s should be zone %s" % (new_device, zone)) # Now get a chain of trust establishing the new device on the zone chain = ChainOfTrust(zone=zone, device=new_device) self.assertTrue(chain.verify(), "Chain of trust should verify.")
def test_valid_trusted(self): """ Chain of trust: 1. Zone created by this device 2. Another device joins (no central server) through an invitation """ own_device = Device.get_own_device() zone = Zone(name="test_zone") zone.save() new_device = Device(name="new_device") # make a new device new_device.set_key(Key()) new_device.save() # get an ID new_device.get_metadata().save() # Now create an invitation, and claim that invitation for the new device. invitation = ZoneInvitation.generate(zone=zone, invited_by=own_device) invitation.claim(used_by=new_device) self.assertEqual(invitation.used_by, new_device, "Invitation should now be used by device %s" % new_device) self.assertEqual(DeviceZone.objects.filter(device=new_device).count(), 1, "There should be a DeviceZone for device %s" % new_device) self.assertEqual(DeviceZone.objects.get(device=new_device).zone, zone, "DeviceZone for device %s should be zone %s" % (new_device, zone)) # Now get a chain of trust establishing the new device on the zone chain = ChainOfTrust(zone=zone, device=new_device) self.assertTrue(chain.verify(), "Chain of trust should verify.")
class ZoneDeletionTestCase(OrganizationManagementTestCase): def setUp(self): super(ZoneDeletionTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() def test_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().accept() self.browser_wait_for_no_element(".zone-delete-link") self.browser_check_django_message(message_type="success", contains="successfully deleted") with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link is gone.") def test_cancel_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().dismiss() self.assertNotEqual( self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link still exists.") self.browser_check_django_message(num_messages=0) def test_cannot_delete_full_zone(self): # Save zone info, but without adding self.devicezone = DeviceZone(device=Device.get_own_device(), zone=self.zone) self.devicezone.save() # Check on the org management page self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link is gone.") # Follow the link, and confirm on the zone management page. zone_url = self.browser.find_element_by_css_selector( ".zone-manage-link").get_attribute("href") self.browse_to(zone_url) self.assertEqual(self.browser.current_url, zone_url, "Expect link to go to zone management page") with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link is gone.") def test_issue_697_part1(self): self.facility = Facility(name=self.FACILITY_NAME) self.facility.save() self.test_delete_zone_from_org_admin()
class OrganizationDeletionTestCase(OrganizationManagementTestCase): def test_delete_org(self): """Delete an empty org""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears." ) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon appears." ) self.browser.find_element_by_css_selector(".icon-trash").click() self.browser.switch_to_alert().accept() self.browser_wait_for_no_element(".icon-trash") self.browser_check_django_message(message_type="success", contains="successfully deleted") with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon is gone." ) def test_cancel_delete_org(self): """Click to delete an empty org, then choose CANCEL""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears." ) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon appears." ) self.browser.find_element_by_css_selector(".icon-trash").click() self.browser.switch_to_alert().dismiss() self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon appears." ) self.browser_check_django_message(num_messages=0) def test_cannot_delete_full_org(self): """Confirm no option to delete an org with data""" # Save zone info, but without adding self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears." ) with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon does not appear.", ) def test_issue_697(self): self.facility = Facility(name=self.FACILITY_NAME) self.facility.save() self.test_delete_org()
class OrganizationDeletionTestCase(OrganizationManagementTestCase): def test_delete_org(self): """Delete an empty org""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears.") self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon appears.") self.browser.find_element_by_css_selector(".icon-trash").click() self.browser.switch_to_alert().accept() self.browser_wait_for_no_element(".icon-trash") self.browser_check_django_message(message_type="success", contains="successfully deleted") with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon is gone.") def test_cancel_delete_org(self): """Click to delete an empty org, then choose CANCEL""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears.") self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon appears.") self.browser.find_element_by_css_selector(".icon-trash").click() self.browser.switch_to_alert().dismiss() self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon appears.") self.browser_check_django_message(num_messages=0) def test_cannot_delete_full_org(self): """Confirm no option to delete an org with data""" # Save zone info, but without adding self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual( self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears.") with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon does not appear.") def test_issue_697_part2(self): self.facility = Facility(name=self.FACILITY_NAME) self.facility.save() self.test_delete_org()
def do_fake_registration(): """ Register the device, in case some feature being tested depends on it. Will be undone by the database teardown. """ # Create a Zone and DeviceZone to fool the Device into thinking it's registered zone = Zone(name="The Danger Zone", description="Welcome to it.") zone.save() device = Device.get_own_device() device_zone = DeviceZone(device=device, zone=zone) device_zone.save()
def setUp(self): super(CentralFacilityUserFormTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() self.facility = Facility(name=self.FACILITY_NAME, zone_fallback=self.zone) self.facility.save() self.user.facility = self.facility self.user.save()
def test_cannot_delete_full_org(self): """Confirm no option to delete an org with data""" # Save zone info, but without adding self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual(self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears.") with self.assertRaises(NoSuchElementException): self.assertEqual(self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon does not appear.")
class ZoneDeletionTestCase(OrganizationManagementTestCase): def setUp(self): super(ZoneDeletionTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() def test_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().accept() self.browser_wait_for_no_element(".zone-delete-link") self.browser_check_django_message(message_type="success", contains="successfully deleted") with self.assertRaises(NoSuchElementException): self.assertEqual(self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link is gone.") def test_cancel_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().dismiss() self.assertNotEqual(self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link still exists.") self.browser_check_django_message(num_messages=0) def test_cannot_delete_full_zone(self): # Save zone info, but without adding self.devicezone = DeviceZone(device=Device.get_own_device(), zone=self.zone) self.devicezone.save() # Check on the org management page self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) with self.assertRaises(NoSuchElementException): self.assertEqual(self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link is gone.") # Follow the link, and confirm on the zone management page. zone_url = self.browser.find_element_by_css_selector(".zone-manage-link").get_attribute("href") self.browse_to(zone_url) self.assertEqual(self.browser.current_url, zone_url, "Expect link to go to zone management page") with self.assertRaises(NoSuchElementException): self.assertEqual(self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link is gone.") def test_issue_697_part1(self): self.facility = Facility(name=self.FACILITY_NAME) self.facility.save() self.test_delete_zone_from_org_admin()
def register_public_key_server(request): if request.method == 'POST': form = RegisteredDevicePublicKeyForm(request.user, data=request.POST) if form.is_valid(): form.save() zone_id = form.data["zone"] org_id = Zone.objects.get(id=zone_id).get_org().id callback_url = form.cleaned_data.get("callback_url", None) if callback_url: # New style: go directly to the origin page, which will force a sync to occur (no reason to ping refresh) # This is better for the current force_job return HttpResponseRedirect(callback_url) else: # Old style, for clients that don't send a callback url messages.success(request, _("The device's public key has been successfully registered. You may now close this window.")) return HttpResponseRedirect(reverse("zone_management", kwargs={'org_id': org_id, 'zone_id': zone_id})) else: # This is hackish--we now create default organizations and zones for users, based on their # registration information. For previous users, however, we don't. And we don't # give any links / instructions for creating zones when they get here. # So, rather than block them, let's create an org and zone for them, so that # at least they can proceed directly. if request.user.organization_set.count() == 0: # Localizing central-only import from central.models import Organization org = Organization(name="Your organization", owner=request.user) org.save() org.add_member(request.user) org.save() if not sum([org.zones.count() for org in request.user.organization_set.all()]): org = request.user.organization_set.all()[0] zone = Zone(name="Default zone") zone.save() org.add_zone(zone) # callback_url: 0.10.3 and higher (distributed server) # prev: 0.10.3 and higher (central server) # # Note: can't use referer, because this breaks if the user is redirected # to the central server login page--gets confusing. form = RegisteredDevicePublicKeyForm( request.user, callback_url = request.REQUEST.get("callback_url") or request.REQUEST.get("prev"), ) return { "form": form, }
def get_or_create_headless_organization(cls, refresh_zones=False): """ Retrieve the organization encapsulating all headless zones. """ if cls.HEADLESS_ORG_PK is not None: # Already exists and cached, just query fast and return headless_org = cls.objects.get(pk=cls.HEADLESS_ORG_PK) else: # Potentially inefficient query, so limit this to once per server thread # by caching the results. Here, we've had a cache miss headless_orgs = cls.objects.filter(name=cls.HEADLESS_ORG_NAME) if not headless_orgs: # Cache miss because the org actually doesn't exist. Create it! headless_org = Organization(name=cls.HEADLESS_ORG_NAME) headless_org.save(**({cls.HEADLESS_ORG_SAVE_FLAG: True})) cls.HEADLESS_ORG_PK = headless_org.pk else: # Cache miss because it's the first relevant query since this thread started. assert len(headless_orgs) == 1, "Cannot have multiple HEADLESS ZONE organizations" cls.HEADLESS_ORG_PK = headless_orgs[0].pk headless_org = headless_orgs[0] # TODO(bcipolli): remove this code! # # In the future, when we self-register headless zones, we'll # add them directly to the headless organization. # For now, we'll have to do an exhaustive search. if refresh_zones: headless_org.zones.add(*Zone.get_headless_zones()) return headless_org
def get_or_create_headless_organization(cls, refresh_zones=False): """ Retrieve the organization encapsulating all headless zones. """ if cls.HEADLESS_ORG_PK is not None: # Already exists and cached, just query fast and return headless_org = cls.objects.get(pk=cls.HEADLESS_ORG_PK) else: # Potentially inefficient query, so limit this to once per server thread # by caching the results. Here, we've had a cache miss headless_orgs = cls.objects.filter(name=cls.HEADLESS_ORG_NAME) if not headless_orgs: # Cache miss because the org actually doesn't exist. Create it! headless_org = Organization(name=cls.HEADLESS_ORG_NAME) headless_org.save(**({cls.HEADLESS_ORG_SAVE_FLAG: True})) cls.HEADLESS_ORG_PK = headless_org.pk else: # Cache miss because it's the first relevant query since this thread started. assert len( headless_orgs ) == 1, "Cannot have multiple HEADLESS ZONE organizations" cls.HEADLESS_ORG_PK = headless_orgs[0].pk headless_org = headless_orgs[0] # TODO(bcipolli): remove this code! # # In the future, when we self-register headless zones, we'll # add them directly to the headless organization. # For now, we'll have to do an exhaustive search. if refresh_zones: headless_org.zones.add(*Zone.get_headless_zones()) return headless_org
def test_can_delete_full_org(self): """Confirm no option to delete an org with data""" # Save zone info, but without adding self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.assertNotEqual(self.browser.find_element_by_css_selector(".icon-pencil"), None, "Make sure 'edit' icon appears.") self.assertNotEqual(self.browser.find_element_by_css_selector(".icon-trash"), None, "Make sure 'delete' icon appears.")
class CentralFacilityUserFormTestCase(OrganizationManagementTestCase): def setUp(self): super(CentralFacilityUserFormTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() self.facility = Facility(name=self.FACILITY_NAME, zone_fallback=self.zone) self.facility.save() self.user.facility = self.facility self.user.save() def test_add_student(self): self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browse_to('%s?facility=%s' % (self.reverse('add_facility_student'), self.facility.id)) self.browser.find_element_by_id('id_username').send_keys('s') self.browser.find_element_by_id('id_password_first').send_keys('password') self.browser.find_element_by_id('id_password_recheck').send_keys('password') self.browser.find_elements_by_class_name('submit')[0].click() self.browser_check_django_message(message_type="success", contains="successfully created")
def handle(self, *args, **options): if settings.CENTRAL_SERVER: raise CommandError("You shouldn't be trying to put the central server on a sharing network!") own_device = Device.get_own_device() if DeviceZone.objects.filter(device=own_device).count() > 0: raise CommandError("This device already belongs to a sharing network.") zone_name = args[0] if len(args) >= 1 else "Sharing network for Device %s" % own_device.name zone_description = args[1] if (len(args) >= 2 and args[1]) else "" # Create the zone self.stdout.write("Generating a sharing network.\n") zone = Zone(name=zone_name, description=zone_description) zone.save() # this will sign the zone with the current device # Create the zone invitation--you're invited to a party of one! self.stdout.write("Generating a sharing network invitation--from me, to me!\n") invitation = ZoneInvitation.generate(zone=zone, invited_by=own_device) invitation.save() invitation.claim(used_by=own_device) self.stdout.write("Done!\n")
def register_public_key_server_auto(request): """This function allows an anonymous client to request a device key to be associated with a new zone. This allows registration to occur without a single login; the device will be associated with a headless zone. """ public_key = urllib.unquote(request.GET.get("device_key", "")) if RegisteredDevicePublicKey.objects.filter(public_key=public_key): return HttpResponseForbidden("Device is already registered.") # Create some zone. zone = Zone(name="Zone for public key %s" % public_key[:50]) zone.save() # Add an association between a device 's public key and this zone, # so that when registration is attempted by the distributed server # with this key, it will register and receive this zone info. RegisteredDevicePublicKey(zone=zone, public_key=public_key).save() # Report success return JsonResponse({})
class ZoneDeletionTestCase(OrganizationManagementTestCase): def setUp(self): super(ZoneDeletionTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save() def test_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().accept() self.browser_wait_for_no_element(".zone-delete-link") time.sleep(1) self.browser_check_django_message(message_type="success", contains="successfully deleted") with self.assertRaises(NoSuchElementException): self.assertEqual( self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link no longer exists.") def test_cancel_delete_zone_from_org_admin(self): """Delete a zone from the org_management page""" self.browser_login_user(self.USER_EMAIL, self.USER_PASSWORD) self.browser.find_element_by_css_selector(".zone-delete-link").click() self.browser.switch_to_alert().dismiss() self.assertNotEqual( self.browser.find_element_by_css_selector(".zone-delete-link"), None, "Make sure 'delete' link still exists.") self.browser_check_django_message(num_messages=0) def test_issue_697_part1(self): self.facility = Facility(name=self.FACILITY_NAME) self.facility.save() self.test_delete_zone_from_org_admin()
def setUp(self): super(ZoneDeletionTestCase, self).setUp() self.zone = Zone(name=self.ZONE_NAME) self.zone.save() self.org.add_zone(self.zone) self.org.save()
def register(request, backend, success_url=None, form_class=None, disallowed_url='registration_disallowed', template_name='registration/registration_form.html', extra_context=None): """ Allow a new user to register an account. The actual registration of the account will be delegated to the backend specified by the ``backend`` keyword argument (see below); it will be used as follows: 1. The backend's ``registration_allowed()`` method will be called, passing the ``HttpRequest``, to determine whether registration of an account is to be allowed; if not, a redirect is issued to the view corresponding to the named URL pattern ``registration_disallowed``. To override this, see the list of optional arguments for this view (below). 2. The form to use for account registration will be obtained by calling the backend's ``get_form_class()`` method, passing the ``HttpRequest``. To override this, see the list of optional arguments for this view (below). 3. If valid, the form's ``cleaned_data`` will be passed (as keyword arguments, and along with the ``HttpRequest``) to the backend's ``register()`` method, which should return the new ``User`` object. 4. Upon successful registration, the backend's ``post_registration_redirect()`` method will be called, passing the ``HttpRequest`` and the new ``User``, to determine the URL to redirect the user to. To override this, see the list of optional arguments for this view (below). **Required arguments** None. **Optional arguments** ``backend`` The dotted Python import path to the backend class to use. ``disallowed_url`` URL to redirect to if registration is not permitted for the current ``HttpRequest``. Must be a value which can legally be passed to ``django.shortcuts.redirect``. If not supplied, this will be whatever URL corresponds to the named URL pattern ``registration_disallowed``. ``form_class`` The form class to use for registration. If not supplied, this will be retrieved from the registration backend. ``extra_context`` A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. ``success_url`` URL to redirect to after successful registration. Must be a value which can legally be passed to ``django.shortcuts.redirect``. If not supplied, this will be retrieved from the registration backend. ``template_name`` A custom template to use. If not supplied, this will default to ``registration/registration_form.html``. **Context:** ``form`` The registration form. Any extra variables supplied in the ``extra_context`` argument (see above). **Template:** registration/registration_form.html or ``template_name`` keyword argument. """ backend = get_backend(backend) if not backend.registration_allowed(request): return redirect(disallowed_url) if form_class is None: form_class = backend.get_form_class(request) do_subscribe = request.REQUEST.get("email_subscribe") == "on" if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) org_form = OrganizationForm(data=request.POST, instance=Organization()) # Could register if form.is_valid() and org_form.is_valid(): assert form.cleaned_data.get("username") == form.cleaned_data.get("email"), "Should be set equal in the call to clean()" try: # Create the user new_user = backend.register(request, **form.cleaned_data) # Add an org. Must create org before adding user. org_form.instance.owner = new_user org_form.save() org = org_form.instance org.add_member(new_user) # Now add a zone, and link to the org zone = Zone(name=org_form.instance.name + " Sharing Network") zone.save() org.add_zone(zone) # Finally, try and subscribe the user to the mailing list # (silently; don't return anything to the user) if do_subscribe: contact_subscribe(request, form.cleaned_data['email']) # no "return" org.save() if success_url is None: to, args, kwargs = backend.post_registration_redirect(request, new_user) return redirect(to, *args, **kwargs) else: return redirect(success_url) except IntegrityError as e: if e.message=='column username is not unique': form._errors['__all__'] = _("An account with this email address has already been created. Please login at the link above.") else: raise e # GET, not POST else: form = form_class() org_form = OrganizationForm() if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response( template_name, { 'form': form, "org_form" : org_form, "subscribe": do_subscribe, }, context_instance=context, )
def register(request, backend, success_url=None, form_class=None, disallowed_url='registration_disallowed', template_name='registration/registration_form.html', extra_context=None): """ Allow a new user to register an account. The actual registration of the account will be delegated to the backend specified by the ``backend`` keyword argument (see below); it will be used as follows: 1. The backend's ``registration_allowed()`` method will be called, passing the ``HttpRequest``, to determine whether registration of an account is to be allowed; if not, a redirect is issued to the view corresponding to the named URL pattern ``registration_disallowed``. To override this, see the list of optional arguments for this view (below). 2. The form to use for account registration will be obtained by calling the backend's ``get_form_class()`` method, passing the ``HttpRequest``. To override this, see the list of optional arguments for this view (below). 3. If valid, the form's ``cleaned_data`` will be passed (as keyword arguments, and along with the ``HttpRequest``) to the backend's ``register()`` method, which should return the new ``User`` object. 4. Upon successful registration, the backend's ``post_registration_redirect()`` method will be called, passing the ``HttpRequest`` and the new ``User``, to determine the URL to redirect the user to. To override this, see the list of optional arguments for this view (below). **Required arguments** None. **Optional arguments** ``backend`` The dotted Python import path to the backend class to use. ``disallowed_url`` URL to redirect to if registration is not permitted for the current ``HttpRequest``. Must be a value which can legally be passed to ``django.shortcuts.redirect``. If not supplied, this will be whatever URL corresponds to the named URL pattern ``registration_disallowed``. ``form_class`` The form class to use for registration. If not supplied, this will be retrieved from the registration backend. ``extra_context`` A dictionary of variables to add to the template context. Any callable object in this dictionary will be called to produce the end result which appears in the context. ``success_url`` URL to redirect to after successful registration. Must be a value which can legally be passed to ``django.shortcuts.redirect``. If not supplied, this will be retrieved from the registration backend. ``template_name`` A custom template to use. If not supplied, this will default to ``registration/registration_form.html``. **Context:** ``form`` The registration form. Any extra variables supplied in the ``extra_context`` argument (see above). **Template:** registration/registration_form.html or ``template_name`` keyword argument. """ backend = get_backend(backend) if not backend.registration_allowed(request): return redirect(disallowed_url) if form_class is None: form_class = backend.get_form_class(request) do_subscribe = request.REQUEST.get("email_subscribe") == "on" if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) org_form = OrganizationForm(data=request.POST, instance=Organization()) # Could register if form.is_valid() and org_form.is_valid(): assert form.cleaned_data.get("username") == form.cleaned_data.get("email"), "Should be set equal in the call to clean()" try: # Create the user new_user = backend.register(request, **form.cleaned_data) # Add an org. Must create org before adding user. org_form.instance.owner = new_user org_form.save() org = org_form.instance org.add_member(new_user) # Now add a zone, and link to the org zone = Zone(name=org_form.instance.name + " Default Zone") zone.save() org.add_zone(zone) # Finally, try and subscribe the user to the mailing list # (silently; don't return anything to the user) if do_subscribe: contact_subscribe(request, form.cleaned_data['email']) # no "return" org.save() if success_url is None: to, args, kwargs = backend.post_registration_redirect(request, new_user) return redirect(to, *args, **kwargs) else: return redirect(success_url) except IntegrityError as e: if e.message=='column username is not unique': form._errors['__all__'] = _("An account with this email address has already been created. Please login at the link above.") else: raise e # GET, not POST else: form = form_class() org_form = OrganizationForm() if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response( template_name, { 'form': form, "org_form" : org_form, "subscribe": do_subscribe, }, context_instance=context, )