Permalink
Browse files

Bug fixing:

- fixed revert_plugins url pattern in admin
- added check for correct reversions version - VersionAdmin must contain get_urls method
- fixed change_view for page without moderation, added MAX_MODERATION_LEVEL
- revert_plugin fix - added new overriden revision_view
- models renamed ExtUser => PageUser, ExtGroup => PageUserGroup
- changed PageUserAdmin now allows editing based on low lewel permissions
- created common function for sending emails, @see utils.mail
- added account change notifications over email
  • Loading branch information...
1 parent d0a945f commit db4bc263d44591ce60f13b8287f16e037c1f7dd3 pcicman committed Jun 9, 2009
View
@@ -3,4 +3,6 @@
*.DS_Store
cms/media/cms_page_media/
example/run
+
example/local_settings.py
+reversion/
View
@@ -14,4 +14,15 @@ def validate_settings():
if not 'mptt' in d_settings.INSTALLED_APPS:
raise ImproperlyConfigured('django-cms needs django-mptt installed.')
-validate_settings()
+validate_settings()
+
+
+def validate_dependencies():
+ # check for right version of reversions
+ if 'reversion' in d_settings.INSTALLED_APPS:
+ from reversion.admin import VersionAdmin
+ if not hasattr(VersionAdmin, 'get_urls'):
+ raise ImproperlyConfigured('django-cms requires never version of reversion (VersionAdmin must contain get_urls method)')
+
+validate_dependencies()
+
View
@@ -6,6 +6,9 @@
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.util import unquote
from django.contrib.admin.views.decorators import staff_member_required
+from django.contrib.sites.models import Site
+from django.contrib.auth.models import User
+
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.db import models
from django.forms import Widget, TextInput, Textarea, CharField, HiddenInput
@@ -15,14 +18,13 @@
from django.template.defaultfilters import title, escapejs, force_escape
from django.utils.encoding import force_unicode, smart_str
from django.utils.translation import ugettext as _, ugettext_lazy, ugettext
+
+from django.utils.functional import curry
from django.views.generic.create_update import redirect
-#from django import template
-from django.contrib.sites.models import Site
-from django.contrib.auth.models import User
from cms import settings
from cms.admin.change_list import CMSChangeList
-from cms.admin.forms import PageForm, ExtUserCreationForm
+from cms.admin.forms import PageForm, PageUserForm
from cms.admin.utils import get_placeholders
from cms.admin.views import (change_status, change_innavigation, add_plugin,
edit_plugin, remove_plugin, move_plugin, revert_plugins, change_moderation)
@@ -31,7 +33,8 @@
from cms.plugin_pool import plugin_pool
from cms.utils import get_template_from_request, get_language_from_request
from cms.utils.permissions import has_page_add_permission,\
- get_user_permission_level, has_global_change_permissions_permission
+ get_user_permission_level, has_global_change_permissions_permission,\
+ get_subordinate_users
from cms.views import details
from cms.admin.models import BaseInlineFormSetWithQuerySet
from cms.exceptions import NoPermissionsException
@@ -41,7 +44,7 @@
get_test_moderation_level, moderator_should_approve, approve_page
from django.core.urlresolvers import reverse
from cms.utils.admin import render_admin_menu_item
-from django.utils.functional import curry
+
PAGE_ADMIN_INLINES = []
@@ -50,8 +53,7 @@
################################################################################
if settings.CMS_PERMISSION:
- from cms.models import PagePermission, GlobalPagePermission, ExtUser, \
- ExtGroup
+ from cms.models import PagePermission, GlobalPagePermission, PageUser, PageUserGroup
from cms.admin.forms import PagePermissionInlineAdminForm
@@ -142,12 +144,15 @@ class GlobalPagePermissionAdmin(admin.ModelAdmin):
from django.contrib.auth.admin import UserAdmin
- class ExtUserAdmin(UserAdmin):
- form = ExtUserCreationForm
+ class PageUserAdmin(UserAdmin):
+ form = PageUserForm
+ model = PageUser
+
+ list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'created_by')
# get_fieldsets method may add fieldsets depending on user
fieldsets = [
- (None, {'fields': ('username', ('password1', 'password2'))}),
+ (None, {'fields': ('username', ('password1', 'password2'), 'notify_user')}),
(_('User details'), {'fields': (('first_name', 'last_name'), 'email')}),
]
@@ -160,7 +165,7 @@ def get_fieldsets(self, request, obj=None):
models = (
(Page, _('Page permissions')),
- (User, _('User permissions')),
+ (PageUser, _('User permissions')),
(PagePermission, _('Page permission management')),
)
@@ -174,32 +179,30 @@ def get_fieldsets(self, request, obj=None):
if fields:
fieldsets.append((title, {'fields': (fields,)}),)
+
+ if not '/add' in request.path:
+ fieldsets[0] = (None, {'fields': ('username', 'notify_user')})
+ fieldsets.append((_('Password'), {'fields': ('password1', 'password2'), 'classes': ('collapse',)}))
return fieldsets
- def add_view(self, request):
- return super(UserAdmin, self).add_view(request)
+ def queryset(self, request):
+ qs = super(PageUserAdmin, self).queryset(request)
+ user_id_set = get_subordinate_users(request.user).values_list('id', flat=True)
+ return qs.filter(pk__in=user_id_set)
+
- def has_add_permission(self, request):
- """Allow add only in popup, this is a shortcut admin view, for other
- operations might be used the auth user admin
- """
- if '_popup' in request.REQUEST and (request.user.is_superuser or \
- request.user.has_perm(User._meta.app_label + '.' + User._meta.get_add_permission())):
- return True
- return False
+ def add_view(self, request):
+ return super(UserAdmin, self).add_view(request)
- has_change_permission = lambda *args: False
- has_delete_permission = lambda *args: False
- admin.site.register(ExtUser, ExtUserAdmin)
+ admin.site.register(PageUser, PageUserAdmin)
+
+ admin.site.register(PageUserGroup)
################################################################################
# Page
################################################################################
-if 'reversion' in settings.INSTALLED_APPS:
- from reversion import revision
-
class PageAdmin(admin.ModelAdmin):
form = PageForm
@@ -343,9 +346,9 @@ def get_urls(self):
url(r'^([0-9]+)/jsi18n/$',
self.admin_site.admin_view(self.redirect_jsi18n),
name='%s_jsi18n' % info),
- url(r'^(?:[0-9]+)/(?:((history|version)))/([0-9]+)/$',
- self.admin_site.admin_view(revert_plugins),
- name='%s_revert_plugins' % info),
+
+ # NOTE: revert plugin is newly integrated in overriden revision_view
+
# approve page
url(r'^([0-9]+)/approve/$',
self.admin_site.admin_view(self.approve_page),
@@ -545,7 +548,7 @@ def change_view(self, request, object_id, extra_context=None):
'moderator_should_approve': moderator_should_approve(request, obj),
}
return super(PageAdmin, self).change_view(request, object_id, extra_context)
-
+
def has_add_permission(self, request):
"""
Return true if the current user has permission to add a new page.
@@ -620,6 +623,19 @@ def changelist_view(self, request, extra_context=None):
'admin/change_list.html'
], context, context_instance=RequestContext(request))
+ def revision_view(self, request, object_id, version_id, extra_context=None):
+ """This will be called only if is reversion installed. If its revert,
+ some plugins need to be restored...
+ """
+ response = super(PageAdmin, self).revision_view(request, object_id, version_id, extra_context)
+
+ if request.method == 'POST' \
+ and ('history' in request.path or 'recover' in request.path) \
+ and response.status_code == 302:
+ # revert plugins
+ version = request.path.split("/")[-2]
+ revert_plugins(request, version)
+ return response
def list_pages(self, request, template_name=None, extra_context=None):
"""
@@ -661,7 +677,8 @@ def move_page(self, request, page_id, extra_context=None):
# move page
page.move_page(target, position)
return HttpResponse("ok")
-
+
+
def get_permissions(self, request, page_id):
#if not obj.has_change_permissions_permission(request):
print ">> get_permissions", page_id
@@ -754,7 +771,7 @@ def approve_page(self, request, page_id):
# if request comes from tree..
return render_admin_menu_item(request, page)
return HttpResponseRedirect('../../')
-
+
class PageAdminMixins(admin.ModelAdmin):
pass
View
@@ -8,10 +8,10 @@
from django.db.models.fields import BooleanField
from cms import settings as cms_settings
-from cms.models import Page, Title, PagePermission, ExtUser, ACCESS_PAGE
+from cms.models import Page, Title, PagePermission, PageUser, ACCESS_PAGE
from cms.utils.urlutils import any_path_re
from cms.utils.permissions import get_current_user, get_subordinate_users,\
- get_subordinate_groups
+ get_subordinate_groups, mail_page_user_change
from cms.admin.widgets import UserSelectAdminWidget
@@ -160,48 +160,94 @@ def save(self, commit=True):
return instance
-class ExtUserCreationForm(UserCreationForm):
+class PageUserForm(UserCreationForm):
can_add_page = forms.BooleanField(label=_('Can add page'), required=False, initial=True)
can_change_page = forms.BooleanField(label=_('Can change page'), required=False, initial=True)
can_delete_page = forms.BooleanField(label=_('Can delete page'), required=False)
- can_add_user = forms.BooleanField(label=_('Can create user'), required=False)
- can_change_user = forms.BooleanField(label=_('Can change User'), required=False)
- can_delete_user = forms.BooleanField(label=_('Can delete User'), required=False)
+ can_add_pageuser = forms.BooleanField(label=_('Can create user'), required=False)
+ can_change_pageuser = forms.BooleanField(label=_('Can change User'), required=False)
+ can_delete_pageuser = forms.BooleanField(label=_('Can delete User'), required=False)
can_add_pagepermission = forms.BooleanField(label=_('Can add page permission'), required=False)
can_change_pagepermission = forms.BooleanField(label=_('Can change page permission'), required=False)
can_delete_pagepermission = forms.BooleanField(label=_('Can delete page permission'), required=False)
+ notify_user = forms.BooleanField(label=_('Notify user'), required=False,
+ help_text=_('Send email notification to user about username or password change. Requires user email.'))
+
class Meta:
- model = ExtUser
+ model = PageUser
+ def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
+ initial=None, error_class=ErrorList, label_suffix=':',
+ empty_permitted=False, instance=None):
+ super(PageUserForm, self).__init__(data, files, auto_id, prefix,
+ initial, error_class, label_suffix, empty_permitted, instance)
+
+ if instance:
+ # if it is a change form, keep those fields as not required
+ # password will be changed only if there is something entered inside
+ self.fields['password1'].required = False
+ self.fields['password1'].label = _('New password')
+ self.fields['password2'].required = False
+ self.fields['password2'].label = _('New password confirmation')
+
+ self._password_change = True
+
+ def clean_username(self):
+ if self.instance:
+ return self.cleaned_data['username']
+ return super(PageUserForm, self).clean_username()
+
+ def clean_password2(self):
+ if self.instance and self.cleaned_data['password1'] == '' and self.cleaned_data['password2'] == '':
+ self._password_change = False
+ return u''
+ return super(PageUserForm, self).clean_password2()
+
+ def clean(self):
+ cleaned_data = super(PageUserForm, self).clean()
+ notify_user = self.cleaned_data['notify_user']
+ if notify_user and not self.cleaned_data.get('email', None):
+ raise forms.ValidationError(_("Email notification requires valid email address."))
+ return cleaned_data
+
def save(self, commit=True):
"""Create user, assign him to staff users, and create permissions for
him if required. Also assigns creator to user.
"""
- user = super(ExtUserCreationForm, self).save(commit=False)
- user.is_staff=True
+ Super = self._password_change and PageUserForm or UserCreationForm
+ user = super(Super, self).save(commit=False)
+
+ user.is_staff = True
# assign creator to user
user.created_by = get_current_user()
-
- models = (Page, User, PagePermission)
-
+
if commit:
user.save()
+
+ if self.cleaned_data['notify_user']:
+ print "notify!!"
+ created = not bool(self.instance)
+ mail_page_user_change(user, created, self.cleaned_data['password1'])
+
+ models = (Page, PageUser, PagePermission)
for model in models:
name = model.__name__.lower()
content_type = ContentType.objects.get_for_model(model)
for t in ('add', 'change', 'delete'):
- if not self.cleaned_data.get('can_%s_%s' % (t, name), None):
- continue
if not user.pk:
# save user, otherwise we can't assign permissions to him
user.save()
# add permission `t` to model `model`
codename = getattr(model._meta, 'get_%s_permission' % t)()
permission = Permission.objects.get(content_type=content_type, codename=codename)
- user.user_permissions.add(permission)
+
+ if self.cleaned_data.get('can_%s_%s' % (t, name), None):
+ user.user_permissions.add(permission)
+ else:
+ user.user_permissions.remove(permission)
return user
View
@@ -14,7 +14,7 @@ def get_placeholders(request, template_name):
except TemplateDoesNotExist:
return []
context = details(request, no404=True, only_context=True)
- # this sucks - it requests context in admin and eats user messages,
+ # lacks - it requests context in admin and eats user messages,
# standard context will be hopefully enough here
# temp.render(RequestContext(request, context))
View
@@ -244,6 +244,7 @@ def save_all_plugins(request, page, excludes=None):
plugin.save()
def revert_plugins(request, version_id):
+ print ">> revert_plugins !"
from reversion.models import Version
version = get_object_or_404(Version, pk=version_id)
revs = [related_version.object_version for related_version in version.revision.version_set.all()]
View
@@ -51,7 +51,7 @@ def render(self, name, value, attrs=None, choices=()):
if hasattr(self, 'user') and (self.user.is_superuser or \
self.user.has_perm(User._meta.app_label + '.' + User._meta.get_add_permission())):
# append + icon
- add_url = '../../../cms/extuser/add/'
+ add_url = '../../../cms/pageuser/add/'
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
(add_url, name))
output.append(u'<img src="%simg/admin/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another')))
Oops, something went wrong.

0 comments on commit db4bc26

Please sign in to comment.