def view_obj_permissions(request, class_name, obj_id=None,
    user_id=None, group_id=None,
    row_template='object_permissions/permissions/object_row.html'):
    """
    Generic view for editing permissions on an object when the user is already.
    Known.  This is an admin only view since it is impossible to know the
    permission scheme for the apps that are registering properties.
    """
    
    if not request.user.is_superuser:
        return HttpResponseForbidden('You are not authorized to view this page')
    
    try:
        cls = get_class(class_name)
    except KeyError:
        return HttpResponseNotFound('Class type does not exist')
    
    if request.method == 'POST':
        form = ObjectPermissionFormNewUsers(cls, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            form_user = form.cleaned_data['user']
            group = form.cleaned_data['group']
            edited_user = form_user if form_user else group
            
            
            if form.update_perms():
                # send correct signal based on new or edited user
                if data['new']:
                    view_add_user.send(sender=cls,
                                       editor=request.user,
                                       user=edited_user, obj=data['obj'])
                else:
                    view_edit_user.send(sender=cls,
                                        editor=request.user,
                                        user=edited_user, obj=data['obj'])
                
                # return html to replace existing user row
                return render_to_response(row_template,
                    {'class_name':class_name, 'obj':data['obj'], 'persona':edited_user})
            else:
                # no permissions, send ajax response to remove object
                view_remove_user.send(sender=cls,
                                      editor=request.user, user=edited_user,
                                      obj=data['obj'])
                id = '"%s_%s"' % (class_name, obj_id)
                return HttpResponse(id, mimetype='application/json')
        
        # error in form return ajax response
        content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')
    
    # GET - create form for editing and return as html
    if obj_id:
        obj = get_object_or_404(cls, pk=obj_id)
        data = {'obj':obj}
        if user_id:
            form_user = get_object_or_404(User, id=user_id)
            data['user'] = user_id
            data['permissions'] = get_user_perms(form_user, obj, False)
            url = reverse('user-edit-permissions',
                          args=(user_id, class_name, obj_id))
        elif group_id:
            group = get_object_or_404(Group, id=group_id)
            data['group'] = group_id
            data['permissions'] = get_group_perms(group, obj)
            url = reverse('group-edit-permissions',
                          args=(group_id, class_name, obj_id))
    else:
        obj = None
        if user_id:
            get_object_or_404(User, id=user_id)
            data={'user':user_id}
            url = reverse('user-add-permissions',
                          args=(user_id, class_name))
        elif group_id:
            get_object_or_404(Group, id=group_id)
            data={'group':group_id}
            url = reverse('group-add-permissions',
                          args=(group_id, class_name))
    
    form = ObjectPermissionFormNewUsers(cls, data)
    return render_to_response('object_permissions/permissions/form.html',
            {'form':form, 'obj':obj, 'user_id':user_id, 'group_id':group_id, 
             'url':url},
            context_instance=RequestContext(request))
def view_obj_permissions(
        request,
        class_name,
        obj_id=None,
        user_id=None,
        group_id=None,
        row_template='object_permissions/permissions/object_row.html'):
    """
    Generic view for editing permissions on an object when the user is already.
    Known.  This is an admin only view since it is impossible to know the
    permission scheme for the apps that are registering properties.
    """

    if not request.user.is_superuser:
        return HttpResponseForbidden(
            'You are not authorized to view this page')

    try:
        cls = get_class(class_name)
    except KeyError:
        return HttpResponseNotFound('Class type does not exist')

    if request.method == 'POST':
        form = ObjectPermissionFormNewUsers(cls, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            form_user = form.cleaned_data['user']
            group = form.cleaned_data['group']
            edited_user = form_user if form_user else group

            if form.update_perms():
                # send correct signal based on new or edited user
                if data['new']:
                    view_add_user.send(sender=cls,
                                       editor=request.user,
                                       user=edited_user,
                                       obj=data['obj'])
                else:
                    view_edit_user.send(sender=cls,
                                        editor=request.user,
                                        user=edited_user,
                                        obj=data['obj'])

                # return html to replace existing user row
                return render_to_response(
                    row_template, {
                        'class_name': class_name,
                        'obj': data['obj'],
                        'persona': edited_user
                    })
            else:
                # no permissions, send ajax response to remove object
                view_remove_user.send(sender=cls,
                                      editor=request.user,
                                      user=edited_user,
                                      obj=data['obj'])
                id = '"%s_%s"' % (class_name, obj_id)
                return HttpResponse(id, mimetype='application/json')

        # error in form return ajax response
        content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')

    # GET - create form for editing and return as html
    if obj_id:
        obj = get_object_or_404(cls, pk=obj_id)
        data = {'obj': obj}
        if user_id:
            form_user = get_object_or_404(User, id=user_id)
            data['user'] = user_id
            data['permissions'] = get_user_perms(form_user, obj, False)
            url = reverse('user-edit-permissions',
                          args=(user_id, class_name, obj_id))
        elif group_id:
            group = get_object_or_404(Group, id=group_id)
            data['group'] = group_id
            data['permissions'] = get_group_perms(group, obj)
            url = reverse('group-edit-permissions',
                          args=(group_id, class_name, obj_id))
    else:
        obj = None
        if user_id:
            get_object_or_404(User, id=user_id)
            data = {'user': user_id}
            url = reverse('user-add-permissions', args=(user_id, class_name))
        elif group_id:
            get_object_or_404(Group, id=group_id)
            data = {'group': group_id}
            url = reverse('group-add-permissions', args=(group_id, class_name))

    form = ObjectPermissionFormNewUsers(cls, data)
    return render_to_response('object_permissions/permissions/form.html', {
        'form': form,
        'obj': obj,
        'user_id': user_id,
        'group_id': group_id,
        'url': url
    },
                              context_instance=RequestContext(request))
def view_permissions(request, obj, url, user_id=None, group_id=None,
                user_template='object_permissions/permissions/user_row.html',
                group_template='object_permissions/permissions/group_row.html'
                ):
    """
    Update a User or Group permissions on an object.  This is a generic view
    intended to be used for editing permissions on any object.  It must be
    configured with a model and url.  It may also be customized by adding custom
    templates or changing the pk field.
    
    @param obj: object permissions are being set on
    @param url: name of url being edited
    @param user_id: ID of User being edited
    @param group_id: ID of Group being edited
    @param user_template: template used to render user rows
    @param group_template: template used to render group rows
    """
    if request.method == 'POST':
        form = ObjectPermissionFormNewUsers(obj.__class__, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            form_user = form.cleaned_data['user']
            group = form.cleaned_data['group']
            edited_user = form_user if form_user else group
            
            if form.update_perms():
                # send correct signal based on new or edited user
                if data['new']:
                    view_add_user.send(sender=obj.__class__,
                                       editor=request.user,
                                       user=edited_user, obj=obj)
                else:
                    view_edit_user.send(sender=obj.__class__,
                                        editor=request.user,
                                        user=edited_user, obj=obj)
                
                # return html to replace existing user row
                if form_user:
                    return render_to_response(user_template,
                                {'object':obj, 'user_detail':form_user, 'url':url},
                                context_instance=RequestContext(request))
                else:
                    return render_to_response(group_template,
                                {'object':obj, 'group':group, 'url':url},
                                context_instance=RequestContext(request))
                
            else:
                # no permissions, send ajax response to remove user
                view_remove_user.send(sender=obj.__class__,
                                      editor=request.user, user=edited_user,
                                      obj=obj)
                id = ('"user_%d"' if form_user else '"group_%d"')%edited_user.pk
                return HttpResponse(id, mimetype='application/json')

        # error in form return ajax response
        content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')

    if user_id:
        form_user = get_object_or_404(User, id=user_id)
        data = {'permissions':get_user_perms(form_user, obj, False),
                'user':user_id, 'obj':obj}
    elif group_id:
        group = get_object_or_404(Group, id=group_id)
        data = {'permissions':get_group_perms(group, obj),
                'group':group_id, 'obj':obj}
    else:
        data = {}
        
    form = ObjectPermissionFormNewUsers(obj.__class__, data)
    
    return render_to_response('object_permissions/permissions/form.html',
                {'form':form, 'obj':obj, 'user_id':user_id,
                'group_id':group_id, 'url':url},
               context_instance=RequestContext(request))
def view_permissions(
        request,
        obj,
        url,
        user_id=None,
        group_id=None,
        user_template='object_permissions/permissions/user_row.html',
        group_template='object_permissions/permissions/group_row.html'):
    """
    Update a User or Group permissions on an object.  This is a generic view
    intended to be used for editing permissions on any object.  It must be
    configured with a model and url.  It may also be customized by adding custom
    templates or changing the pk field.
    
    @param obj: object permissions are being set on
    @param url: name of url being edited
    @param user_id: ID of User being edited
    @param group_id: ID of Group being edited
    @param user_template: template used to render user rows
    @param group_template: template used to render group rows
    """
    if request.method == 'POST':
        form = ObjectPermissionFormNewUsers(obj.__class__, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            form_user = form.cleaned_data['user']
            group = form.cleaned_data['group']
            edited_user = form_user if form_user else group

            if form.update_perms():
                # send correct signal based on new or edited user
                if data['new']:
                    view_add_user.send(sender=obj.__class__,
                                       editor=request.user,
                                       user=edited_user,
                                       obj=obj)
                else:
                    view_edit_user.send(sender=obj.__class__,
                                        editor=request.user,
                                        user=edited_user,
                                        obj=obj)

                # return html to replace existing user row
                if form_user:
                    return render_to_response(
                        user_template, {
                            'object': obj,
                            'user_detail': form_user,
                            'url': url
                        },
                        context_instance=RequestContext(request))
                else:
                    return render_to_response(
                        group_template, {
                            'object': obj,
                            'group': group,
                            'url': url
                        },
                        context_instance=RequestContext(request))

            else:
                # no permissions, send ajax response to remove user
                view_remove_user.send(sender=obj.__class__,
                                      editor=request.user,
                                      user=edited_user,
                                      obj=obj)
                id = ('"user_%d"'
                      if form_user else '"group_%d"') % edited_user.pk
                return HttpResponse(id, mimetype='application/json')

        # error in form return ajax response
        content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')

    if user_id:
        form_user = get_object_or_404(User, id=user_id)
        data = {
            'permissions': get_user_perms(form_user, obj, False),
            'user': user_id,
            'obj': obj
        }
    elif group_id:
        group = get_object_or_404(Group, id=group_id)
        data = {
            'permissions': get_group_perms(group, obj),
            'group': group_id,
            'obj': obj
        }
    else:
        data = {}

    form = ObjectPermissionFormNewUsers(obj.__class__, data)

    return render_to_response('object_permissions/permissions/form.html', {
        'form': form,
        'obj': obj,
        'user_id': user_id,
        'group_id': group_id,
        'url': url
    },
                              context_instance=RequestContext(request))