Пример #1
0
def get_or_create_anonymous_user():
    try:
        anon_user = get_anonymous_user()
    except:
        create_anonymous_user(None)
        anon_user = get_anonymous_user()

    return anon_user
Пример #2
0
def add_initial_groups(apps, schema_editor):
	initial_group_names = list(filter(lambda x: 'GROUP_NAME' in x and not 'DEFAULT' in x, dir(settings)))

	for group_name in initial_group_names:
		group, created = Group.objects.get_or_create(name=getattr(settings, group_name))

		if 'ANONYMOUS' in group_name:
			get_anonymous_user().groups.add(group)
		group.save()
Пример #3
0
 def test_fallback_to_anonymous_user(self):
     repo = Repository(owner=self._human_a, name='Node isnt web scale')
     repo.save()
     self.assertTrue(self._human_a.has_perm('read', repo))
     self.assertFalse(self._human_b.has_perm('read', repo))
     assign('read', get_anonymous_user(), repo)
     self.assertTrue(self._human_b.has_perm('read', repo))
Пример #4
0
    def has_permission(self, request, *args, **kwargs):
        """
        Figures out if the current user has permissions for this view.
        """
        self.kwargs = kwargs
        self.args = args
        self.request = request
        
        if not getattr(self, 'permission', None):
            return True
        else:
            # first check our anonymous permissions
            real_anon = get_anonymous_user()
            has_perm = real_anon.has_perm(self.permission)            

            # if not, then check our real permissions
            if not has_perm:
                has_perm = request.user.has_perm(self.permission)

            # if not, perhaps we have it per object
            if not has_perm:
                has_perm = self.has_object_permission('get_object')

            # if still no luck, check if we have permissions on the parent object
            if not has_perm:
                has_perm = self.has_object_permission('get_parent_object')

            return has_perm
Пример #5
0
def reviewer_whitelist(request, project_id=None):
    """ Allows users to retrieve (GET) or update (POST) the set of users whose
    reviews they trust for a given project.
    """
    # Ignore anonymous user
    if request.user == get_anonymous_user() or not request.user.is_authenticated:
        return HttpResponse(json.dumps({'success': "The reviewer whitelist " +
                "of  the anonymous user won't be updated"}),
                content_type='application/json')

    if request.method == 'GET':
        # Retrieve whitelist
        whitelist = ReviewerWhitelist.objects.filter(project_id=project_id,
                user_id=request.user.id).values('reviewer_id', 'accept_after')
        # DjangoJSONEncoder is required to properly encode datetime to ECMA-262
        return HttpResponse(json.dumps(list(whitelist), cls=DjangoJSONEncoder),
                content_type='application/json')

    # Since this is a collections resource replacing all objects, PUT would be
    # correct, but POST is used for consistency with the rest of the API.
    if request.method == 'POST':
        # Update whitelist
        ReviewerWhitelist.objects.filter(
                project_id=project_id, user_id=request.user.id).delete()
        whitelist = [ReviewerWhitelist(
            project_id=project_id, user_id=request.user.id, reviewer_id=int(r),
            accept_after=t) for r,t in six.iteritems(request.POST)]
        ReviewerWhitelist.objects.bulk_create(whitelist)

        return HttpResponse(
                json.dumps({'success': 'Updated review whitelist'}),
                content_type='application/json')
Пример #6
0
	def test_impersonate_as_user(self):
		users = list(UserProfile.objects.all().exclude(username=self.user.username))
		users.append(get_anonymous_user())

		for user in users:
			response = self.app.post('/hijack/{user_id}/'.format(user_id=user.id), user=user)
			self.assertRedirects(response, reverse('admin:login') + '?next=/hijack/{user_id}/'.format(user_id=user.id))
Пример #7
0
    def test_create_permissions_for_anonymous_user(self):
        anonymous_user = get_anonymous_user()

        # check that anonymous user is not allowed to see that document
        response = self.app.get(reverse("information_pages:create"), user=anonymous_user, status=403)
        self.assertEqual(response.status_code, 403)

        # allow anonymous users to see that document and test that
        assign_perm("information_pages.add_informationdocument", anonymous_user)
        assign_perm("information_pages.change_informationdocument", anonymous_user)

        # it should work now
        response = self.app.get(reverse("information_pages:create"), user=anonymous_user)
        self.assertEqual(response.status_code, 200)

        remove_perm("information_pages.add_informationdocument", anonymous_user)
        remove_perm("information_pages.change_informationdocument", anonymous_user)

        # check that anonymous user is not allowed to see page anymore
        response = self.app.get(reverse("information_pages:create"), user=anonymous_user, status=403)
        self.assertEqual(response.status_code, 403)

        # test the same with group
        anonymous_user.groups.add(self.group)
        anonymous_user.save()

        response = self.app.get(reverse("information_pages:create"))
        self.assertEqual(response.status_code, 200)
Пример #8
0
    def post(self, request, format=None):
        """Create a key-value store datastore for the client.

        The request user must not be anonymous and must have browse, annotate
        or administer permissions for at least one project.
        ---
        parameters:
        - name: name
          description: |
            String key for the datastore. This will be used in URLs so may only
            contain alphanumeric characters and hyphens.
          required: true
          type: string
          paramType: form
        serializer: ClientDatastoreSerializer
        """
        if request.user == get_anonymous_user() or not request.user.is_authenticated:
            raise PermissionDenied('Unauthenticated or anonymous users ' \
                                   'can not create datastores.')
        name = request.POST['name']
        if not name:
            raise ValidationError('A name for the datastore must be provided.')

        datastore = ClientDatastore(name=name)
        datastore.full_clean()
        datastore.save()
        serializer = ClientDatastoreSerializer(datastore)
        return Response(serializer.data)
Пример #9
0
    def test_view_permissions_for_anonymous_user(self):
        anonymous_user = get_anonymous_user()
        document = Document.objects.get()

        # check that anonymous user is not allowed to see that document
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user, status=403
        )
        self.assertEqual(response.status_code, 403)

        # allow anonymous users to see that document and test that
        assign_perm(InformationDocument.VIEW_PERMISSION_NAME, anonymous_user, document)

        # it should work now
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user
        )
        self.assertEqual(response.status_code, 200)

        remove_perm(InformationDocument.VIEW_PERMISSION_NAME, anonymous_user, document)

        # check that anonymous user is not allowed to see page anymore
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user, status=403
        )
        self.assertEqual(response.status_code, 403)

        # test the same with group
        anonymous_user.groups.add(self.group)
        anonymous_user.save()

        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user
        )
        self.assertEqual(response.status_code, 200)
Пример #10
0
    def test_can_browse_access(self):
        # Give anonymous user browse permissions for the test project
        anon_user = get_anonymous_user()
        p = Project.objects.get(pk=self.test_project_id)
        assign_perm('can_browse', anon_user, p)
        # Give anonymous user general browse permissions
        permission = Permission.objects.get(codename='can_browse')
        anon_user.user_permissions.add(permission)


        # Make sure we get no permission error on anonymous accessible get
        # methods. Test for all errors, since none of them should occur.
        for api in self.can_browse_get_api:
            msg = "GET %s" % api
            response = self.client.get(api)
            self.assertEqual(response.status_code, 200, msg)
            try:
                parsed_response = json.loads(response.content)
                missing_permissions = ('error' in parsed_response and
                        parsed_response.get('type', None) == 'PermissionError')
                self.assertFalse(missing_permissions, msg)
            except ValueError, e:
                # If a response is no JSON, everything is fine as well
                if str(e) != "No JSON object could be decoded":
                    raise e
Пример #11
0
def get_resources_for_user(user, resource_type):
    return get_objects_for_user(
        user if user.is_authenticated()
        else get_anonymous_user(),
        which_default_read_perm(resource_type),
        accept_global_perms=accept_global_perms(resource_type)
    )
Пример #12
0
	def test_main_page_minutes_document_set(self):
		document = mommy.make(MinutesDocument)
		assign_perm(MinutesDocument.VIEW_PERMISSION_NAME, get_anonymous_user(), document)
		with self.settings(MAIN_PAGE_ID=document.id):
			response = self.app.get(reverse('index')).follow()
			self.assertEqual(response.status_code, 200)
			self.assertTemplateUsed(response, 'documents_base.html')
Пример #13
0
	def test_create_permissions_for_anonymous_user(self):
		anonymous_user = get_anonymous_user()

		# check that anonymous user is not allowed to see that document
		response = self.app.get(reverse('documents:create', args=['informationdocument']), user=anonymous_user, status=403)
		self.assertEqual(response.status_code, 403)

		# allow anonymous users to edit that document and test that
		assign_perm('information_pages.change_informationdocument', anonymous_user)

		# it should still not work
		response = self.app.get(reverse('documents:create', args=['informationdocument']), user=anonymous_user, status=403)
		self.assertEqual(response.status_code, 403)

		# the user also needs to be in a group that allows him to create documents
		anonymous_user.groups.add(self.group)

		# it should work now
		response = self.app.get(reverse('documents:create', args=['informationdocument']), user=anonymous_user)
		self.assertEqual(response.status_code, 200)

		anonymous_user.groups.remove(self.group)
		remove_perm('information_pages.change_informationdocument', anonymous_user)

		# check that anonymous user is not allowed to see page anymore
		response = self.app.get(reverse('documents:create', args=['informationdocument']), user=anonymous_user, status=403)
		self.assertEqual(response.status_code, 403)
Пример #14
0
def document_detail(request, docid):
    """
    The view that show details of each document
    """
    document = get_object_or_404(Document, pk=docid)
    if not request.user.has_perm(
            'view_resourcebase',
            obj=document.get_self_resource()):
        return HttpResponse(
            loader.render_to_string(
                '401.html', RequestContext(
                    request, {
                        'error_message': _("You are not allowed to view this document.")})), status=403)
    try:
        related = document.content_type.get_object_for_this_type(
            id=document.object_id)
    except:
        related = ''

    document.popular_count += 1
    document.save()
    all_perms=ast.literal_eval(_perms_info_json(document))
    user = request.user.username if request.user.is_authenticated() else get_anonymous_user().username
    perms_dict=all_perms['users'][user]
    return render_to_response(
        "documents/document_detail.html",
        RequestContext(
            request,
            {
                'permissions_json': _perms_info_json(document),
                'resource': document,
                'imgtypes': IMGTYPES,
                'related': related,
                'perms_dict': perms_dict}))
Пример #15
0
    def test_project_list(self):
        # Check that, pre-authentication, we can see none of the
        # projects:
        response = self.client.get('/projects/')
        self.assertEqual(response.status_code, 200)
        result = json.loads(response.content)
        self.assertEqual(len(result), 0)

        # Add permission to the anonymous user to browse two projects
        anon_user = get_anonymous_user()
        p = Project.objects.get(pk=self.test_project_id)
        assign_perm('can_browse', anon_user, p)

        # Check that, pre-authentication, we can see two of the
        # projects:
        response = self.client.get('/projects/')
        self.assertEqual(response.status_code, 200)
        result = json.loads(response.content)
        self.assertEqual(len(result), 1)

        # Check stacks:
        stacks = result[0]['stacks']
        self.assertEqual(len(stacks), 1)

        # Check stacks groups
        stackgroups = result[0]['stackgroups']
        self.assertEqual(len(stackgroups), 0)

        # Now log in and check that we see a different set of projects:
        self.fake_authentication()

        # Add permission to the test  user to browse three projects
        test_user = User.objects.get(pk=self.test_user_id)
        for pid in (1,2,3,5):
            p = Project.objects.get(pk=pid)
            assign_perm('can_browse', test_user, p)

        # We expect four projects, one of them (project 2) is empty.
        response = self.client.get('/projects/')
        self.assertEqual(response.status_code, 200)
        result = json.loads(response.content)
        self.assertEqual(len(result), 4)

        def get_project(result, pid):
            rl = [r for r in result if r['id'] == pid]
            if len(rl) != 1:
                raise ValueError("Malformed result")
            return rl[0]

        # Check the first project:
        stacks = get_project(result, 1)['stacks']
        self.assertEqual(len(stacks), 1)

        # Check the second project:
        stacks = get_project(result, 3)['stacks']
        self.assertEqual(len(stacks), 1)

        # Check the third project:
        stacks = get_project(result, 5)['stacks']
        self.assertEqual(len(stacks), 2)
Пример #16
0
def granular_perms_detail(request, contenttype_id, object_id):
	if not request.user.is_staff:
		raise Http404

	content_type = get_object_or_404(ContentType, pk=contenttype_id)
	model = content_type.model_class()

	try:
		obj = content_type.get_object_for_this_type(pk=object_id)
	except model.DoesNotExist():
		raise Http404

	if not isinstance(obj, GranularPermissionedModel):
		raise Http404

	actors = list(Group.objects.all())
	anonymous = get_anonymous_user()
	# adding anonymous user
	actors.append(anonymous)
	# adding users with custom permissions
	# (excluding anonymous user from this qs)
	actors += list(get_users_with_perms(obj,
		with_group_users=False).exclude(pk=anonymous.id))

	return TemplateResponse(request, 'core/perms/granular_detail.html', {
		'model': model,
		'perms_to_check': model._meta.permissions,
		'actors': actors,
		'object': obj,
		'obj_ct_id': contenttype_id,
	})
Пример #17
0
	def test_anonymous_fallback_if_user_has_no_permissions(self):
		anonymous_user = get_anonymous_user()
		anonymous_groups = anonymous_user.groups.all()
		for group in anonymous_groups:
			assign_perm(self.document.view_permission_name, group, self.document)

		response = self.app.get(reverse(self.document.get_view_url_name(), args=[self.document.url_title]), user=self.user)
		self.assertEqual(response.status_code, 200)
Пример #18
0
	def test_impersonate_any_user(self):
		users = list(UserProfile.objects.all().exclude(username=self.user.username))
		users.append(get_anonymous_user())

		for user in users:
			response = self.app.post('/hijack/{user_id}/'.format(user_id=user.id), user=self.user)
			self.assertRedirects(response, reverse('index'))
			response = response.follow()
			self.assertEqual(response.status_code, 200)

			self.assertIn("{username}".format(username=user.get_full_name()), response.body.decode('utf-8'))
Пример #19
0
def check_all_anon_permissions(sender, **kwargs):
    """
    Checks that all our anonymous permissions have been granted
    """
    if not is_last_model(kwargs):
        return

    permissions = getattr(settings, 'ANONYMOUS_PERMISSIONS', [])
    anon_user = get_anonymous_user()

    check_role_permissions(anon_user, permissions, anon_user.get_all_permissions())
Пример #20
0
def access_check(user):
    """ Returns true if users are logged in or if they have the general
    can_browse permission assigned (i.e. not with respect to a certain object).
    This is used to also allow the not logged in anonymous user to retrieve
    data if it is granted the 'can_browse' permission.
    """
    if user.is_authenticated:
        if user == get_anonymous_user():
            return user.has_perm('catmaid.can_browse')
        else:
            return True
    return False
Пример #21
0
def forums_index(request):
	if request.user.is_authenticated():
		user = request.user
	else:
		user = get_anonymous_user()
	categories = get_objects_for_user(user, 'forums.view_category')
	categories = categories.filter(parent__isnull=True).select_related()
	# FIXME currently all subcategories will be shown
	#       if an user has access to root category
	return TemplateResponse(request, 'forums/index.html', {
		'categories': categories,
	})
Пример #22
0
    def test_reserve_correct_devices(self):
        response = self.app.get(reverse('reserve'), user=self.user)
        response_text = response.body.decode('utf-8')
        for device in self.devices[:-1]:
            self.assertIn(device.name, response_text)
        self.assertNotIn(self.devices[-1].name, response_text)

        response = self.app.get(reverse('reserve'), user=self.staff_user)
        for device in self.devices:
            self.assertIn(device.name, response.body.decode('utf-8'))

        response = self.app.get(reverse("reserve"), user=get_anonymous_user())
        for device in self.devices:
            self.assertNotIn(device.name, response.body.decode('utf-8'))
Пример #23
0
    def setUp(self):
        self.user_model = django.contrib.auth.get_user_model()
        super(UserTestCase, self).setUp()
        
        self.users = {
            0: self.user_model(username="******"),
            1: self.user_model(username="******"),
            2: self.user_model(username="******"),
        }
        for key, user in self.users.items():
            user.set_password('test')
            user.save()

        self.all_users_group = Group.objects.get(name=settings.ALL_USERS_GROUP)
        self.anonymous_user = get_anonymous_user()
Пример #24
0
def reviewer_whitelist(request, project_id=None):
    """This is currently only a stub.
    """
    # Ignore anonymous user
    if request.user == get_anonymous_user() or not request.user.is_authenticated:
        return JsonResponse({
            'success': "The reviewer whitelist of the anonymous user won't be updated"
        })

    if request.method == 'GET':
        return JsonResponse([], safe=False)
    else:
        return JsonResponse({
            'success': 'Updating the review whitelist is not ' +
                       'supported for Janelia Render stacks at this time'
        })
Пример #25
0
def reviewer_whitelist(request, project_id=None):
    """This is currently only a stub.
    """
    # Ignore anonymous user
    if request.user == get_anonymous_user() or not request.user.is_authenticated():
        return HttpResponse(json.dumps({'success': "The reviewer whitelist " +
                "of  the anonymous user won't be updated"}),
                content_type='application/json')

    if request.method == 'GET':
        return HttpResponse(json.dumps([]), content_type='application/json')
    else:
        return HttpResponse(
                json.dumps({'success': 'Updating the review whitelist is not ' +
                            'supported for FlyTEM stacks at this time'}),
                content_type='application/json')
Пример #26
0
def view_information(request, title):
	document = get_object_or_error(InformationDocument, request.user, [InformationDocument.get_view_permission()], url_title=title)

	md = markdown.Markdown(safe_mode='escape', extensions=[TocExtension(baselevel=2)])
	text = md.convert(document.text)

	anonymous_rights = get_anonymous_user().has_perm(InformationDocument.VIEW_PERMISSION_NAME, document)
	edit_rights = request.user.has_perm("change_informationdocument", document)
	permission_warning = edit_rights and not anonymous_rights

	return render(request, 'information_pages_base.html', {
		'document': document,
		'text': text,
		'toc': md.toc,
		'attachments': document.attachments.all().order_by('index'),
		'active_page': 'view',
		'permission_warning' : permission_warning,
	})
Пример #27
0
def perms_detail(request, contenttype_id):
	if not request.user.is_staff:
		raise Http404

	content_type = get_object_or_404(ContentType, pk=contenttype_id)
	model = content_type.model_class()
	if not issubclass(model, PermissionedModel):
		raise Http404

	actors = list(Group.objects.all())
	anonymous = get_anonymous_user()
	# adding anonymous user
	actors.append(anonymous)

	return TemplateResponse(request, 'core/perms/detail.html', {
		'perms_to_check': get_perms_for_model(model),
		'actors': actors,
		'model': model,
	})
 def handle(self, *args, **options):
     update_anon_user = options['update-anon-user']
     anon_user = get_anonymous_user()
     for u in User.objects.all():
         # Ignore the anonymous user by default
         if u == anon_user and not update_anon_user:
             continue
         up = u.userprofile
         # Expect user profiles to be there and add all default settings
         up.independent_ontology_workspace_is_default = \
             settings.PROFILE_INDEPENDENT_ONTOLOGY_WORKSPACE_IS_DEFAULT
         up.show_text_label_tool = settings.PROFILE_SHOW_TEXT_LABEL_TOOL
         up.show_tagging_tool = settings.PROFILE_SHOW_TAGGING_TOOL
         up.show_cropping_tool = settings.PROFILE_SHOW_CROPPING_TOOL
         up.show_segmentation_tool = settings.PROFILE_SHOW_SEGMENTATION_TOOL
         up.show_tracing_tool = settings.PROFILE_SHOW_TRACING_TOOL
         up.show_ontology_tool = settings.PROFILE_SHOW_ONTOLOGY_TOOL
         # Save the changes
         up.save()
Пример #29
0
    def filter_permissions(self, search):
        """Filter given query based on permissions of the user in the request.

        :param search: ElasticSearch query object

        """
        user = self.request.user
        if user.is_superuser:
            return search
        if user.is_anonymous:
            user = get_anonymous_user()

        filters = [Q('match', users_with_permissions=user.pk)]
        filters.extend([
            Q('match', groups_with_permissions=group.pk) for group in user.groups.all()
        ])
        filters.append(Q('match', public_permission=True))

        # `minimum_should_match` is set to 1 by default
        return search.query('bool', should=filters)
Пример #30
0
def autosave(request, title):
	if request.user.is_anonymous or request.user == get_anonymous_user():
		raise PermissionDenied()

	document = None
	try:
		document = get_object_or_404(Document, url_title=title)
		if document.has_perms():
			check_permissions(document, request.user, [document.edit_permission_name])
	except Document.DoesNotExist:
		pass

	handle_autosave(request, document)

	data = {
		'preview_url': request.build_absolute_uri(
			reverse('documents:preview') + '?hash_value=' + document.hash_value
		)
	}

	return HttpResponse(json.dumps(data))
Пример #31
0
def new_map_config(request):
    '''
    View that creates a new map.

    If the query argument 'copy' is given, the initial map is
    a copy of the map with the id specified, otherwise the
    default map configuration is used.  If copy is specified
    and the map specified does not exist a 404 is returned.
    '''
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request)

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        access_token = None

    if request.method == 'GET' and 'copy' in request.GET:
        mapid = request.GET['copy']
        map_obj = _resolve_map(request, mapid, 'base.view_resourcebase')

        map_obj.abstract = DEFAULT_ABSTRACT
        map_obj.title = DEFAULT_TITLE
        if request.user.is_authenticated():
            map_obj.owner = request.user

        config = map_obj.viewer_json(request.user, access_token)
        map_obj.handle_moderated_uploads()
        del config['id']
    else:
        if request.method == 'GET':
            params = request.GET
        elif request.method == 'POST':
            params = request.POST
        else:
            return HttpResponse(status=405)

        if 'layer' in params:
            bbox = None
            map_obj = Map(
                projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

            if request.user.is_authenticated():
                map_obj.owner = request.user
            else:
                map_obj.owner = get_anonymous_user()

            layers = []
            for layer_name in params.getlist('layer'):
                try:
                    layer = _resolve_layer(request, layer_name)
                except ObjectDoesNotExist:
                    # bad layer, skip
                    continue

                if not request.user.has_perm('view_resourcebase',
                                             obj=layer.get_self_resource()):
                    # invisible layer, skip inclusion
                    continue

                layer_bbox = layer.bbox
                # assert False, str(layer_bbox)
                if bbox is None:
                    bbox = list(layer_bbox[0:4])
                else:
                    bbox[0] = min(bbox[0], layer_bbox[0])
                    bbox[1] = max(bbox[1], layer_bbox[1])
                    bbox[2] = min(bbox[2], layer_bbox[2])
                    bbox[3] = max(bbox[3], layer_bbox[3])

                config = layer.attribute_config()

                # Add required parameters for GXP lazy-loading
                config["title"] = layer.title
                config["queryable"] = True

                config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS',
                                        'EPSG:900913')
                config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
                    else llbbox_to_mercator([float(coord) for coord in bbox])

                if layer.storeType == "remoteStore":
                    service = layer.service
                    # Probably not a good idea to send the access token to every remote service.
                    # This should never match, so no access token should be sent to remote services.
                    ogc_server_url = urlparse.urlsplit(
                        ogc_server_settings.PUBLIC_LOCATION).netloc
                    service_url = urlparse.urlsplit(service.base_url).netloc

                    if access_token and ogc_server_url == service_url and 'access_token' not in service.base_url:
                        url = service.base_url + '?access_token=' + access_token
                    else:
                        url = service.base_url
                    maplayer = MapLayer(map=map_obj,
                                        name=layer.typename,
                                        ows_url=layer.ows_url,
                                        layer_params=json.dumps(config),
                                        visibility=True,
                                        source_params=json.dumps({
                                            "ptype":
                                            service.ptype,
                                            "remote":
                                            True,
                                            "url":
                                            url,
                                            "name":
                                            service.name
                                        }))
                else:
                    ogc_server_url = urlparse.urlsplit(
                        ogc_server_settings.PUBLIC_LOCATION).netloc
                    layer_url = urlparse.urlsplit(layer.ows_url).netloc

                    if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url:
                        url = layer.ows_url + '?access_token=' + access_token
                    else:
                        url = layer.ows_url
                    maplayer = MapLayer(
                        map=map_obj,
                        name=layer.typename,
                        ows_url=url,
                        # use DjangoJSONEncoder to handle Decimal values
                        layer_params=json.dumps(config, cls=DjangoJSONEncoder),
                        visibility=True)

                layers.append(maplayer)

            if bbox is not None:
                minx, maxx, miny, maxy = [float(coord) for coord in bbox]
                x = (minx + maxx) / 2
                y = (miny + maxy) / 2

                if getattr(settings, 'DEFAULT_MAP_CRS',
                           'EPSG:900913') == "EPSG:4326":
                    center = list((x, y))
                else:
                    center = list(forward_mercator((x, y)))

                if center[1] == float('-inf'):
                    center[1] = 0

                BBOX_DIFFERENCE_THRESHOLD = 1e-5

                # Check if the bbox is invalid
                valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD
                valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD

                if valid_x:
                    width_zoom = math.log(360 / abs(maxx - minx), 2)
                else:
                    width_zoom = 15

                if valid_y:
                    height_zoom = math.log(360 / abs(maxy - miny), 2)
                else:
                    height_zoom = 15

                map_obj.center_x = center[0]
                map_obj.center_y = center[1]
                map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

            map_obj.handle_moderated_uploads()
            config = map_obj.viewer_json(request.user, access_token,
                                         *(DEFAULT_BASE_LAYERS + layers))
            config['fromLayer'] = True
        else:
            config = DEFAULT_MAP_CONFIG
    return json.dumps(config)
Пример #32
0
 def clean_authors(self):
     authors = self.cleaned_data["authors"]
     if get_anonymous_user() in authors:
         raise ValidationError("You cannot add this user!")
     return authors
Пример #33
0
    def post(self, request: Request, project_id) -> Response:
        """Create a deep-link.

        The request user must not be anonymous and must have annotate
        permissions.
        ---
        serializer: DeepLinkSerializer
        """
        if request.user == get_anonymous_user(
        ) or not request.user.is_authenticated:
            raise PermissionError('Unauthenticated or anonymous users ' \
                                   'can not create persistent deep links.')

        project_id = int(project_id)

        alias = request.POST.get('alias')
        if alias:
            if not re.match(r'^[a-zA-Z0-9-_\.]+$', alias):
                raise ValueError(
                    "Only alphanumeric characters, '-', '_' and '.' allowed")
        else:
            n_links = DeepLink.objects.filter(project_id=project_id).count()
            alias = make_unique_id()

        params = {
            'project_id': project_id,
            'user': request.user,
            'alias': alias,
        }

        if 'is_public' in request.POST:
            params['is_public'] = get_request_bool(request.POST, 'is_public')

        if 'is_exportable' in request.POST:
            params['is_exportable'] = get_request_bool(request.POST,
                                                       'is_exportable')

        if 'location_x' in request.POST:
            params['location_x'] = float(request.POST['location_x'])

        if 'location_y' in request.POST:
            params['location_y'] = float(request.POST['location_y'])

        if 'location_z' in request.POST:
            params['location_z'] = float(request.POST['location_z'])

        if 'active_treenode_id' in request.POST:
            params['active_treenode_id'] = int(
                request.POST['active_treenode_id'])

        if 'active_connector_id' in request.POST:
            params['active_connector_id'] = int(
                request.POST['active_connector_id'])

        if 'active_skeleton_id' in request.POST:
            params['active_skeleton_id'] = int(
                request.POST['active_skeleton_id'])

        if 'closest_node_to_location' in request.POST:
            params['closest_node_to_location'] = get_request_bool(
                request.POST, 'closest_node_to_location')

        if 'follow_id_history' in request.POST:
            params['follow_id_history'] = get_request_bool(
                request.POST, 'follow_id_history')

        if 'layered_stacks' in request.POST:
            params['layered_stacks'] = get_request_bool(
                request.POST, 'layered_stacks')

        if 'layout' in request.POST:
            params['layout'] = request.POST['layout']

        if 'tool' in request.POST:
            params['tool'] = request.POST['tool']

        if 'show_help' in request.POST:
            params['show_help'] = get_request_bool(request.POST, 'show_help')

        if 'password' in request.POST:
            params['password'] = make_password(request.POST('password'))

        if 'message' in request.POST:
            params['message'] = request.POST['message']

        # TBA: data_view

        deeplink = DeepLink(**params)
        deeplink.save()
        serializer = DeepLinkSerializer(deeplink)

        # Stacks
        stacks = get_request_list(request.POST, 'stacks', map_fn=float)
        if stacks:
            # Nested lists of 2-tuples: [[stack_id, scale_level]]
            for s in stacks:
                stack_link = DeepLinkStack(
                    **{
                        'project_id': project_id,
                        'user_id': request.user.id,
                        'deep_link': deeplink,
                        'stack_id': int(s[0]),
                        'zoom_level': s[1],
                    })
                stack_link.save()

        # Stack groups
        if 'stack_group' in request.POST:
            sg_id = int(request.POST['stack_group'])
            sg_zoom_levels = get_request_list(request.POST,
                                              'stack_group_scale_levels',
                                              map_fn=float)
            sg_link = DeepLinkStackGroup(
                **{
                    'project_id': project_id,
                    'user_id': request.user.id,
                    'deeplink': deeplink,
                    'stack_group_id': sg_id,
                    'zoom_levels': sg_zoom_levels,
                })
            sg_link.save()

        return Response(serializer.data)
Пример #34
0
 def test(self):
     anon = get_anonymous_user()
     self.assertTrue(isinstance(anon, User))
Пример #35
0
    def test_project_list(self):
        # Check that, pre-authentication, we can see none of the
        # projects:
        response = self.client.get('/projects/')
        self.assertEqual(response.status_code, 200)
        result = json.loads(response.content.decode('utf-8'))
        self.assertEqual(len(result), 0)

        # Add permission to the anonymous user to browse two projects
        anon_user = get_anonymous_user()
        p = Project.objects.get(pk=self.test_project_id)
        assign_perm('can_browse', anon_user, p)

        # Check that, pre-authentication, we can see two of the
        # projects:
        response = self.client.get('/projects/')
        self.assertEqual(response.status_code, 200)
        result = json.loads(response.content.decode('utf-8'))
        self.assertEqual(len(result), 1)

        # Check stacks:
        stacks = result[0]['stacks']
        self.assertEqual(len(stacks), 1)

        # Check stacks groups
        stackgroups = result[0]['stackgroups']
        self.assertEqual(len(stackgroups), 0)

        # Now log in and check that we see a different set of projects:
        self.fake_authentication()

        # Add permission to the test  user to browse three projects
        test_user = User.objects.get(pk=self.test_user_id)
        for pid in (1, 2, 3, 5):
            p = Project.objects.get(pk=pid)
            assign_perm('can_browse', test_user, p)

        # We expect four projects, one of them (project 2) is empty.
        response = self.client.get('/projects/')
        self.assertEqual(response.status_code, 200)
        result = json.loads(response.content.decode('utf-8'))
        self.assertEqual(len(result), 4)

        def get_project(result, pid):
            rl = [r for r in result if r['id'] == pid]
            if len(rl) != 1:
                raise ValueError("Malformed result")
            return rl[0]

        # Check the first project:
        p1 = get_project(result, 1)
        self.assertEqual(len(p1['stacks']), 1)
        self.assertEqual(len(p1['stackgroups']), 0)

        # Check the second project
        p3 = get_project(result, 3)
        self.assertEqual(len(p3['stacks']), 1)
        self.assertEqual(len(p3['stackgroups']), 0)

        # Check the third project:
        p5 = get_project(result, 5)
        self.assertEqual(len(p5['stacks']), 2)
        self.assertEqual(len(p5['stackgroups']), 1)
Пример #36
0
def get_objects_for_user(user,
                         perms,
                         klass=None,
                         use_groups=True,
                         any_perm=False,
                         with_superuser=True,
                         accept_global_perms=True):
    """
    Returns queryset of objects for which a given ``user`` has *all*
    permissions present at ``perms``.

    :param user: ``User`` or ``AnonymousUser`` instance for which objects would
      be returned.
    :param perms: single permission string, or sequence of permission strings
      which should be checked.
      If ``klass`` parameter is not given, those should be full permission
      names rather than only codenames (i.e. ``auth.change_user``). If more than
      one permission is present within sequence, their content type **must** be
      the same or ``MixedContentTypeError`` exception would be raised.
    :param klass: may be a Model, Manager or QuerySet object. If not given
      this parameter would be computed based on given ``params``.
    :param use_groups: if ``False``, wouldn't check user's groups object
      permissions. Default is ``True``.
    :param any_perm: if True, any of permission in sequence is accepted. Default is ``False``.
    :param with_superuser: if ``True`` and if ``user.is_superuser`` is set,
      returns the entire queryset. Otherwise will only return objects the user
      has explicit permissions. This must be ``True`` for the accept_global_perms
      parameter to have any affect. Default is ``True``.
    :param accept_global_perms: if ``True`` takes global permissions into account.
      Object based permissions are taken into account if more than one permission is handed in in perms and at least
      one of these perms is not globally set. If any_perm is set to false then the intersection of matching object
      is returned. Note, that if with_superuser is False, accept_global_perms will be ignored, which means that only
      object permissions will be checked! Default is ``True``.

    :raises MixedContentTypeError: when computed content type for ``perms``
      and/or ``klass`` clashes.
    :raises WrongAppError: if cannot compute app label for given ``perms``/
      ``klass``.

    Example::

        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import get_objects_for_user
        >>> joe = User.objects.get(username='******')
        >>> get_objects_for_user(joe, 'auth.change_group')
        []
        >>> from guardian.shortcuts import assign_perm
        >>> group = Group.objects.create('some group')
        >>> assign_perm('auth.change_group', joe, group)
        >>> get_objects_for_user(joe, 'auth.change_group')
        [<Group some group>]


    The permission string can also be an iterable. Continuing with the previous example:

        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        []
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
        [<Group some group>]
        >>> assign_perm('auth.delete_group', joe, group)
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        [<Group some group>]

    Take global permissions into account:

        >>> jack = User.objects.get(username='******')
        >>> assign_perm('auth.change_group', jack) # this will set a global permission
        >>> get_objects_for_user(jack, 'auth.change_group')
        [<Group some group>]
        >>> group2 = Group.objects.create('other group')
        >>> assign_perm('auth.delete_group', jack, group2)
        >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group']) # this retrieves intersection
        [<Group other group>]
        >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group'], any_perm) # this retrieves union
        [<Group some group>, <Group other group>]

    If accept_global_perms is set to ``True``, then all assigned global
    permissions will also be taken into account.

    - Scenario 1: a user has view permissions generally defined on the model
      'books' but no object based permission on a single book instance:

        - If accept_global_perms is ``True``: List of all books will be
          returned.
        - If accept_global_perms is ``False``: list will be empty.

    - Scenario 2: a user has view permissions generally defined on the model
      'books' and also has an object based permission to view book 'Whatever':

        - If accept_global_perms is ``True``: List of all books will be
          returned.
        - If accept_global_perms is ``False``: list will only contain book
          'Whatever'.

    - Scenario 3: a user only has object based permission on book 'Whatever':

        - If accept_global_perms is ``True``: List will only contain book
          'Whatever'.
        - If accept_global_perms is ``False``: List will only contain book
          'Whatever'.

    - Scenario 4: a user does not have any permission:

        - If accept_global_perms is ``True``: Empty list.
        - If accept_global_perms is ``False``: Empty list.
    """
    if isinstance(perms, str):
        perms = [perms]
    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError("Given perms must have same app "
                                            "label (%s != %s)" %
                                            (app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)
        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                                                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError("ContentType was once computed "
                                            "to be %s and another one %s" %
                                            (ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = get_content_type(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    elif klass is None:
        raise WrongAppError("Cannot determine content type")
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model:
            raise MixedContentTypeError("Content type for given perms and "
                                        "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have ``codenames`` list

    # First check if user is superuser and if so, return queryset immediately
    if with_superuser and user.is_superuser:
        return queryset

    # Check if the user is anonymous. The
    # django.contrib.auth.models.AnonymousUser object doesn't work for queries
    # and it's nice to be able to pass in request.user blindly.
    if user.is_anonymous:
        user = get_anonymous_user()

    global_perms = set()
    has_global_perms = False
    # a superuser has by default assigned global perms for any
    if accept_global_perms and with_superuser:
        for code in codenames:
            if user.has_perm(ctype.app_label + '.' + code):
                global_perms.add(code)
        for code in global_perms:
            codenames.remove(code)
        # prerequisite: there must be elements in global_perms otherwise just follow the procedure for
        # object based permissions only AND
        # 1. codenames is empty, which means that permissions are ONLY set globally, therefore return the full queryset.
        # OR
        # 2. any_perm is True, then the global permission beats the object based permission anyway,
        # therefore return full queryset
        if len(global_perms) > 0 and (len(codenames) == 0 or any_perm):
            return queryset
        # if we have global perms and still some object based perms differing from global perms and any_perm is set
        # to false, then we have to flag that global perms exist in order to merge object based permissions by user
        # and by group correctly. Scenario: global perm change_xx and object based perm delete_xx on object A for user,
        # and object based permission delete_xx  on object B for group, to which user is assigned.
        # get_objects_for_user(user, [change_xx, delete_xx], use_groups=True, any_perm=False, accept_global_perms=True)
        # must retrieve object A and B.
        elif len(global_perms) > 0 and (len(codenames) > 0):
            has_global_perms = True

    # Now we should extract list of pk values for which we would filter
    # queryset
    user_model = get_user_obj_perms_model(queryset.model)
    user_obj_perms_queryset = (user_model.objects.filter(user=user).filter(
        permission__content_type=ctype))
    if len(codenames):
        user_obj_perms_queryset = user_obj_perms_queryset.filter(
            permission__codename__in=codenames)
    direct_fields = ['content_object__pk', 'permission__codename']
    generic_fields = ['object_pk', 'permission__codename']
    if user_model.objects.is_generic():
        user_fields = generic_fields
    else:
        user_fields = direct_fields

    if use_groups:
        group_model = get_group_obj_perms_model(queryset.model)
        group_filters = {
            'permission__content_type': ctype,
            'group__%s' % get_user_model().groups.field.related_query_name():
            user,
        }
        if len(codenames):
            group_filters.update({
                'permission__codename__in': codenames,
            })
        groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
        if group_model.objects.is_generic():
            group_fields = generic_fields
        else:
            group_fields = direct_fields
        if not any_perm and len(codenames) > 1 and not has_global_perms:
            user_obj_perms = user_obj_perms_queryset.values_list(*user_fields)
            groups_obj_perms = groups_obj_perms_queryset.values_list(
                *group_fields)
            data = list(user_obj_perms) + list(groups_obj_perms)
            # sorting/grouping by pk (first in result tuple)
            keyfunc = lambda t: t[0]
            data = sorted(data, key=keyfunc)
            pk_list = []
            for pk, group in groupby(data, keyfunc):
                obj_codenames = {e[1] for e in group}
                if codenames.issubset(obj_codenames):
                    pk_list.append(pk)
            objects = queryset.filter(pk__in=pk_list)
            return objects

    if not any_perm and len(codenames) > 1:
        counts = user_obj_perms_queryset.values(
            user_fields[0]).annotate(object_pk_count=Count(user_fields[0]))
        user_obj_perms_queryset = counts.filter(
            object_pk_count__gte=len(codenames))

    field_pk = user_fields[0]
    values = user_obj_perms_queryset

    handle_pk_field = _handle_pk_field(queryset)
    if handle_pk_field is not None:
        values = values.annotate(obj_pk=handle_pk_field(expression=field_pk))
        field_pk = 'obj_pk'

    values = values.values_list(field_pk, flat=True)
    q = Q(pk__in=values)
    if use_groups:
        field_pk = group_fields[0]
        values = groups_obj_perms_queryset
        if handle_pk_field is not None:
            values = values.annotate(obj_pk=handle_pk_field(
                expression=field_pk))
            field_pk = 'obj_pk'
        values = values.values_list(field_pk, flat=True)
        q |= Q(pk__in=values)

    return queryset.filter(q)
Пример #37
0
 def get_queryset(self):
     user = self.request.user if self.request else get_anonymous_user()
     return StaticDevice.objects.filter(user=user.pk)
Пример #38
0
def logout_user(request:HttpRequest) -> JsonResponse:
    logout(request)
    # Return profile context of anonymous user
    anon_user = get_anonymous_user()
    return user_context_response(anon_user)