Skip to content

Commit

Permalink
refactor to use get_xform_users_with_perms which uses a less expensiv…
Browse files Browse the repository at this point in the history
…e query
  • Loading branch information
ukanga committed Apr 27, 2017
1 parent f44e581 commit c5eb9c2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
8 changes: 5 additions & 3 deletions onadata/apps/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from django.utils.translation import ugettext as _
from django.views.decorators.http import (require_GET, require_http_methods,
require_POST)
from guardian.shortcuts import assign_perm, get_users_with_perms, remove_perm
from guardian.shortcuts import assign_perm, remove_perm
from rest_framework.authtoken.models import Token

from onadata.apps.logger.models import Instance, XForm
Expand Down Expand Up @@ -51,7 +51,9 @@
from onadata.libs.utils.user_auth import (add_cors_headers, check_and_set_user,
check_and_set_user_and_form,
get_user_default_project,
get_xform_and_perms, has_permission,
get_xform_and_perms,
get_xform_users_with_perms,
has_permission,
helper_auth_helper, set_profile_data)
from onadata.libs.utils.viewer_tools import (EnketoError, enketo_url,
get_enketo_preview_url, get_form)
Expand Down Expand Up @@ -356,7 +358,7 @@ def set_xform_owner_data(data, xform, request, username, id_string):
data['external_export_form'] = ExternalExportForm()
users_with_perms = []

for perm in get_users_with_perms(xform, attach_perms=True).items():
for perm in get_xform_users_with_perms(xform).items():
has_perm = []
if 'change_xform' in perm[1]:
has_perm.append(_(u"Can Edit"))
Expand Down
17 changes: 17 additions & 0 deletions onadata/libs/utils/user_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,23 @@ def get_xform_and_perms(username, id_string, request):
return [xform, is_owner, can_edit, can_view]


def get_xform_users_with_perms(xform):
"""Similar to django-guadian's get_users_with_perms here the query makes
use of the xformuserobjectpermission_set to return a dictionary of users
with a list of permissions to the XForm object. The query in use is not as
expensive as the one in use with get_users_with_perms
"""
user_perms = {}
for p in xform.xformuserobjectpermission_set.all().select_related(
'user', 'permission').only(
'user', 'permission__codename', 'content_object_id'):
if p.user.username not in user_perms:
user_perms[p.user] = []
user_perms[p.user].append(p.permission.codename)

return user_perms


def helper_auth_helper(request):
if request.user and request.user.is_authenticated():
return None
Expand Down

0 comments on commit c5eb9c2

Please sign in to comment.