Commits

Hector Garcia committed 40c19b9

Added example project. Unified rbac_permission() params to receive a model class if you want to query generic permissions, or a model instance if you want to do it on per-object permissions

  • Participants
  • Parent commits 968aa23

Comments (0)

Files changed (11)

File example/__init__.py

Empty file added.

File example/db/dev.db

Binary file added.

File example/localsettings.py

+import os.path
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+INTERNAL_IPS = ('127.0.0.1',)
+
+DATABASE_ENGINE = 'sqlite3'
+DATABASE_NAME = os.path.join(os.path.dirname(__file__), 'db/dev.db')
+
+TEMPLATE_DIRS = (
+    os.path.join(os.path.dirname(__file__), 'templates'),
+)

File example/manage.py

+#!/usr/bin/env python
+from django.core.management import execute_manager
+try:
+    import settings # Assumed to be in the same directory.
+except ImportError:
+    import sys
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+    sys.exit(1)
+
+if __name__ == "__main__":
+    execute_manager(settings)

File example/myapp/__init__.py

Empty file added.

File example/myapp/urls.py

+from django.conf.urls.defaults import *
+
+urlpatterns = patterns('myapp.views',
+    url(
+        regex=r'^$',
+        view='my_view',
+        name='my_view',
+    ),
+)

File example/myapp/views.py

+from django.template import RequestContext
+from django.shortcuts import get_object_or_404
+from django.http import HttpResponse, HttpResponseForbidden
+from django.contrib.auth.models import User, Group
+
+from rbac.models import RBACRole
+from rbac.utils import rbac_permission
+
+
+def users_are_friends(user, target_user):
+    return False
+
+def users_are_coworkers(user, target_user):
+    return True
+
+def get_user_roles(user, target_user):
+    roles = []
+    if users_are_friends(user, target_user):
+        roles.append(RBACRole.objects.get(name='friend'))
+    if users_are_coworkers(user, target_user):
+        roles.append(RBACRole.objects.get(name='coworker'))
+    return roles
+
+def my_view(request):
+    """Displays info details from nabuco user"""
+
+    owner, c = User.objects.get_or_create(username='nabuco')
+    # Owner of the object has full permissions, otherwise check RBAC
+    if request.user != owner:
+
+        # Get roles and permission for a social relationship RBAC context
+        roles = get_user_roles(request.user, owner)
+
+        # Per-model permission:
+        # Has user permission to display groups that nabuco belongs to?
+        if not rbac_permission(roles, owner, Group, 'display object'):
+            return HttpResponseForbidden("Sorry, you are not allowed to see nabuco groups")
+
+        # Per-object permission:
+        # Has user permission to see this group which nabuco belong to?
+        group_inst = get_object_or_404(Group, name='punks')
+        if not rbac_permission(roles, owner, group_inst, 'display object')
+            return HttpResponseForbidden("Sorry, you are not allowed to see this group details")
+
+    return HttpResponse('Test passed!')

File example/settings.py

+import os.path
+
+ADMINS = (
+    # ('Your Name', 'your_email@domain.com'),
+)
+
+MANAGERS = ADMINS
+
+TIME_ZONE = 'America/Chicago'
+
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+USE_I18N = True
+
+MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
+MEDIA_URL = '/media'
+ADMIN_MEDIA_PREFIX = '/media/admin/'
+
+SECRET_KEY = '!bkp)n00_c@-93aco!fxgce*nwz8v+jsm#dn0r=h!vy97#)+e_'
+
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.load_template_source',
+    'django.template.loaders.app_directories.load_template_source',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+)
+
+ROOT_URLCONF = 'example.urls'
+
+INSTALLED_APPS = (
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+    'rbac',
+)
+
+try:
+    from localsettings import *
+except ImportError:
+    pass
+

File example/templates/base.html

+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+
+<head>
+    <title>nbskel project</title>
+</head>
+
+<body>
+    {% block content %}<p>Hello world!</p>{% endblock content %}
+</body>
+
+</html>

File example/urls.py

+import os
+
+from django.conf.urls.defaults import *
+from django.conf import settings
+from django.contrib import admin
+
+
+admin.autodiscover()
+
+urlpatterns = patterns('',
+    (r'^admin/(.*)', admin.site.root),
+    (r'^myapp/', include('myapp.urls')),
+)
+
+if settings.DEBUG:
+    urlpatterns += patterns('',
+        (r'^media/(?P<path>.*)$', 'django.views.static.serve',
+            {'document_root': os.path.join(os.path.dirname(__file__), "media")}),
+    )
+

File rbac/utils.py

 def get_permission(owner, model, operation, generic):
     owner_ct = ContentType.objects.get_for_model(owner)
     model_ct = ContentType.objects.get_for_model(model)
-    # TODO: remove generic param, if model is an instance then do an
-    # RBACPermission search, if it is a Model class do a RBACGenericPermission instead
-    if generic:
+    # model is a class
+    if isinstance(model, type):
         permission = RBACGenericPermission.objects.get(owner_ct=owner_ct,
             owner_id=owner.id, content_type=model_ct, operation=operation)
+    # model is a model instance
     else:
         permission = RBACPermission.objects.get(owner_ct=owner_ct, owner_id=owner.id,
             object_ct=model_ct, object_id=model.id, operation=operation)
     return permission
 
-def rbac_permission(roles, owner, model, operation_str, generic=True):
-    # TODO: change order of params to match manager methods
-    # TODO: remove generic param
+def rbac_permission(owner, model, operation_str, roles):
     # TODO: roles param could be a list/queryset or a single model instance
     operation = RBACOperation.objects.get(name=operation_str)
     try:
-        permission = get_permission(owner, model, operation, generic)
+        permission = get_permission(owner, model, operation)
     # If permission does not exist, authorization is not allowed
     except ObjectDoesNotExist:
         return False