From c5eb9c22deeaa11606d6687e008b8747fb768ddc Mon Sep 17 00:00:00 2001 From: Dickson Ukang'a Date: Thu, 27 Apr 2017 15:33:38 +0300 Subject: [PATCH] refactor to use get_xform_users_with_perms which uses a less expensive query --- onadata/apps/main/views.py | 8 +++++--- onadata/libs/utils/user_auth.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index f6ffeafbb9..7f7a845e51 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -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 @@ -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) @@ -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")) diff --git a/onadata/libs/utils/user_auth.py b/onadata/libs/utils/user_auth.py index ccf0b28046..cb48e2e11a 100644 --- a/onadata/libs/utils/user_auth.py +++ b/onadata/libs/utils/user_auth.py @@ -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