def test_node_staff_access_page_and_children_group_1_no_staff(self): """ simulate behaviour of group b member group_b_ACCESS_PAGE_AND_CHILDREN to page_b no staff user """ self._setup_user_groups() all_pages = self._setup_tree_pages() self._setup_view_restrictions() granted = [ 'page_b', 'page_b_a', 'page_b_b', 'page_b_c', 'page_b_d', ] self.assertGrantedVisibility(all_pages, granted, username='******') if get_user_model().USERNAME_FIELD == 'email': user = get_user_model().objects.get(email='*****@*****.**') else: user = get_user_model().objects.get(username='******') urls = self.get_url_dict(all_pages) self.assertViewAllowed(urls["/en/page_b/page_b_a/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_b/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_b/page_b_b_a/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_c/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_d/"], user) self.assertViewNotAllowed(urls["/en/page_c/"], user) self.assertViewNotAllowed(urls["/en/page_d/"], user) self.assertViewNotAllowed(urls["/en/page_d/page_d_a/"], user)
def test_placeholder_pk_thousands_format(self): page = create_page("page", "nav_playground.html", "en", published=True) for placeholder in page.placeholders.all(): page.placeholders.remove(placeholder) placeholder.pk += 1000 placeholder.save() page.placeholders.add(placeholder) page.reload() for placeholder in page.placeholders.all(): add_plugin(placeholder, "TextPlugin", "en", body="body", id=placeholder.pk) with SettingsOverride(USE_THOUSAND_SEPARATOR=True, USE_L10N=True): # Superuser user = self.get_superuser() self.client.login(username=getattr(user, get_user_model().USERNAME_FIELD), password=getattr(user, get_user_model().USERNAME_FIELD)) response = self.client.get("/en/?%s" % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) for placeholder in page.placeholders.all(): self.assertContains( response, "'placeholder_id': '%s'" % placeholder.pk) self.assertNotContains( response, "'placeholder_id': '%s'" % format( placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, "'plugin_id': '%s'" % format( placeholder.pk, ".", grouping=3, thousand_sep=",")) self.assertNotContains( response, "'clipboard': '%s'" % format( response.context['request'].toolbar.clipboard.pk, ".", grouping=3, thousand_sep=","))
def test_static_placeholders_permissions(self): # login url = '%s/?%s' % (self.live_server_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) self.driver.get(url) self.assertRaises(NoSuchElementException, self.driver.find_element_by_class_name, 'cms_toolbar-item_logout') username_input = self.driver.find_element_by_id("id_cms-username") username_input.send_keys(getattr(self.user, get_user_model().USERNAME_FIELD)) password_input = self.driver.find_element_by_id("id_cms-password") password_input.send_keys(getattr(self.user, get_user_model().USERNAME_FIELD)) password_input.submit() self.wait_page_loaded() self.assertTrue(self.driver.find_element_by_class_name('cms_toolbar-item-navigation')) # test static placeholder permission (content of static placeholders is NOT editable) self.driver.get('%s/en/?%s' % (self.live_server_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))) self.assertRaises(NoSuchElementException, self.driver.find_element_by_class_name, self.placeholder_name) # update userpermission edit_permission = Permission.objects.get(codename="edit_static_placeholder") self.user.user_permissions.add( edit_permission ) # test static placeholder permission (content of static placeholders is editable) self.driver.get('%s/en/?%s' % (self.live_server_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))) self.assertTrue(self.driver.find_element_by_class_name(self.placeholder_name))
def test_get_page_for_apphook_on_preview_or_edit(self): with SettingsOverride(ROOT_URLCONF='cms.test_utils.project.urls_3'): if get_user_model().USERNAME_FIELD == 'email': superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', '*****@*****.**') else: superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', 'admin') page = create_page("home", "nav_playground.html", "en", created_by=superuser, published=True, apphook=APP_NAME) create_title('de', page.get_title(), page) page.publish('en') page.publish('de') page.save() public_page = page.get_public_object() with self.login_user_context(superuser): with force_language("en"): path = reverse('sample-settings') request = self.get_request(path + '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) request.LANGUAGE_CODE = 'en' attached_to_page = applications_page_check(request, path=path[1:]) # strip leading slash response = self.client.get(path+"?edit") self.assertContains(response, '?redirect=') with force_language("de"): path = reverse('sample-settings') request = self.get_request(path + '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) request.LANGUAGE_CODE = 'de' attached_to_page = applications_page_check(request, path=path[1:]) # strip leading slash self.assertEqual(attached_to_page.pk, public_page.pk)
def test_edit(self): """ Test editing a *PAGE* plugin """ page, placeholder, superuser, staff = self.get_data() # create the plugin using a superuser plugin = add_plugin(placeholder, 'TextPlugin', 'en', body='body') plugin_data = { 'plugin_id': plugin.pk, 'body': 'newbody', } self.assertEqual(plugin.body, 'body') # check the body is as expected. # log the user out, try to edit the plugin self.client.logout() url = URL_CMS_PLUGIN_EDIT + '%s/' % plugin.pk response = self.client.post(url, plugin_data) # since the user is not logged in, they should be prompted to log in. if DJANGO_1_6: self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin/login.html') else: self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/en/admin/login/?next=%s' % url) plugin = self.reload(plugin) self.assertEqual(plugin.body, 'body') # now log a staff user without permissions in and do the same as above. self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD), password=getattr(staff, get_user_model().USERNAME_FIELD)) response = self.client.post(url, plugin_data) # the user is logged in and the security check fails, so it should 403. self.assertEqual(response.status_code, 403) plugin = self.reload(plugin) self.assertEqual(plugin.body, 'body')
def test_command_line_publish_one_site(self): get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456') siteA = Site.objects.create(domain='a.example.com', name='a.example.com') siteB = Site.objects.create(domain='b.example.com', name='b.example.com') #example.com create_page(u"example.com homepage", "nav_playground.html", "en", published=True) #a.example.com create_page(u"a.example.com homepage", "nav_playground.html", "de", site=siteA, published=True) #b.example.com create_page(u"b.example.com homepage", "nav_playground.html", "de", site=siteB, published=True) create_page(u"b.example.com about", "nav_playground.html", "nl", site=siteB, published=True) with StdoutOverride() as buffer: # Now we don't expect it to raise, but we need to redirect IO call_command('publisher_publish', site=siteB.id) lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work for line in lines: if 'Total' in line: pages_from_output = int(line.split(':')[1]) elif 'Published' in line: published_from_output = int(line.split(':')[1]) self.assertEqual(pages_from_output, 2) self.assertEqual(published_from_output, 2)
def test_command_line_publish_multiple_languages_check_count(self): """ Publishing one page with multiple languages still counts as one page. This test case checks whether it works as expected. """ # we need to create a superuser (the db is empty) get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456') # Now, let's create a page with 2 languages. page = create_page("en title", "nav_playground.html", "en", published=True) create_title("de", "de title", page) page.publish("de") pages_from_output = 0 published_from_output = 0 with StdoutOverride() as buffer: # Now we don't expect it to raise, but we need to redirect IO call_command('publisher_publish') lines = buffer.getvalue().split( '\n') #NB: readlines() doesn't work for line in lines: if 'Total' in line: pages_from_output = int(line.split(':')[1]) elif 'Published' in line: published_from_output = int(line.split(':')[1]) self.assertEqual(pages_from_output, 1) self.assertEqual(published_from_output, 1)
def _setup_user_groups(self): """ Setup a group for every grant on ACCESS TYPE """ userdata = [ ('user_1', True, self.GROUPNAME_1), ('user_1_nostaff', False, self.GROUPNAME_1), ('user_2', True, self.GROUPNAME_2), ('user_2_nostaff', False, self.GROUPNAME_2), ('user_3', True, self.GROUPNAME_3), ('user_3_nostaff', False, self.GROUPNAME_3), ('user_4', True, self.GROUPNAME_4), ('user_4_nostaff', False, self.GROUPNAME_4), ('user_5', True, self.GROUPNAME_5), ('user_5_nostaff', False, self.GROUPNAME_5), ('user_staff', True, None), ] default_users_count = get_user_model().objects.all().count() for username, is_staff, groupname in userdata: user = self._create_user(username, is_staff) if groupname: group, _ = Group.objects.get_or_create(name=groupname) user_set = getattr(group, user_related_name) user_set.add(user) group.save() self.assertEqual(11, get_user_model().objects.all().count()-default_users_count)
def assertGrantedVisibility(self, all_pages, expected_granted_pages, username=None): """ helper function to check the expected_granted_pages are not in the restricted_pages list and all visible pages are in the expected_granted_pages """ # log the user in if present user = None if username is not None: if get_user_model().USERNAME_FIELD == 'email': username = username + '@django-cms.org' query = dict() query[get_user_model().USERNAME_FIELD + '__iexact'] = username user = get_user_model().objects.get(**query) request = self.get_request(user) visible_page_ids = get_visible_pages(request, all_pages, self.site) public_page_ids = Page.objects.drafts().filter( title_set__title__in=expected_granted_pages).values_list('id', flat=True) self.assertEqual(len(visible_page_ids), len(expected_granted_pages)) restricted_pages = Page.objects.public().exclude( title_set__title__in=expected_granted_pages).values_list('id', flat=True) self.assertNodeMemberships(visible_page_ids, restricted_pages, public_page_ids)
def test_command_line_publishes_selected_language_drafts(self): # we need to create a superuser (the db is empty) get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456') page = create_page("en title", "nav_playground.html", "en") title = create_title('de', 'de title', page) title.published = False title.save() title = create_title('fr', 'fr title', page) title.published = False title.save() pages_from_output = 0 published_from_output = 0 with StdoutOverride() as buffer: # Now we don't expect it to raise, but we need to redirect IO call_command('publisher_publish', language='de', include_unpublished=True) lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work for line in lines: if 'Total' in line: pages_from_output = int(line.split(':')[1]) elif 'Published' in line: published_from_output = int(line.split(':')[1]) self.assertEqual(pages_from_output, 1) self.assertEqual(published_from_output, 1) self.assertEqual(Page.objects.public().count(), 1) public = Page.objects.public()[0] languages = sorted(public.title_set.values_list('language', flat=True)) self.assertEqual(languages, ['de'])
def test_menu_access_page_group_5(self): """ simulate behaviour of group b member group_d_ACCESS_PAGE to page_d """ self._setup_user_groups() all_pages = self._setup_tree_pages() self._setup_view_restrictions() granted = [ 'page_a', 'page_c', 'page_c_a', 'page_c_b', 'page_d', 'page_d_a', 'page_d_b', 'page_d_c', 'page_d_d', ] self.assertGrantedVisibility(all_pages, granted, username='******') urls = self.get_url_dict(all_pages) if get_user_model().USERNAME_FIELD == 'email': user = get_user_model().objects.get(email='*****@*****.**') else: user = get_user_model().objects.get(username='******') # call / self.assertViewNotAllowed(urls["/en/page_b/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_b/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_b/page_b_b_a/"], user) self.assertViewAllowed(urls["/en/page_d/"], user) self.assertViewAllowed(urls["/en/page_d/page_d_a/"], user)
def _setup_user_groups(self): """ Setup a group for every grant on ACCESS TYPE """ userdata = [ ('user_1', True, self.GROUPNAME_1), ('user_1_nostaff', False, self.GROUPNAME_1), ('user_2', True, self.GROUPNAME_2), ('user_2_nostaff', False, self.GROUPNAME_2), ('user_3', True, self.GROUPNAME_3), ('user_3_nostaff', False, self.GROUPNAME_3), ('user_4', True, self.GROUPNAME_4), ('user_4_nostaff', False, self.GROUPNAME_4), ('user_5', True, self.GROUPNAME_5), ('user_5_nostaff', False, self.GROUPNAME_5), ('user_staff', True, None), ] default_users_count = get_user_model().objects.all().count() for username, is_staff, groupname in userdata: user = self._create_user(username, is_staff) if groupname: group, _ = Group.objects.get_or_create(name=groupname) user_set = getattr(group, user_related_name) user_set.add(user) group.save() self.assertEqual( 11, get_user_model().objects.all().count() - default_users_count)
def test_command_line_ignores_draft_page(self): # we need to create a superuser (the db is empty) get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456') create_page("The page!", "nav_playground.html", "en", published=False) pages_from_output = 0 published_from_output = 0 with StdoutOverride() as buffer: # Now we don't expect it to raise, but we need to redirect IO com = publisher_publish.Command() com.handle_noargs() lines = buffer.getvalue().split( '\n') #NB: readlines() doesn't work for line in lines: if 'Total' in line: pages_from_output = int(line.split(':')[1]) elif 'Published' in line: published_from_output = int(line.split(':')[1]) self.assertEqual(pages_from_output, 0) self.assertEqual(published_from_output, 0) self.assertEqual(Page.objects.public().count(), 0)
def test_command_line_ignores_draft_page(self): # we need to create a superuser (the db is empty) get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456') create_page("The page!", "nav_playground.html", "en", published=False) pages_from_output = 0 published_from_output = 0 with StdoutOverride() as buffer: # Now we don't expect it to raise, but we need to redirect IO com = publisher_publish.Command() com.handle_noargs() lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work for line in lines: if 'Total' in line: pages_from_output = int(line.split(':')[1]) elif 'Published' in line: published_from_output = int(line.split(':')[1]) self.assertEqual(pages_from_output, 0) self.assertEqual(published_from_output, 0) self.assertEqual(Page.objects.public().count(), 0)
def test_menu_access_page_group_5(self): """ simulate behaviour of group b member group_d_ACCESS_PAGE to page_d """ self._setup_user_groups() all_pages = self._setup_tree_pages() self._setup_view_restrictions() granted = ['page_a', 'page_c', 'page_c_a', 'page_c_b', 'page_d', 'page_d_a', 'page_d_b', 'page_d_c', 'page_d_d', ] self.assertGrantedVisibility(all_pages, granted, username='******') urls = self.get_url_dict(all_pages) if get_user_model().USERNAME_FIELD == 'email': user = get_user_model().objects.get(email='*****@*****.**') else: user = get_user_model().objects.get(username='******') # call / self.assertViewNotAllowed(urls["/en/page_b/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_b/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_b/page_b_b_a/"], user) self.assertViewAllowed(urls["/en/page_d/"], user) self.assertViewAllowed(urls["/en/page_d/page_d_a/"], user)
def test_node_staff_access_children_group_2_nostaff(self): """ simulate behaviour of group 2 member GROUPNAME_2 = 'group_b_b_ACCESS_CHILDREN' to page_b_b and user is no staff """ self._setup_user_groups() all_pages = self._setup_tree_pages() self._setup_view_restrictions() granted = ['page_b_b_a', 'page_b_b_b', 'page_b_b_c', ] self.assertGrantedVisibility(all_pages, granted, username='******') if get_user_model().USERNAME_FIELD == 'email': user = get_user_model().objects.get(email='*****@*****.**') else: user = get_user_model().objects.get(username='******') urls = self.get_url_dict(all_pages) # member of group that has access to this page self.assertViewAllowed(urls["/en/page_b/page_b_b/page_b_b_a/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_b/page_b_b_a/page_b_b_a_a/"], user) self.assertViewNotAllowed(urls["/en/page_b/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_a/"], user) self.assertViewNotAllowed(urls["/en/page_b/page_b_b/"], user) self.assertViewNotAllowed(urls["/en/page_c/"], user) self.assertViewNotAllowed(urls["/en/page_d/"], user) self.assertViewNotAllowed(urls["/en/page_d/page_d_a/"], user)
def test_command_line_publishes_selected_language(self): # we need to create a superuser (the db is empty) get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456') page = create_page("en title", "nav_playground.html", "en") title = create_title('de', 'de title', page) title.published = True title.save() title = create_title('fr', 'fr title', page) title.published = True title.save() pages_from_output = 0 published_from_output = 0 with StdoutOverride() as buffer: # Now we don't expect it to raise, but we need to redirect IO call_command('publisher_publish', language='de') lines = buffer.getvalue().split( '\n') #NB: readlines() doesn't work for line in lines: if 'Total' in line: pages_from_output = int(line.split(':')[1]) elif 'Published' in line: published_from_output = int(line.split(':')[1]) self.assertEqual(pages_from_output, 1) self.assertEqual(published_from_output, 1) self.assertEqual(Page.objects.public().count(), 1) public = Page.objects.public()[0] languages = sorted(public.title_set.values_list('language', flat=True)) self.assertEqual(languages, ['de'])
def test_delete(self): """ Test deleting a *PAGE* plugin """ page, placeholder, superuser, staff = self.get_data() plugin = add_plugin(placeholder, 'TextPlugin', 'en', body='body') plugin_data = { 'plugin_id': plugin.pk, } plugin = self.reload(plugin) self.assertEqual(plugin.body, 'body') # log the user out, try to remove the plugin self.client.logout() response = self.client.post(URL_CMS_PLUGIN_REMOVE, plugin_data) # since the user is not logged in, they should be prompted to log in. if DJANGO_1_6: self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin/login.html') else: self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/en/admin/login/?next=%s' % URL_CMS_PLUGIN_REMOVE) self.assertEqual(CMSPlugin.objects.count(), 1) plugin = self.reload(plugin) self.assertEqual(plugin.body, 'body') # now log a staff user without permissions in and do the same as above. self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD), password=getattr(staff, get_user_model().USERNAME_FIELD)) response = self.client.post(URL_CMS_PLUGIN_REMOVE + "%s/" % plugin.pk, plugin_data) # the user is logged in and the security check fails, so it should 403. self.assertEqual(response.status_code, 403) self.assertEqual(CMSPlugin.objects.count(), 1) plugin = self.reload(plugin) self.assertEqual(plugin.body, 'body')
def test_command_line_publish_multiple_languages_check_count(self): """ Publishing one page with multiple languages still counts as one page. This test case checks whether it works as expected. """ # we need to create a superuser (the db is empty) get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456') # Now, let's create a page with 2 languages. page = create_page("en title", "nav_playground.html", "en", published=True) create_title("de", "de title", page) page.publish("de") pages_from_output = 0 published_from_output = 0 with StdoutOverride() as buffer: # Now we don't expect it to raise, but we need to redirect IO call_command('publisher_publish') lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work for line in lines: if 'Total' in line: pages_from_output = int(line.split(':')[1]) elif 'Published' in line: published_from_output = int(line.split(':')[1]) self.assertEqual(pages_from_output, 1) self.assertEqual(published_from_output, 1)
def test_add(self): """ Test adding a plugin to a *PAGE*. """ page, placeholder, superuser, staff = self.get_data() plugin_data = { 'plugin_type': "TextPlugin", 'plugin_language': settings.LANGUAGES[0][0], 'placeholder_id': page.placeholders.get(slot="body").pk, } self.assertEqual(CMSPlugin.objects.count(), 0) # log the user out and post the plugin data to the cms add-plugin URL. self.client.logout() response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) # since the user is not logged in, they should be prompted to log in. if DJANGO_1_6: self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin/login.html') else: self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/en/admin/login/?next=%s' % URL_CMS_PLUGIN_ADD) self.assertEqual(CMSPlugin.objects.count(), 0) # now log a staff user without permissions in and do the same as above. self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD), password=getattr(staff, get_user_model().USERNAME_FIELD)) response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) # the user is logged in and the security check fails, so it should 403. self.assertEqual(response.status_code, 403) self.assertEqual(CMSPlugin.objects.count(), 0)
def test_delete_ph(self): page, placeholder, superuser, staff = self.get_data() plugin = add_plugin(placeholder, 'TextPlugin', 'en', body='body') plugin_data = { 'plugin_id': plugin.pk, } plugin = self.reload(plugin) self.assertEqual(plugin.body, 'body') url = admin_reverse('placeholderapp_example1_delete_plugin', args=[plugin.pk]) # log the user out and try to remove a plugin using PlaceholderAdmin self.client.logout() response = self.client.post(url, plugin_data) # since the user is not logged in, they should be prompted to log in. if DJANGO_1_6: self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'admin/login.html') else: self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/en/admin/login/?next=%s' % url) self.assertEqual(CMSPlugin.objects.count(), 1) # now log a staff user without permissions in and do the same as above. self.client.login(username=getattr(staff, get_user_model().USERNAME_FIELD), password=getattr(staff, get_user_model().USERNAME_FIELD)) response = self.client.post(url, plugin_data) # the user is logged in and the security check fails, so it should 403. self.assertEqual(response.status_code, 403) self.assertEqual(CMSPlugin.objects.count(), 1)
def get_subordinate_users(user): """ Returns users queryset, containing all subordinate users to given user including users created by given user and not assigned to any page. Not assigned users must be returned, because they shouldn't get lost, and user should still have possibility to see them. Only users created_by given user which are on the same, or lover level are returned. If user haves global permissions or is a superuser, then he can see all the users. This function is currently used in PagePermissionInlineAdminForm for limit users in permission combobox. Example: A,W level 0 / \ user B,GroupE level 1 Z / \ C,X D,Y,W level 2 Rules: W was created by user, Z was created by user, but is not assigned to any page. Will return [user, C, X, D, Y, Z]. W was created by user, but is also assigned to higher level. """ # TODO: try to merge with PagePermissionManager.subordinate_to_user() if user.is_superuser or \ GlobalPagePermission.objects.with_can_change_permissions(user): return get_user_model().objects.all() site = Site.objects.get_current() page_id_allow_list = Page.permissions.get_change_permissions_id_list(user, site) try: user_level = get_user_permission_level(user) except NoPermissionsException: # no permission so only staff and no page permissions qs = get_user_model().objects.distinct().filter( Q(is_staff=True) & Q(pageuser__created_by=user) & Q(pagepermission__page=None) ) qs = qs.exclude(pk=user.id).exclude(groups__user__pk=user.id) return qs # normal query qs = get_user_model().objects.distinct().filter( Q(is_staff=True) & (Q(pagepermission__page__id__in=page_id_allow_list) & Q(pagepermission__page__level__gte=user_level)) | (Q(pageuser__created_by=user) & Q(pagepermission__page=None)) ) qs = qs.exclude(pk=user.id).exclude(groups__user__pk=user.id) return qs
def __enter__(self): loginok = self.testcase.client.login( username=getattr(self.user, get_user_model().USERNAME_FIELD), password=getattr(self.user, get_user_model().USERNAME_FIELD)) self.old_user = getattr(self.testcase, 'user', None) self.testcase.user = self.user self.testcase.assertTrue(loginok)
def _create_user(self, username, is_staff=False, is_superuser=False, is_active=True, add_default_permissions=False, permissions=None): """ Use this method to create users. Default permissions on page and text plugin are added if creating a non-superuser and `add_default_permissions` is set. Set `permissions` parameter to an iterable of permission codes to add custom permissios. """ User = get_user_model() fields = dict(email=username + '@django-cms.org', is_staff=is_staff, is_active=is_active, is_superuser=is_superuser) # Check for special case where email is used as username if (get_user_model().USERNAME_FIELD != 'email'): fields[get_user_model().USERNAME_FIELD] = username user = User(**fields) user.set_password(getattr(user, get_user_model().USERNAME_FIELD)) user.save() if is_staff and not is_superuser and add_default_permissions: user.user_permissions.add( Permission.objects.get(codename='add_text')) user.user_permissions.add( Permission.objects.get(codename='delete_text')) user.user_permissions.add( Permission.objects.get(codename='change_text')) user.user_permissions.add( Permission.objects.get(codename='publish_page')) user.user_permissions.add( Permission.objects.get(codename='add_page')) user.user_permissions.add( Permission.objects.get(codename='change_page')) user.user_permissions.add( Permission.objects.get(codename='delete_page')) if is_staff and not is_superuser and permissions: for permission in permissions: user.user_permissions.add( Permission.objects.get(codename=permission)) return user
def test_node_staff_access_page_and_descendants_group_3(self): """ simulate behaviour of group 3 member group_b_ACCESS_PAGE_AND_DESCENDANTS to page_b and user is staff """ self._setup_user_groups() all_pages = self._setup_tree_pages() self._setup_view_restrictions() granted = ['page_a', 'page_b', 'page_b_a', 'page_b_b', 'page_b_b_a', 'page_b_b_a_a', 'page_b_b_b', 'page_b_b_c', 'page_b_c', 'page_b_d', 'page_b_d_a', 'page_b_d_b', 'page_b_d_c', 'page_c', 'page_c_a', 'page_c_b', 'page_d_a', 'page_d_b', 'page_d_c', 'page_d_d', ] self.assertGrantedVisibility(all_pages, granted, username='******') if get_user_model().USERNAME_FIELD == 'email': user = get_user_model().objects.get(email='*****@*****.**') else: user = get_user_model().objects.get(username='******') urls = self.get_url_dict(all_pages) url = self.get_pages_root() self.assertViewAllowed(urls[url], user) self.assertViewAllowed(urls["/en/page_b/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_a/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_b/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_c/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_d/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_b/page_b_b_a/"], user) self.assertViewAllowed(urls["/en/page_b/page_b_b/page_b_b_a/page_b_b_a_a/"], user) self.assertViewAllowed(urls["/en/page_c/"], user) self.assertViewNotAllowed(urls["/en/page_d/"], user) self.assertViewAllowed(urls["/en/page_d/page_d_a/"], user) self.assertViewAllowed(urls["/en/page_d/page_d_b/"], user) self.assertViewAllowed(urls["/en/page_d/page_d_c/"], user)
def _login(self): url = '%s/?%s' % (self.live_server_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) self.driver.get(url) self.assertRaises(NoSuchElementException, self.driver.find_element_by_class_name, 'cms_toolbar-item_logout') username_input = self.driver.find_element_by_id("id_cms-username") username_input.send_keys(getattr(self.user, get_user_model().USERNAME_FIELD)) password_input = self.driver.find_element_by_id("id_cms-password") password_input.send_keys(getattr(self.user, get_user_model().USERNAME_FIELD)) password_input.submit() self.wait_page_loaded() self.assertTrue(self.driver.find_element_by_class_name('cms_toolbar-item-navigation'))
def get_superuser(self): try: query = dict() if get_user_model().USERNAME_FIELD != "email": query[get_user_model().USERNAME_FIELD] = "admin" else: query[get_user_model().USERNAME_FIELD] = "*****@*****.**" admin = get_user_model().objects.get(**query) except get_user_model().DoesNotExist: admin = self._create_user("admin", is_staff=True, is_superuser=True) return admin
def test_page_user_form_initial(self): if get_user_model().USERNAME_FIELD == 'email': myuser = get_user_model().objects.create_superuser("myuser", "*****@*****.**", "*****@*****.**") else: myuser = get_user_model().objects.create_superuser("myuser", "*****@*****.**", "myuser") user = create_page_user(myuser, myuser, grant_all=True) puf = PageUserForm(instance=user) names = ['can_add_page', 'can_change_page', 'can_delete_page', 'can_add_pageuser', 'can_change_pageuser', 'can_delete_pageuser', 'can_add_pagepermission', 'can_change_pagepermission', 'can_delete_pagepermission'] for name in names: self.assertTrue(puf.initial.get(name, False))
def test_plugin_add_edit(self): page_data = { 'title': 'test page 1', 'slug': 'test-page1', 'language': "en-us", 'template': 'nav_playground.html', 'parent': '', 'site': 1, } # required only if user haves can_change_permission self.super_user = self._create_user("test", True, True) self.client.login(username=getattr(self.super_user, get_user_model().USERNAME_FIELD), password=getattr(self.super_user, get_user_model().USERNAME_FIELD)) response = self.client.post(URL_CMS_PAGE_ADD[3:], page_data) page = Page.objects.all()[0] response = self.client.post(URL_CMS_PAGE_CHANGE_TEMPLATE[3:] % page.pk, page_data) page = Page.objects.all()[0] plugin_data = { 'plugin_type': "TextPlugin", 'plugin_language': "en-us", 'placeholder_id': page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD[3:], plugin_data) self.assertEqual(response.status_code, 200) created_plugin_id = int(response.content.decode('utf8').split("/edit-plugin/")[1].split("/")[0]) self.assertEqual(created_plugin_id, CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = "%s%s/" % (URL_CMS_PLUGIN_EDIT[3:], created_plugin_id) response = self.client.get(edit_url) self.assertEqual(response.status_code, 200) data = { "body": "Hello World" } response = self.client.post(edit_url, data) self.assertEqual(response.status_code, 200) txt = Text.objects.get(pk=created_plugin_id) self.assertEqual("Hello World", txt.body) # edit body, but click cancel button data = { "body": "Hello World!!", "_cancel": True, } edit_url = '%s%d/' % (URL_CMS_PLUGIN_EDIT[3:], created_plugin_id) response = self.client.post(edit_url, data) self.assertEqual(response.status_code, 200) txt = Text.objects.all()[0] self.assertEqual("Hello World", txt.body)
def create_page_user(created_by, user, can_add_page=True, can_view_page=True, can_change_page=True, can_delete_page=True, can_recover_page=True, can_add_pageuser=True, can_change_pageuser=True, can_delete_pageuser=True, can_add_pagepermission=True, can_change_pagepermission=True, can_delete_pagepermission=True, grant_all=False): """ Creates a page user. See docs/extending_cms/api_reference.rst for more info """ if grant_all: # just be lazy return create_page_user(created_by, user, True, True, True, True, True, True, True, True, True, True, True) # validate created_by assert isinstance(created_by, get_user_model()) data = { 'can_add_page': can_add_page, 'can_view_page': can_view_page, 'can_change_page': can_change_page, 'can_delete_page': can_delete_page, 'can_recover_page': can_recover_page, 'can_add_pageuser': can_add_pageuser, 'can_change_pageuser': can_change_pageuser, 'can_delete_pageuser': can_delete_pageuser, 'can_add_pagepermission': can_add_pagepermission, 'can_change_pagepermission': can_change_pagepermission, 'can_delete_pagepermission': can_delete_pagepermission, } user.is_staff = True user.is_active = True page_user = PageUser(created_by=created_by) for field in [f.name for f in get_user_model()._meta.local_fields]: setattr(page_user, field, getattr(user, field)) user.save() page_user.save() save_permissions(data, page_user) return user
def test_urls_need_reloading_signal_create(self): superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', 'admin') with signal_tester(urls_need_reloading) as env: create_page("apphooked-page", "nav_playground.html", "en", created_by=superuser, published=True, apphook="SampleApp") self.client.get('/') self.assertEqual(env.call_count, 1)
def test_assign_user_to_page_single(self): page = create_page(**self._get_default_create_page_arguments()) user = get_user_model().objects.create_user(username='******', email='*****@*****.**', password='******') user.is_staff = True user.save() request = AttributeObject(user=user) assign_user_to_page(page, user, can_change=True) self.assertFalse(page.has_change_permission(request)) self.assertFalse(page.has_add_permission(request)) _grant_page_permission(user, 'change') page = Page.objects.get(pk=page.pk) user = get_user_model().objects.get(pk=user.pk) request = AttributeObject(user=user) self.assertTrue(page.has_change_permission(request)) self.assertFalse(page.has_add_permission(request))
def test_assign_user_to_page_nothing(self): page = create_page(**self._get_default_create_page_arguments()) user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******') user.is_staff = True request = AttributeObject(user=user) self.assertFalse(page.has_change_permission(request))
def test_table_name_patching(self): """ This tests the plugin models patching when publishing from the command line """ User = get_user_model() User.objects.create_superuser('djangocms', '*****@*****.**', '123456') create_page("The page!", "nav_playground.html", "en", published=True) draft = Page.objects.drafts()[0] draft.reverse_id = 'a_test' # we have to change *something* draft.save() add_plugin(draft.placeholders.get(slot=u"body"), u"TextPlugin", u"en", body="Test content") draft.publish('en') add_plugin(draft.placeholders.get(slot=u"body"), u"TextPlugin", u"en", body="Test content") # Manually undoing table name patching Text._meta.db_table = 'djangocms_text_ckeditor_text' plugin_pool.patched = False with disable_logger(log): call_command('cms', 'moderator', 'on') # Sanity check the database (we should have one draft and one public) not_drafts = len(Page.objects.filter(publisher_is_draft=False)) drafts = len(Page.objects.filter(publisher_is_draft=True)) self.assertEqual(not_drafts, 1) self.assertEqual(drafts, 1)
def test_assign_user_to_page_single(self): page = create_page(**self._get_default_create_page_arguments()) user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******') user.is_staff = True user.save() request = AttributeObject(user=user) assign_user_to_page(page, user, can_change=True) self.assertFalse(page.has_change_permission(request)) self.assertFalse(page.has_add_permission(request)) _grant_page_permission(user, 'change') page = Page.objects.get(pk=page.pk) user = get_user_model().objects.get(pk=user.pk) request = AttributeObject(user=user) self.assertTrue(page.has_change_permission(request)) self.assertFalse(page.has_add_permission(request))
def test_cached_show_placeholder_sekizai(self): from django.core.cache import cache cache.clear() from cms.test_utils import project User = get_user_model() template_dir = os.path.join(os.path.dirname(project.__file__), 'templates', 'alt_plugin_templates', 'show_placeholder') page = create_page('Test', 'col_two.html', 'en') placeholder = page.placeholders.all()[0] add_plugin(placeholder, TextPlugin, 'en', body='HIDDEN') request = RequestFactory().get('/') request.user = User() request.current_page = page with SettingsOverride(TEMPLATE_DIRS=[template_dir]): template = Template( "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}") context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) output = template.render(context) self.assertIn('JAVASCRIPT', output) context = RequestContext(request, {'page': page, 'slot': placeholder.slot}) output = template.render(context) self.assertIn('JAVASCRIPT', output)
def _testuser(self): User = get_user_model() u = User(is_staff=True, is_active=True, is_superuser=False) setattr(u, u.USERNAME_FIELD, "test") u.set_password("test") u.save() return u
def test_compress_function_gets_a_page_when_one_exists(self): # boilerplate (creating a page) User = get_user_model() fields = dict(is_staff=True, is_active=True, is_superuser=True, email="*****@*****.**") if User.USERNAME_FIELD != 'email': fields[User.USERNAME_FIELD] = "super" user_super = User(**fields) user_super.set_password(getattr(user_super, User.USERNAME_FIELD)) user_super.save() with self.login_user_context(user_super): home_page = create_page("home", "nav_playground.html", "en", created_by=user_super) # The actual test fake_field = Mock_PageSelectFormField() data_list = (0, home_page.pk ) #(site_id, page_id) dsite-id is not used result = fake_field.compress(data_list) self.assertEqual(home_page, result)
def test_table_name_patching(self): """ This tests the plugin models patching when publishing from the command line """ User = get_user_model() User.objects.create_superuser('djangocms', '*****@*****.**', '123456') create_page("The page!", "nav_playground.html", "en", published=True) draft = Page.objects.drafts()[0] draft.reverse_id = 'a_test' # we have to change *something* draft.save() add_plugin(draft.placeholders.get(slot=u"body"), u"TextPlugin", u"en", body="Test content") draft.publish('en') add_plugin(draft.placeholders.get(slot=u"body"), u"TextPlugin", u"en", body="Test content") # Manually undoing table name patching Text._meta.db_table = 'djangocms_text_ckeditor_text' plugin_pool.patched = False with StdoutOverride(): # Now we don't expect it to raise, but we need to redirect IO com = publisher_publish.Command() com.handle_noargs() not_drafts = len(Page.objects.filter(publisher_is_draft=False)) drafts = len(Page.objects.filter(publisher_is_draft=True)) self.assertEqual(not_drafts, 1) self.assertEqual(drafts, 1)
def test_cached_show_placeholder_sekizai(self): from django.core.cache import cache cache.clear() from cms.test_utils import project User = get_user_model() template_dir = os.path.join(os.path.dirname(project.__file__), 'templates', 'alt_plugin_templates', 'show_placeholder') page = create_page('Test', 'col_two.html', 'en') placeholder = page.placeholders.all()[0] add_plugin(placeholder, TextPlugin, 'en', body='HIDDEN') request = RequestFactory().get('/') request.user = User() request.current_page = page with SettingsOverride(TEMPLATE_DIRS=[template_dir]): template = Template( "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}" ) context = RequestContext(request, { 'page': page, 'slot': placeholder.slot }) output = template.render(context) self.assertIn('JAVASCRIPT', output) context = RequestContext(request, { 'page': page, 'slot': placeholder.slot }) output = template.render(context) self.assertIn('JAVASCRIPT', output)
def test_apphook_on_root(self): with SettingsOverride( ROOT_URLCONF='cms.test_utils.project.urls_for_apphook_tests'): apphook_pool.clear() superuser = get_user_model().objects.create_superuser( 'admin', '*****@*****.**', 'admin') page = create_page("apphooked-page", "nav_playground.html", "en", created_by=superuser, published=True, apphook="SampleApp") blank_page = create_page("not-apphooked-page", "nav_playground.html", "en", created_by=superuser, published=True, apphook="", slug='blankapp') english_title = page.title_set.all()[0] self.assertEqual(english_title.language, 'en') create_title("de", "aphooked-page-de", page) self.assertTrue(page.publish('en')) self.assertTrue(page.publish('de')) self.assertTrue(blank_page.publish('en')) with force_language("en"): response = self.client.get(self.get_pages_root()) self.assertTemplateUsed(response, 'sampleapp/home.html') self.assertContains(response, '<--noplaceholder-->') response = self.client.get('/en/blankapp/') self.assertTemplateUsed(response, 'nav_playground.html') apphook_pool.clear()
def test_public_for_all(self): user = get_user_model().objects.create_user('user', '*****@*****.**', 'user') request = self.get_request(user) page = Page() page.pk = 1 fake_tree_attrs(page) self.assertTrue(page.has_view_permission(request))
def test_multiple_apphooks(self): # test for #1538 with SettingsOverride( ROOT_URLCONF= 'cms.test_utils.project.third_urls_for_apphook_tests'): apphook_pool.clear() superuser = get_user_model().objects.create_superuser( 'admin', '*****@*****.**', 'admin') create_page( "home", "nav_playground.html", "en", created_by=superuser, published=True, ) create_page("apphook1-page", "nav_playground.html", "en", created_by=superuser, published=True, apphook="SampleApp") create_page("apphook2-page", "nav_playground.html", "en", created_by=superuser, published=True, apphook="SampleApp2") reverse('sample-root') reverse('sample2-root') apphook_pool.clear()
def test_toolbar_login_cbv(self): User = get_user_model() try: apphook_pool.register(Example1App) except AppAlreadyRegistered: pass self.reload_urls() create_page('Home', 'simple.html', 'en', published=True) ex1 = Example1.objects.create(char_1='char_1', char_2='char_1', char_3='char_3', char_4='char_4', date_field=datetime.datetime.now()) create_page('apphook', 'simple.html', 'en', published=True, apphook=Example1App) url = '%s/%s/?%s' % (self.live_server_url, 'apphook/detail/class/%s' % ex1.pk, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')) self.driver.get(url) username_input = self.driver.find_element_by_id("id_cms-username") username_input.send_keys(getattr(self.user, User.USERNAME_FIELD)) password_input = self.driver.find_element_by_id("id_cms-password") password_input.send_keys("what") password_input.submit() self.wait_page_loaded() self.assertTrue(self.driver.find_element_by_class_name('cms_error'))
def test_page_language_url_for_apphook(self): apphook_pool.clear() superuser = get_user_model().objects.create_superuser( 'admin', '*****@*****.**', 'admin') page = create_page("home", "nav_playground.html", "en", created_by=superuser) create_title('de', page.get_title(), page) page.publish('en') page.publish('de') child_page = create_page("child_page", "nav_playground.html", "en", created_by=superuser, parent=page) create_title('de', child_page.get_title(), child_page) child_page.publish('en') child_page.publish('de') child_child_page = create_page("child_child_page", "nav_playground.html", "en", created_by=superuser, parent=child_page, apphook='SampleApp') create_title("de", '%s_de' % child_child_page.get_title(), child_child_page) child_child_page.publish('en') child_child_page.publish('de') # publisher_public is set to draft on publish, issue with one to one reverse child_child_page = self.reload(child_child_page) with force_language("en"): path = reverse('extra_first') request = self.get_request(path) request.LANGUAGE_CODE = 'en' request.current_page = child_child_page fake_context = {'request': request} tag = DumbPageLanguageUrl() output = tag.get_context(fake_context, 'en') url = output['content'] self.assertEqual(url, '/en/child_page/child_child_page/extra_1/') output = tag.get_context(fake_context, 'de') url = output['content'] # look the extra "_de" self.assertEqual(url, '/de/child_page/child_child_page_de/extra_1/') output = tag.get_context(fake_context, 'fr') url = output['content'] self.assertEqual(url, '/fr/child_page/child_child_page/extra_1/') apphook_pool.clear()
def create_base_structure(self, apphook, title_langs, namespace=None): apphook_pool.clear() superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', 'admin') self.superuser = superuser page = create_page("home", "nav_playground.html", "en", created_by=superuser, published=True) create_title('de', page.get_title(), page) page.publish('de') child_page = create_page("child_page", "nav_playground.html", "en", created_by=superuser, published=True, parent=page) create_title('de', child_page.get_title(), child_page) child_page.publish('de') child_child_page = create_page("child_child_page", "nav_playground.html", "en", created_by=superuser, published=True, parent=child_page, apphook=apphook, apphook_namespace=namespace) create_title("de", child_child_page.get_title(), child_child_page) child_child_page.publish('de') # publisher_public is set to draft on publish, issue with onetoone reverse child_child_page = self.reload(child_child_page) if isinstance(title_langs, six.string_types): titles = child_child_page.publisher_public.get_title_obj(title_langs) else: titles = [child_child_page.publisher_public.get_title_obj(l) for l in title_langs] self.reload_urls() return titles
def test_page_permissions(self): with SettingsOverride(CMS_PUBLIC_FOR='staff'): user = get_user_model().objects.create_user('user', '*****@*****.**', 'user') request = self.get_request(user) page = create_page('A', 'nav_playground.html', 'en') PagePermission.objects.create(can_view=True, user=user, page=page) self.assertTrue(page.has_view_permission(request))