Skip to content

Instantly share code, notes, and snippets.

@Ciantic
Created February 2, 2011 21:44
Show Gist options
  • Save Ciantic/808516 to your computer and use it in GitHub Desktop.
Save Ciantic/808516 to your computer and use it in GitHub Desktop.
ForbiddenMixin can't be Mixin for security's sake
from django.conf.urls.defaults import * #@UnusedWildImport
from django.contrib.auth.models import Permission, User
from django.http import HttpResponse
from django.test import TestCase
from django.test.client import Client
from django.views.generic.base import View
class ForbiddenMixin(object):
"""ForbiddenMixin"""
def dispatch(self, request, *args, **kwargs):
if not request.user.has_perm('auth.change_user'):
return HttpResponse("Not for you man", status=403)
return super(ForbiddenMixin, self).dispatch(request, *args, **kwargs)
class AuthedView(ForbiddenMixin, View):
def get(self, request, *args, **kwargs):
return HttpResponse("ok")
class AuthedViewSecond(View, ForbiddenMixin):
def get(self, request, *args, **kwargs):
return HttpResponse("ok")
def test_root_view(request):
return HttpResponse('ok')
urlpatterns = patterns('',
(r'^$', 'pagesystem.tests.forbiddenmixin.test_root_view'),
(r'^authed/$', AuthedView.as_view()),
(r'^authed2/$', AuthedViewSecond.as_view()),
)
class TestForbiddenMixin(TestCase):
urls = 'pagesystem.tests.forbiddenmixin'
def setUp(self):
self.usr = User.objects.create(username='test', is_staff=True)
self.usr.set_password('1234')
self.usr.save()
self.usr.user_permissions.add(Permission.objects.get_by_natural_key('change_user', 'auth', 'user'))
def test_auth(self):
c = Client()
self.assertEqual(c.get("/authed/").status_code, 403)
self.assertEqual(c.get("/authed2/").status_code, 403) # <----------- this fails (is assumed 200) because of MRO of python
c.login(username='test', password='1234')
self.assertEqual(c.get("/authed/").status_code, 200)
self.assertEqual(c.get("/authed2/").status_code, 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment