def test_req_process(self): """ Test that when a request is made for a user, it shows up in the dashboard. """ self.client.login(username="******", password="******") resp = self.client.get(reverse("permissionmgmt_dashboard")) # "permission1" should not be mentioned anywhere on the page self.assertContains(resp, "permission1", 0) obj_perm1=ObjectPermission.objects.get_or_create_for_object_or_class( "permission1", self.u1, )[0] obj_perm2=ObjectPermission.objects.get_or_create_for_object_or_class( "permission1", self.u2, )[0] req1 = PermissionRequest.objects.create( requesting_user=self.u2, permittee=Permittee.objects.get_or_create_from_instance(self.u2)[0], permission_owner=self.u1, requested_permission=obj_perm1, ) req2 = PermissionRequest.objects.create( requesting_user=self.u2, permittee=Permittee.objects.get_or_create_from_instance(self.u2)[0], permission_owner=self.u1, requested_permission=obj_perm2, ) resp = self.client.get(reverse("permissionmgmt_dashboard")) # "permission1" should be mentioned twice: once in each request self.assertContains(resp, "permission1", 2) resp = test_get_and_post_form( self.client, reverse("permissionmgmt_dashboard"), dict( approved=[str(req2.id)], denied=[str(req1.id)], ) ) self.assertRedirects(resp, reverse("permissionmgmt_confirm_req")) resp = test_get_and_post_form( self.client, reverse("permissionmgmt_confirm_req"), dict( post="yes", ) ) self.assertRedirects(resp, reverse("home")) self.assertEqual(PermissionRequest.objects.count(), 0) self.assertTrue(has_permission(self.u2, self.u2, "permission1")) self.assertFalse(has_permission(self.u2, self.u1, "permission1"))
def test_req_process(self): """ Test that when a request is made for a user, it shows up in the dashboard. """ self.client.login(username="******", password="******") resp = self.client.get(reverse("permissionmgmt_dashboard")) # "permission1" should not be mentioned anywhere on the page self.assertContains(resp, "permission1", 0) obj_perm1 = ObjectPermission.objects.get_or_create_for_object_or_class( "permission1", self.u1, )[0] obj_perm2 = ObjectPermission.objects.get_or_create_for_object_or_class( "permission1", self.u2, )[0] req1 = PermissionRequest.objects.create( requesting_user=self.u2, permittee=Permittee.objects.get_or_create_from_instance( self.u2)[0], permission_owner=self.u1, requested_permission=obj_perm1, ) req2 = PermissionRequest.objects.create( requesting_user=self.u2, permittee=Permittee.objects.get_or_create_from_instance( self.u2)[0], permission_owner=self.u1, requested_permission=obj_perm2, ) resp = self.client.get(reverse("permissionmgmt_dashboard")) # "permission1" should be mentioned twice: once in each request self.assertContains(resp, "permission1", 2) resp = test_get_and_post_form( self.client, reverse("permissionmgmt_dashboard"), dict( approved=[str(req2.id)], denied=[str(req1.id)], )) self.assertRedirects(resp, reverse("permissionmgmt_confirm_req")) resp = test_get_and_post_form(self.client, reverse("permissionmgmt_confirm_req"), dict(post="yes", )) self.assertRedirects(resp, reverse("home")) self.assertEqual(PermissionRequest.objects.count(), 0) self.assertTrue(has_permission(self.u2, self.u2, "permission1")) self.assertFalse(has_permission(self.u2, self.u1, "permission1"))
def test_remove_from_permittee_no_conflict(self): """ Check that a role can be removed from a permittee along with its permissions when no other roles give the same permission """ self.role1.give_to_permittee(self.u1) self.assertTrue(has_permission(self.u1, self.project, "perm1")) self.role1.remove_from_permittee(self.u1) self.assertFalse(has_permission(self.u1, self.project, "perm1"))
def test_add_permission(self): """ Check that adding a permission to a role gives that permission to all permittees with the role """ self.role1.give_to_permittee(self.u1) self.role1.give_to_permittee(self.u2) self.assertFalse(has_permission(self.u1, self.project, "perm2")) self.assertFalse(has_permission(self.u2, self.project, "perm2")) self.role1.add_permission(self.obj_perm2) self.assertTrue(has_permission(self.u1, self.project, "perm2")) self.assertTrue(has_permission(self.u2, self.project, "perm2"))
def stop_slice(self, slice): """Take out the resource reservation from the aggregates. Subclasses overriding this method should call the parent class to ensure permission checks. """ user = get_permittee_from_threadlocals("user") can_use = has_permission(user, self.as_leaf_class(), "can_use_aggregate") can_edit = has_permission(user, self.as_leaf_class(), "can_edit_aggregate") if not can_use and not can_edit: raise PermissionDenied("can_use_aggregate", self.as_leaf_class(), user, allow_redirect=False) pass
def stop_slice(self, slice): """Take out the resource reservation from the aggregates. Subclasses overriding this method should call the parent class to ensure permission checks. """ user = get_permittee_from_threadlocals("user") can_use = has_permission( user, self.as_leaf_class(), "can_use_aggregate") can_edit = has_permission( user, self.as_leaf_class(), "can_edit_aggregate") if not can_use and not can_edit: raise PermissionDenied( "can_use_aggregate", self.as_leaf_class(), user, allow_redirect=False) pass
def add_member(request, proj_id): """Add a member to the project""" project = get_object_or_404(Project, id=proj_id) if request.method == "POST": form = AddMemberForm(project=project, giver=request.user, data=request.POST) if form.is_valid(): user = User.objects.get(id = request.POST['user'] ) form.save() try: #Sync LDAP project.save() except: logger.warning("User '%s' may have not been added to project '%s'. It could be a bug within LDAP." % (user.username, project.name)) DatedMessage.objects.post_message_to_user( "User '%s' may not own the requested permissions. It could be a bug within LDAP." % user.username, request.user, msg_type=DatedMessage.TYPE_ERROR) return HttpResponseRedirect(reverse("project_detail", args=[proj_id])) #Send mail notification to the user roles = ', '.join(repr(role.encode('ascii')) for role in ProjectRole.objects.filter( id__in = request.POST.getlist('roles')).values_list('name', flat=True)) #XXX: Not sure about this... maybe give_permission_to... for aggregate in project._get_aggregates(): if not has_permission(user, aggregate, "can_use_aggregate"): aggregate.add_to_user(user,"/") try: # Get project detail URL to send via e-mail from expedient.clearinghouse.project import urls project_detail_url = reverse("project_detail", args=[project.id]) or "/" # No "https://" check should be needed if settings are OK site_domain_url = "https://" + Site.objects.get_current().domain + project_detail_url send_mail( settings.EMAIL_SUBJECT_PREFIX + "Project %s membership notification" % (project.name), "You have been added to project '%s' as a user with the following roles: %s.\nYou may start experimenting now by going to %s\n\n" % (project.name, roles, site_domain_url), from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[user.email], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e) return HttpResponseRedirect(reverse("project_detail", args=[proj_id])) else: form = AddMemberForm(project=project, giver=request.user) return simple.direct_to_template( request, template=TEMPLATE_PATH+"/add_member.html", extra_context={ "form": form, "project": project, "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % project.name, reverse("project_detail", args=[project.id])), ("Add Member", request.path), ), }, )
def test_get_aggregates(self): proj = self.test_allowed_create() self.assertEqual(proj.aggregates.count(), 0) give_permission_to("can_use_aggregate", self.agg1, proj) self.assertTrue(has_permission(proj, self.agg1, "can_use_aggregate")) self.assertEqual(proj.aggregates.count(), 1) self.assertTrue(self.agg1.aggregate_ptr in proj.aggregates)
def remove_member(request, proj_id, user_id): """ Kick a member out by stripping his roles """ project = get_object_or_404(Project, id=proj_id) member = get_object_or_404(User, id=user_id) if request.method == "POST": #<UT> if settings.ENABLE_CBAS: authz_user = UserProfile.get_or_create_profile(request.user) user_to_remove = UserProfile.get_or_create_profile(member) remove_member_from_project(project.urn, user_to_remove.urn, authz_user.urn, authz_user.certificate) member = Permittee.objects.get_as_permittee(member) # Remove the roles for role in ProjectRole.objects.filter(project=project): role.remove_from_permittee(member) # Remove other permissions PermissionOwnership.objects.delete_all_for_target(project, member) #Remove can_use_aggregate if user is not member of any other project using the aggregates of this project for projectAgg in project._get_aggregates(): aggNotUsedAnymoreByMember=1 for p in Project.objects.exclude(id=project.id): if projectAgg in p._get_aggregates() and unicode(member) in p.members.values_list("username", flat=True): aggNotUsedAnymoreByMember=0 break; if aggNotUsedAnymoreByMember and not has_permission(member, projectAgg, "can_use_aggregate"): projectAgg.remove_from_user(member,"/") try: #Sync LDAP project.save() except: logger.warning("User '%s' may have not been deleted from project '%s'. It could be a bug within LDAP." % (member.object.username, project.name)) return HttpResponseRedirect( reverse("project_detail", args=[proj_id])) return simple.direct_to_template( request, template=TEMPLATE_PATH+"/remove_member.html", extra_context={ "project": project, "member": member, "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % project.name, reverse("project_detail", args=[project.id])), ("Remove Member %s" % member.username, request.path), ), }, )
def is_super_user(user): """ Checks if the given user is superuser. @param user User object @return boolean True or False depending on permissions for user """ isSuperUser = False if has_permission(user, User, "can_manage_users"): return True else: return False
def is_super_user(user): """ Checks if the given user is superuser. @param user User object @return boolean True or False depending on permissions for user """ isSuperUser = False if (has_permission(user, User, "can_manage_users")): return True else: return False
def test_add_permission_delegation(self): """ Checks that add_permission works, and that delegation permissions are enforced. """ self.role1.give_to_permittee(self.u1) self.role1.add_permission(self.obj_perm2, can_delegate=True) self.role1.add_permission(self.obj_perm3, can_delegate=True) self.role2.give_to_permittee(self.u2, giver=self.u1) self.role2.add_permission(self.obj_perm3, giver=self.u1) self.assertTrue(has_permission(self.u2, self.project, "perm2")) self.assertTrue(has_permission(self.u2, self.project, "perm3")) # check when delegation does not work self.role2.add_permission(self.obj_perm4) self.assertTrue(has_permission(self.u2, self.project, "perm4")) self.assertRaises(PermissionCannotBeDelegated, self.role1.add_permission, self.obj_perm4, giver=self.u2)
def remove_member(request, proj_id, user_id): """Kick a member out by stripping his roles""" project = get_object_or_404(Project, id=proj_id) member = get_object_or_404(User, id=user_id) if request.method == "POST": member = Permittee.objects.get_as_permittee(member) # Remove the roles for role in ProjectRole.objects.filter(project=project): role.remove_from_permittee(member) # Remove other permissions PermissionOwnership.objects.delete_all_for_target(project, member) #Remove can_use_aggregate if user is not member of any other project using the aggregates of this project for projectAgg in project._get_aggregates(): aggNotUsedAnymoreByMember = 1 for p in Project.objects.exclude(id=project.id): if projectAgg in p._get_aggregates() and unicode( member) in p.members.values_list("username", flat=True): aggNotUsedAnymoreByMember = 0 break if aggNotUsedAnymoreByMember and not has_permission( member, projectAgg, "can_use_aggregate"): projectAgg.remove_from_user(member, "/") try: #Sync LDAP project.save() except: logger.warning( "User '%s' may have not been deleted from project '%s'. It could be a bug within LDAP." % (member.object.username, project.name)) return HttpResponseRedirect(reverse("project_detail", args=[proj_id])) return simple.direct_to_template( request, template=TEMPLATE_PATH + "/remove_member.html", extra_context={ "project": project, "member": member, "breadcrumbs": ( ("Home", reverse("home")), ("Project %s" % project.name, reverse("project_detail", args=[project.id])), ("Remove Member %s" % member.username, request.path), ), }, )
def test_remove_permission(self): """ Check that a permission can be removed from a role with and without conflicts """ self.role1.give_to_permittee(self.u1) self.role1.give_to_permittee(self.u2) self.role1.add_permission(self.obj_perm2) # remove with no conflict self.role1.remove_permission(self.obj_perm2) self.assertFalse(has_permission(self.u1, self.project, "perm2")) self.assertFalse(has_permission(self.u2, self.project, "perm2")) # add perm and conflicting role self.role2.give_to_permittee(self.u1) self.role2.give_to_permittee(self.u2) self.role1.add_permission(self.obj_perm2) self.assertTrue(has_permission(self.u1, self.project, "perm2")) self.assertTrue(has_permission(self.u2, self.project, "perm2")) # nothing should happen since role2 has "perm2" self.role1.remove_permission(self.obj_perm2) self.assertTrue(has_permission(self.u1, self.project, "perm2")) self.assertTrue(has_permission(self.u2, self.project, "perm2"))
def process_request(self, request): if not request.POST.has_key('cert') or not request.POST.has_key('key') or not request.POST.has_key('csrfmiddlewaretoken'): return None cert_str = request.POST.get('cert') sign_str = request.POST.get('key') token = request.POST.get('csrfmiddlewaretoken') if not cert_str or not sign_str or not token: return None myBackend = ScriptsRemoteUserBackend() try: user = myBackend.authenticate(cert_str, sign_str, token) if not user: raise # In case of error, show a generic error except: isSuperUser = False try: if has_permission(request.user, User, "can_manage_users"): isSuperUser = True except: pass if request.session.get("visited") == None: showFirstTimeTooltips = True request.session["visited"] = True else: showFirstTimeTooltips = False return direct_to_template( request, template="expedient/clearinghouse/registration/login.html", extra_context={ "error": "Could not log in with cert, key. Check that you are using the proper pair or try authenticating with user, pass", "isSuperUser": isSuperUser, "showFirstTimeTooltips": showFirstTimeTooltips, "breadcrumbs": ( ("Home", reverse("home")), ), } ) auth.login(request, user) if request.user.is_authenticated(): # They're already authenticated --- go ahead and redirect redirect_field_name = REDIRECT_FIELD_NAME redirect_to = request.REQUEST.get(redirect_field_name, '') if not redirect_to or '//' in redirect_to or ' ' in redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(redirect_to)
def test_give_to_permittee(self): # Give the role to a user and check that she gets the permission self.role1.give_to_permittee(self.u1) self.assertTrue(has_permission(self.u1, self.project, "perm1")) # check that delegation permissions are enforced self.assertRaises( PermissionCannotBeDelegated, self.role1.give_to_permittee, self.u2, giver=self.u1, ) # Give another role to the user and check that she gets the permission self.role2.give_to_permittee(self.u1, can_delegate=True) self.assertTrue(has_permission(self.u1, self.project, "perm2")) # check that delegation permissions are enforced self.role2.give_to_permittee( self.u2, giver=self.u1, ) self.assertTrue(has_permission(self.u1, self.project, "perm2"))
def test_add_permission_delegation(self): """ Checks that add_permission works, and that delegation permissions are enforced. """ self.role1.give_to_permittee(self.u1) self.role1.add_permission(self.obj_perm2, can_delegate=True) self.role1.add_permission(self.obj_perm3, can_delegate=True) self.role2.give_to_permittee(self.u2, giver=self.u1) self.role2.add_permission(self.obj_perm3, giver=self.u1) self.assertTrue(has_permission(self.u2, self.project, "perm2")) self.assertTrue(has_permission(self.u2, self.project, "perm3")) # check when delegation does not work self.role2.add_permission(self.obj_perm4) self.assertTrue(has_permission(self.u2, self.project, "perm4")) self.assertRaises( PermissionCannotBeDelegated, self.role1.add_permission, self.obj_perm4, giver=self.u2 )
def process_request(self, request): if not request.POST.has_key('cert') or not request.POST.has_key( 'key') or not request.POST.has_key('csrfmiddlewaretoken'): return None cert_str = request.POST.get('cert') sign_str = request.POST.get('key') token = request.POST.get('csrfmiddlewaretoken') if not cert_str or not sign_str or not token: return None myBackend = ScriptsRemoteUserBackend() try: user = myBackend.authenticate(cert_str, sign_str, token) if not user: raise # In case of error, show a generic error except: isSuperUser = False try: if has_permission(request.user, User, "can_manage_users"): isSuperUser = True except: pass if request.session.get("visited") == None: showFirstTimeTooltips = True request.session["visited"] = True else: showFirstTimeTooltips = False return direct_to_template( request, template="expedient/clearinghouse/registration/login.html", extra_context={ "error": "Could not log in with cert, key. Check that you are using the proper pair or try authenticating with user, pass", "isSuperUser": isSuperUser, "showFirstTimeTooltips": showFirstTimeTooltips, "breadcrumbs": (("Home", reverse("home")), ), }) auth.login(request, user) if request.user.is_authenticated(): # They're already authenticated --- go ahead and redirect redirect_field_name = REDIRECT_FIELD_NAME redirect_to = request.REQUEST.get(redirect_field_name, '') if not redirect_to or '//' in redirect_to or ' ' in redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(redirect_to)
def clean_roles(self): """ Make sure that no roles have been taken out unless the user has the "can_remove_member" permission. """ roles = self.cleaned_data["roles"] for role in self.initial_roles: if role not in roles and\ not has_permission(self.giver, self.project, "can_remove_member"): raise forms.ValidationError( "You tried to remove role '%s' from the user, " "but you do not have permission to remove members " "so you cannot remove roles from members either." % role.name) return roles
def clean_roles(self): """ Make sure that no roles have been taken out unless the user has the "can_remove_members" permission. """ roles = self.cleaned_data["roles"] for role in self.initial_roles: if role not in roles and\ not has_permission(self.giver, self.project, "can_remove_members"): raise forms.ValidationError( "You tried to remove role '%s' from the user, " "but you do not have permission to remove members " "so you cannot remove roles from members either." % role.name) return roles
def home(request): isSuperUser = False if (has_permission(request.user, User, "can_manage_users")): isSuperUser = True if request.session.get("visited") == None: showFirstTimeTooltips = True request.session["visited"] = True else: showFirstTimeTooltips = False #<UT> if settings.ENABLE_CBAS: try: user_profile = UserProfile.get_or_create_profile(request.user) user_details = { "FIRST_NAME": user_profile.user.first_name, "LAST_NAME": user_profile.user.last_name, "EMAIL": user_profile.user.email } # if not (user_profile.urn and user_profile.certificate and # user_profile.certificate_key and user_profile.credentials): urn, cert, creds, ssh_key_pair = get_member_info( str(request.user), user_details) user_profile.urn = urn user_profile.certificate = cert user_profile.credentials = creds if ssh_key_pair: user_profile.public_ssh_key = ssh_key_pair[0] user_profile.private_ssh_key = ssh_key_pair[1] user_profile.save() except socket_error as serr: # Error 111: connection refused if serr.errno == errno.ECONNREFUSED: DatedMessage.objects.post_message_to_user( "Warning: the clearinghouse is enabled, but its server is not running. You or the administrator should start it", request.user, msg_type=DatedMessage.TYPE_WARNING) return direct_to_template(request, template="expedient/clearinghouse/index.html", extra_context={ "isSuperUser": isSuperUser, "showFirstTimeTooltips": showFirstTimeTooltips, "breadcrumbs": (("Home", reverse("home")), ), })
def home(request): isSuperUser = False if(has_permission(request.user, User, "can_manage_users")): isSuperUser = True if request.session.get("visited") == None: showFirstTimeTooltips = True request.session["visited"] = True else: showFirstTimeTooltips = False #<UT> if settings.ENABLE_CBAS: try: user_profile = UserProfile.get_or_create_profile(request.user) user_details = {"FIRST_NAME": user_profile.user.first_name, "LAST_NAME": user_profile.user.last_name, "EMAIL": user_profile.user.email} # if not (user_profile.urn and user_profile.certificate and # user_profile.certificate_key and user_profile.credentials): urn, cert, creds, ssh_key_pair = get_member_info(str(request.user), user_details) user_profile.urn = urn user_profile.certificate = cert user_profile.credentials = creds if ssh_key_pair: # Keys are returned only for new registration user_profile.public_ssh_key = ssh_key_pair[0] user_profile.private_ssh_key = ssh_key_pair[1] user_profile.save() except socket_error as serr: # Error 111: connection refused if serr.errno == errno.ECONNREFUSED: DatedMessage.objects.post_message_to_user( "Warning: the clearinghouse is enabled, but its server is not running. You or the administrator should start it", request.user, msg_type=DatedMessage.TYPE_WARNING) return direct_to_template( request, template="expedient/clearinghouse/index.html", extra_context={ "isSuperUser": isSuperUser, "showFirstTimeTooltips": showFirstTimeTooltips, "breadcrumbs": ( ("Home", reverse("home")), ), } )
def home(request): isSuperUser = False if (has_permission(request.user, User, "can_manage_users")): isSuperUser = True if request.session.get('visited') == None: showFirstTimeTooltips = True request.session['visited'] = True else: showFirstTimeTooltips = False return direct_to_template(request, template='expedient/clearinghouse/index.html', extra_context={ "isSuperUser": isSuperUser, "showFirstTimeTooltips": showFirstTimeTooltips, "breadcrumbs": (("Home", reverse("home")), ), })
def clean_obj_permissions(self): new_obj_permissions = self.cleaned_data["obj_permissions"] new_obj_permissions_pks = [p.pk for p in new_obj_permissions] initial_role_pks = self.fields["obj_permissions"].initial if not initial_role_pks: return new_obj_permissions for perm_pk in initial_role_pks: if perm_pk not in new_obj_permissions_pks and\ not has_permission(self.user, self.project, "can_remove_members"): perm = ObjectPermission.objects.get(pk=perm_pk) raise forms.ValidationError( "You tried to remove permission '%s' for target '%s' " "from the role, " "but you do not have permission to remove members " "so you cannot remove permissions from roles either." % (perm.permission.name, perm.target)) return new_obj_permissions
def home(request): isSuperUser = False if(has_permission(request.user, User, "can_manage_users")): isSuperUser = True if request.session.get('visited') == None: showFirstTimeTooltips = True request.session['visited'] = True else: showFirstTimeTooltips = False return direct_to_template( request, template='expedient/clearinghouse/index.html', extra_context={ "isSuperUser": isSuperUser, "showFirstTimeTooltips" : showFirstTimeTooltips, "breadcrumbs": ( ("Home", reverse("home")), ), } )
def test_remove_from_permittee_with_conflict(self): """ Check that a role can be removed from a permittee along with its non-conflicting permissions """ self.role1.give_to_permittee(self.u1) self.role3.give_to_permittee(self.u1) self.assertTrue(has_permission(self.u1, self.project, "perm1")) self.assertTrue(has_permission(self.u1, self.project, "perm3")) self.role1.remove_from_permittee(self.u1) self.assertTrue(has_permission(self.u1, self.project, "perm1")) self.assertTrue(has_permission(self.u1, self.project, "perm3")) self.role1.give_to_permittee(self.u1) self.role3.remove_from_permittee(self.u1) self.assertTrue(has_permission(self.u1, self.project, "perm1")) self.assertFalse(has_permission(self.u1, self.project, "perm3"))