예제 #1
0
def fh_perms_update(layer,filename):
    # anonymous_group, created = Group.objects.get_or_create(name='anonymous')
    #layer_list = Layer.objects.filter(name__icontains='fh')
    #total_layers = len(layer_list)
    #ctr = 1
    #for layer in layer_list:

    try:
        # geoadmin = User.objects.get.filter(username='******')
        # for user in User.objects.all():
        datarequesters = Group.objects.get(name='data-requesters')
        assign_perm('view_resourcebase', datarequesters, layer.get_self_resource())
        assign_perm('download_resourcebase', datarequesters, layer.get_self_resource())
        # superusers=get_user_model().objects.filter(Q(is_superuser=True))
        # for superuser in superusers:
        #     assign_perm('view_resourcebase', superuser, layer.get_self_resource())
        #     assign_perm('download_resourcebase', superuser, layer.get_self_resource())
        assign_perm('view_resourcebase', get_anonymous_user(), layer.get_self_resource())
        assign_perm('download_resourcebase', get_anonymous_user(), layer.get_self_resource())
        #print "[FH PERMISSIONS] {0}/{1} : {2} ".format(ctr,total_layers,layer.name)
        # layer.remove_all_permissions()
        # assign_perm('view_resourcebase', get_anonymous_user(), layer.get_self_resource())
        # assign_perm('download_resourcebase', get_anonymous_user(), layer.get_self_resource())
        #ctr+=1
    except:
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
        Err_msg = st + " Error in updating style of " + layer.name + "\n"
        filename.write(Err_msg)
        pass
예제 #2
0
 def test_new_with_user(self):
     """Create a new Event passing a user as kwarg"""
     event = Event.new("unittest", test={"model": get_anonymous_user()})
     event.save()  # We save to ensure nothing is un-saveable
     self.assertEqual(
         event.context.get("test").get("model").get("username"),
         get_anonymous_user().username,
     )
예제 #3
0
파일: forms.py 프로젝트: kiiproject/kii
    def save(self, *args, **kwargs):
        r = super(PermissionMixinForm, self).save(*args, **kwargs)

        readable_by = self.cleaned_data['readable_by']
        if readable_by == "everybody":
            # create required permission object
            self.instance.assign_perm("read", get_anonymous_user())

        elif readable_by == "owner":
            # Delete anonymous user perm, if any
            self.instance.remove_perm('read', get_anonymous_user())

        return r
예제 #4
0
def fhm_perms_update(layer):
    try:
        # layer.remove_all_permissions()
        anon_group = Group.objects.get(name='anonymous')
        assign_perm('view_resourcebase', anon_group, layer.get_self_resource())
        assign_perm('download_resourcebase', anon_group,
                    layer.get_self_resource())
        assign_perm('view_resourcebase', get_anonymous_user(),
                    layer.get_self_resource())
        assign_perm('download_resourcebase', get_anonymous_user(),
                    layer.get_self_resource())
    except:
        st = str(datetime.now())
        logger.exception(st + " Error in updating style of " + layer.name)
        pass
예제 #5
0
 def test_add_permissions(self):
     """Create blob and check that anonymous user gets view permission assigned"""
     _blob = Blob.objects.create(path='/test', volume=self.volume)
     # Reload from DB so we get the latest data
     blob = Blob.objects.get(pk=_blob.pk)
     self.assertTrue(get_anonymous_user().has_perm('p2_core.view_blob',
                                                   blob))
예제 #6
0
def create_traveler_profile(sender, **kwargs):
    """
    Create traveler profile for and whenever every User instance created.
    Assign the user all the basic permissions for a traveler by adding them
    to traveler group.
    """
    user = kwargs['instance']
    if kwargs['created'] and user != get_anonymous_user():
        profile = TravelerProfile(
            type_of_traveler='Employee',
            nationality='Kenyan',
            contact_telephone='',
            contact_email=user.email,
            user_account=user,
        ).save()
        logger.debug("Created profile for %s", user.username)
        assign_perm("traveler.change_travelerprofile", user, profile)
        logger.debug("Granted %s permission to change own profile",
                     user.username)
        try:
            travelers = Group.objects.get(name='travelers')
            travelers.user_set.add(user)
        except Group.DoesNotExist:
            logger.error("Travelers group doesn't exist. " \
                "Create the group and assign it the proper permissions.")
예제 #7
0
    def test_planner_cache(self):
        """Test planner cache"""
        flow = Flow.objects.create(
            name="test-cache",
            slug="test-cache",
            designation=FlowDesignation.AUTHENTICATION,
        )
        FlowStageBinding.objects.create(
            target=flow, stage=DummyStage.objects.create(name="dummy"), order=0
        )
        request = self.request_factory.get(
            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
        )
        request.user = get_anonymous_user()

        planner = FlowPlanner(flow)
        planner.plan(request)
        self.assertEqual(
            CACHE_MOCK.set.call_count, 1
        )  # Ensure plan is written to cache
        planner = FlowPlanner(flow)
        planner.plan(request)
        self.assertEqual(
            CACHE_MOCK.set.call_count, 1
        )  # Ensure nothing is written to cache
        self.assertEqual(CACHE_MOCK.get.call_count, 2)  # Get is called twice
예제 #8
0
파일: tests.py 프로젝트: ict4eo/geonode
    def test_login_middleware(self):
        """
        Tests the Geonode login required authentication middleware.
        """
        from geonode.security.middleware import LoginRequiredMiddleware
        middleware = LoginRequiredMiddleware()

        white_list = [
            reverse('account_ajax_login'),
            reverse('account_confirm_email', kwargs=dict(key='test')),
            reverse('account_login'),
            reverse('account_password_reset'),
            reverse('forgot_username'),
            reverse('layer_acls'),
            reverse('layer_resolve_user'),
        ]

        black_list = [
            reverse('account_signup'),
            reverse('document_browse'),
            reverse('maps_browse'),
            reverse('layer_browse'),
            reverse('layer_detail', kwargs=dict(layername='geonode:Test')),
            reverse('layer_remove', kwargs=dict(layername='geonode:Test')),
            reverse('profile_browse'),
        ]

        request = HttpRequest()
        request.user = get_anonymous_user()

        # Requests should be redirected to the the `redirected_to` path when un-authenticated user attempts to visit
        # a black-listed url.
        for path in black_list:
            request.path = path
            response = middleware.process_request(request)
            self.assertEqual(response.status_code, 302)
            self.assertTrue(
                response.get('Location').startswith(
                    middleware.redirect_to))

        # The middleware should return None when an un-authenticated user
        # attempts to visit a white-listed url.
        for path in white_list:
            request.path = path
            response = middleware.process_request(request)
            self.assertIsNone(
                response,
                msg="Middleware activated for white listed path: {0}".format(path))

        c = Client()
        c.login(username='******', password='******')
        self.assertTrue(self.admin.is_authenticated())
        request.user = self.admin

        # The middleware should return None when an authenticated user attempts
        # to visit a black-listed url.
        for path in black_list:
            request.path = path
            response = middleware.process_request(request)
            self.assertIsNone(response)
예제 #9
0
 def test_failed_digits(self):
     """not enough digits"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages, ("test message", ))
예제 #10
0
def get_user_geolimits(layer, user, group, gf_services):
    _user = None
    _group = None
    _disable_dataset_cache = None
    users_geolimits = None
    groups_geolimits = None
    anonymous_geolimits = None
    if user:
        _user = user if isinstance(user, str) else user.username
        users_geolimits = layer.users_geolimits.filter(
            user=get_user_model().objects.get(username=_user))
        gf_services["*"] = users_geolimits.count(
        ) > 0 if not gf_services["*"] else gf_services["*"]
        _disable_dataset_cache = users_geolimits.count() > 0

    if group:
        _group = group if isinstance(group, str) else group.name
        if GroupProfile.objects.filter(group__name=_group).count() == 1:
            groups_geolimits = layer.groups_geolimits.filter(
                group=GroupProfile.objects.get(group__name=_group))
            gf_services["*"] = groups_geolimits.count(
            ) > 0 if not gf_services["*"] else gf_services["*"]
            _disable_dataset_cache = groups_geolimits.count() > 0

    if not user and not group:
        anonymous_geolimits = layer.users_geolimits.filter(
            user=get_anonymous_user())
        gf_services["*"] = anonymous_geolimits.count(
        ) > 0 if not gf_services["*"] else gf_services["*"]
        _disable_dataset_cache = anonymous_geolimits.count() > 0
    return _group, _user, _disable_dataset_cache, users_geolimits, groups_geolimits, anonymous_geolimits
예제 #11
0
    def test_webservice_api(self):
        """ Test webservices api """

        # project not exixts
        resp = json.loads(
            self._testApiCall('qdjango-webservice-api-list', [1111]).content)
        self.assertFalse(resp['result'])

        # project exist locked
        resp = json.loads(
            self._testApiCall('qdjango-webservice-api-list',
                              [self.project310.instance.pk]).content)

        self.assertEqual(resp['data']['WMS']['access'], 'locked')
        ows_url = reverse('OWS:ows',
                          args=[
                              self.project310.instance.group.slug, 'qdjango',
                              self.project310.instance.pk
                          ])
        self.assertEqual(resp['data']['WMS']['url'], ows_url)
        self.assertTrue('WFS' in resp['data'])
        self.assertEqual(resp['data']['WFS']['url'], ows_url)

        # project exist free
        assign_perm('view_project', get_anonymous_user(),
                    self.project310.instance)
        # project exist locked
        resp = json.loads(
            self._testApiCall('qdjango-webservice-api-list',
                              [self.project310.instance.pk]).content)
        self.assertEqual(resp['data']['WMS']['access'], 'free')
예제 #12
0
 def setUp(self):
     super(DocumentsTest, self).setUp()
     create_models('map')
     self.imgfile = StringIO.StringIO(
         'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
         '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
     self.anonymous_user = get_anonymous_user()
예제 #13
0
 def dehydrate_is_public(self, bundle):
     anonymous_user = get_anonymous_user()
     public_wfpdocs_ids = get_objects_for_user(
         anonymous_user,
         'base.view_resourcebase').instance_of(WFPDocument).values_list(
             'id', flat=True)
     return bundle.obj.id in public_wfpdocs_ids
예제 #14
0
 def setUp(self):
     create_models(type='layer')
     create_models(type='map')
     create_models(type='document')
     self.norman = get_user_model().objects.get(username="******")
     self.bar = GroupProfile.objects.get(slug='bar')
     self.anonymous_user = get_anonymous_user()
예제 #15
0
    def setUp(self):
        super(SearchApiTests, self).setUp()

        self.list_url = reverse('api_dispatch_list',
                                kwargs={
                                    'api_name': 'api',
                                    'resource_name': 'layers'
                                })
        create_models(type='layer')
        all_public()
        self.norman = get_user_model().objects.get(username="******")
        self.norman.groups.add(Group.objects.get(name='anonymous'))
        self.test_user = get_user_model().objects.get(username='******')
        self.test_user.groups.add(Group.objects.get(name='anonymous'))
        self.bar = GroupProfile.objects.get(slug='bar')
        self.anonymous_user = get_anonymous_user()
        self.profiles_list_url = reverse('api_dispatch_list',
                                         kwargs={
                                             'api_name': 'api',
                                             'resource_name': 'profiles'
                                         })
        self.groups_list_url = reverse('api_dispatch_list',
                                       kwargs={
                                           'api_name': 'api',
                                           'resource_name': 'groups'
                                       })
예제 #16
0
 def test_failed_uppercase(self):
     """not enough uppercase"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages, ("test message", ))
예제 #17
0
 def setUp(self):
     create_models(type='layer')
     create_models(type='map')
     create_models(type='document')
     self.norman = get_user_model().objects.get(username="******")
     self.bar = GroupProfile.objects.get(slug='bar')
     self.anonymous_user = get_anonymous_user()
예제 #18
0
 def test_full(self):
     """Test full with Policy instance"""
     policy = ExpressionPolicy(name="test", expression="return 'test'")
     policy.save()
     request = PolicyRequest(get_anonymous_user())
     result = policy.passes(request)
     self.assertTrue(result.passing)
예제 #19
0
    def test_get_valid_user(self):
        # Verify it accepts an admin user
        adminuser = get_user_model().objects.get(is_superuser=True)
        valid_user = get_valid_user(adminuser)
        msg = ('Passed in a valid admin user "%s" but got "%s" in return' %
               (adminuser, valid_user))
        assert valid_user.id == adminuser.id, msg

        # Verify it returns a valid user after receiving None
        valid_user = get_valid_user(None)
        msg = ('Expected valid user after passing None, got "%s"' % valid_user)
        assert isinstance(valid_user, get_user_model()), msg

        newuser = get_user_model().objects.create(username='******')
        valid_user = get_valid_user(newuser)
        msg = ('Passed in a valid user "%s" but got "%s" in return' %
               (newuser, valid_user))
        assert valid_user.id == newuser.id, msg

        valid_user = get_valid_user('arieluser')
        msg = ('Passed in a valid user by username "%s" but got'
               ' "%s" in return' % ('arieluser', valid_user))
        assert valid_user.username == 'arieluser', msg

        nn = get_anonymous_user()
        self.assertRaises(GeoNodeException, get_valid_user, nn)
예제 #20
0
 def test_invalid(self):
     """Test without password"""
     policy = HaveIBeenPwendPolicy.objects.create(name="test_invalid", )
     request = PolicyRequest(get_anonymous_user())
     result: PolicyResult = policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages[0], "Password not set in context")
예제 #21
0
 def test_token_expire_no_expire(self):
     """Test token expiring with "expiring" set """
     token = Token.objects.create(expires=now(),
                                  user=get_anonymous_user(),
                                  expiring=False)
     sleep(0.5)
     self.assertFalse(token.is_expired)
예제 #22
0
    def setUp(self):
        create_sites()
        super(SiteTests, self).setUp()

        self.user = '******'
        self.passwd = 'admin'
        self.admin = Profile.objects.get(username='******')
        self.bobby = Profile.objects.get(username='******')
        self.master_site = Site.objects.get(name='Master')
        self.slave_site = Site.objects.get(name='Slave')
        self.api_site_url = reverse('api_dispatch_list',
                                    kwargs={
                                        'api_name': 'api',
                                        'resource_name': 'sites'
                                    })
        self.api_slave_detail_url = reverse('api_dispatch_detail',
                                            kwargs={
                                                'api_name': 'api',
                                                'resource_name': 'sites',
                                                'pk': self.slave_site.pk
                                            })
        self.api_layer_url = reverse('api_dispatch_list',
                                     kwargs={
                                         'api_name': 'api',
                                         'resource_name': 'layers'
                                     })

        self.anonymous_user = get_anonymous_user()
        self.slave2_data = {'name': 'Slave2', 'domain': 'slave2.test.org'}
        # all layers belong to slave but let's remove one resource from it (CA)
        SiteResources.objects.get(site=self.slave_site).resources.remove(
            Layer.objects.get(alternate='geonode:CA'))
예제 #23
0
    def test_login_middleware(self):
        """
        Tests the Geonode login required authentication middleware.
        """
        from geonode.security.middleware import LoginRequiredMiddleware
        middleware = LoginRequiredMiddleware()

        white_list = [
            reverse('account_ajax_login'),
            reverse('account_confirm_email', kwargs=dict(key='test')),
            reverse('account_login'),
            reverse('account_password_reset'),
            reverse('forgot_username'),
            reverse('layer_acls'),
            reverse('layer_resolve_user'),
        ]

        black_list = [
            reverse('account_signup'),
            reverse('document_browse'),
            reverse('maps_browse'),
            reverse('layer_browse'),
            reverse('layer_detail', kwargs=dict(layername='geonode:Test')),
            reverse('layer_remove', kwargs=dict(layername='geonode:Test')),
            reverse('profile_browse'),
        ]

        request = HttpRequest()
        request.user = get_anonymous_user()

        # Requests should be redirected to the the `redirected_to` path when un-authenticated user attempts to visit
        # a black-listed url.
        for path in black_list:
            request.path = path
            response = middleware.process_request(request)
            self.assertEqual(response.status_code, 302)
            self.assertTrue(
                response.get('Location').startswith(middleware.redirect_to))

        # The middleware should return None when an un-authenticated user
        # attempts to visit a white-listed url.
        for path in white_list:
            request.path = path
            response = middleware.process_request(request)
            self.assertIsNone(
                response,
                msg="Middleware activated for white listed path: {0}".format(
                    path))

        c = Client()
        c.login(username='******', password='******')
        self.assertTrue(self.admin.is_authenticated())
        request.user = self.admin

        # The middleware should return None when an authenticated user attempts
        # to visit a black-listed url.
        for path in black_list:
            request.path = path
            response = middleware.process_request(request)
            self.assertIsNone(response)
예제 #24
0
    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
        # Check if we have any static or hidden fields, and ensure they
        # still have the same value
        static_hidden_fields: QuerySet[Prompt] = self.stage.fields.filter(
            type__in=[
                FieldTypes.HIDDEN, FieldTypes.STATIC, FieldTypes.TEXT_READ_ONLY
            ])
        for static_hidden in static_hidden_fields:
            field = self.fields[static_hidden.field_key]
            attrs[static_hidden.field_key] = field.default

        # Check if we have two password fields, and make sure they are the same
        password_fields: QuerySet[Prompt] = self.stage.fields.filter(
            type=FieldTypes.PASSWORD)
        if password_fields.exists() and password_fields.count() == 2:
            self._validate_password_fields(
                *[field.field_key for field in password_fields])

        user = self.plan.context.get(PLAN_CONTEXT_PENDING_USER,
                                     get_anonymous_user())
        engine = ListPolicyEngine(self.stage.validation_policies.all(), user,
                                  self.request)
        engine.mode = PolicyEngineMode.MODE_ALL
        engine.request.context[PLAN_CONTEXT_PROMPT] = attrs
        engine.request.context.update(attrs)
        engine.build()
        result = engine.result
        if not result.passing:
            raise ValidationError(list(result.messages))
        return attrs
예제 #25
0
    def test_with_invitation_get(self):
        """Test with invitation, check data in session"""
        plan = FlowPlan(flow_pk=self.flow.pk.hex,
                        stages=[self.stage],
                        markers=[StageMarker()])
        session = self.client.session
        session[SESSION_KEY_PLAN] = plan
        session.save()

        data = {"foo": "bar"}
        invite = Invitation.objects.create(created_by=get_anonymous_user(),
                                           fixed_data=data)

        with patch("authentik.flows.views.FlowExecutorView.cancel",
                   MagicMock()):
            base_url = reverse("authentik_api:flow-executor",
                               kwargs={"flow_slug": self.flow.slug})
            args = urlencode({INVITATION_TOKEN_KEY: invite.pk.hex})
            response = self.client.get(base_url + f"?query={args}")

        session = self.client.session
        plan: FlowPlan = session[SESSION_KEY_PLAN]
        self.assertEqual(plan.context[PLAN_CONTEXT_PROMPT], data)

        self.assertEqual(response.status_code, 200)
        self.assertJSONEqual(
            force_str(response.content),
            {
                "to": reverse("authentik_core:root-redirect"),
                "type": "redirect"
            },
        )
예제 #26
0
 def setUp(self):
     super().setUp()
     create_models('map')
     self.imgfile = io.BytesIO(
         b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
         b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
     self.anonymous_user = get_anonymous_user()
예제 #27
0
파일: tests.py 프로젝트: GavinDu/geonode
    def setUp(self):
        super(SiteTests, self).setUp()
        create_sites()
        create_models(type='layer')

        self.user = '******'
        self.passwd = 'admin'
        self.admin = Profile.objects.get(username='******')
        self.bobby = Profile.objects.get(username='******')
        self.master_site = Site.objects.get(name='Master')
        self.slave_site = Site.objects.get(name='Slave')
        self.api_site_url = reverse('api_dispatch_list',
                                    kwargs={
                                        'api_name': 'api',
                                        'resource_name': 'sites'})
        self.api_slave_detail_url = reverse('api_dispatch_detail',
                                            kwargs={
                                                'api_name': 'api',
                                                'resource_name': 'sites',
                                                'pk': self.slave_site.pk})
        self.api_layer_url = reverse('api_dispatch_list',
                                     kwargs={
                                        'api_name': 'api',
                                        'resource_name': 'layers'})

        self.anonymous_user = get_anonymous_user()
        self.slave2_data = {'name': 'Slave2',
                            'domain': 'slave2.test.org'}
        # all layers belong to slave but let's remove one resource from it (CA)
        SiteResources.objects.get(site=self.slave_site).resources.remove(Layer.objects.get(typename='geonode:CA'))
예제 #28
0
    def test_user_negative(self):
        """Test binding to user"""
        binding = PolicyBinding(user=get_anonymous_user())

        request = PolicyRequest(self.user)
        response = PolicyProcess(binding, request, None).execute()
        self.assertEqual(response.passing, False)
예제 #29
0
 def test_true(self):
     """Positive password case"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = generate_key() + "1ee!!!"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertTrue(result.passing)
     self.assertEqual(result.messages, tuple())
예제 #30
0
    def test_with_invitation_prompt_data(self):
        """Test with invitation, check data in session"""
        data = {"foo": "bar"}
        invite = Invitation.objects.create(
            created_by=get_anonymous_user(), fixed_data=data, single_use=True
        )

        plan = FlowPlan(
            flow_pk=self.flow.pk.hex, stages=[self.stage], markers=[StageMarker()]
        )
        plan.context[PLAN_CONTEXT_PROMPT] = {INVITATION_TOKEN_KEY: invite.pk.hex}
        session = self.client.session
        session[SESSION_KEY_PLAN] = plan
        session.save()

        with patch("authentik.flows.views.FlowExecutorView.cancel", MagicMock()):
            base_url = reverse(
                "authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}
            )
            response = self.client.get(base_url)

        session = self.client.session
        plan: FlowPlan = session[SESSION_KEY_PLAN]
        self.assertEqual(plan.context[PLAN_CONTEXT_PROMPT], data)

        self.assertEqual(response.status_code, 200)
        self.assertJSONEqual(
            force_str(response.content),
            {
                "component": "xak-flow-redirect",
                "to": reverse("authentik_core:root-redirect"),
                "type": ChallengeTypes.REDIRECT.value,
            },
        )
        self.assertFalse(Invitation.objects.filter(pk=invite.pk))
예제 #31
0
 def is_public(self):
     """
     Returns True if anonymous (public) user can view geoapp.
     """
     user = get_anonymous_user()
     return user.has_perm('base.view_resourcebase',
                          obj=self.resourcebase_ptr)
예제 #32
0
 def test_failed_length(self):
     """Password too short"""
     request = PolicyRequest(get_anonymous_user())
     request.context["password"] = "******"  # nosec
     result: PolicyResult = self.policy.passes(request)
     self.assertFalse(result.passing)
     self.assertEqual(result.messages, ("test message", ))
예제 #33
0
    def setUp(self):
        super(LayersTest, self).setUp()

        create_layer_data()
        self.user = '******'
        self.passwd = 'admin'
        self.anonymous_user = get_anonymous_user()
예제 #34
0
파일: tests.py 프로젝트: atenekom/geonode
    def test_get_valid_user(self):
        # Verify it accepts an admin user
        adminuser = get_user_model().objects.get(is_superuser=True)
        valid_user = get_valid_user(adminuser)
        msg = ('Passed in a valid admin user "%s" but got "%s" in return'
               % (adminuser, valid_user))
        assert valid_user.id == adminuser.id, msg

        # Verify it returns a valid user after receiving None
        valid_user = get_valid_user(None)
        msg = ('Expected valid user after passing None, got "%s"' % valid_user)
        assert isinstance(valid_user, get_user_model()), msg

        newuser = get_user_model().objects.create(username='******')
        valid_user = get_valid_user(newuser)
        msg = ('Passed in a valid user "%s" but got "%s" in return'
               % (newuser, valid_user))
        assert valid_user.id == newuser.id, msg

        valid_user = get_valid_user('arieluser')
        msg = ('Passed in a valid user by username "%s" but got'
               ' "%s" in return' % ('arieluser', valid_user))
        assert valid_user.username == 'arieluser', msg

        nn = get_anonymous_user()
        self.assertRaises(GeoNodeException, get_valid_user, nn)
예제 #35
0
 def setUp(self):
     self.user = '******'
     self.passwd = 'admin'
     create_models(type='layer')
     create_layer_data()
     create_notifications()
     self.anonymous_user = get_anonymous_user()
예제 #36
0
파일: tests.py 프로젝트: atenekom/geonode
    def setUp(self):
        super(SearchApiTests, self).setUp()

        self.list_url = reverse(
            'api_dispatch_list',
            kwargs={
                'api_name': 'api',
                'resource_name': 'layers'})
        all_public()
        self.norman = get_user_model().objects.get(username="******")
        self.norman.groups.add(Group.objects.get(name='anonymous'))
        self.test_user = get_user_model().objects.get(username='******')
        self.test_user.groups.add(Group.objects.get(name='anonymous'))
        self.bar = GroupProfile.objects.get(slug='bar')
        self.anonymous_user = get_anonymous_user()
        self.profiles_list_url = reverse(
            'api_dispatch_list',
            kwargs={
                'api_name': 'api',
                'resource_name': 'profiles'})
        self.groups_list_url = reverse(
            'api_dispatch_list',
            kwargs={
                'api_name': 'api',
                'resource_name': 'groups'})
예제 #37
0
파일: tests.py 프로젝트: atenekom/geonode
    def setUp(self):
        super(LayersTest, self).setUp()

        create_layer_data()
        self.user = '******'
        self.passwd = 'admin'
        self.anonymous_user = get_anonymous_user()
예제 #38
0
파일: tests.py 프로젝트: alaw005/geonode
 def setUp(self):
     self.user = '******'
     self.passwd = 'admin'
     create_models(type='layer')
     create_layer_data()
     create_notifications()
     self.anonymous_user = get_anonymous_user()
예제 #39
0
 def test_invalid(self):
     """Test passing event"""
     request = PolicyRequest(get_anonymous_user())
     policy: EventMatcherPolicy = EventMatcherPolicy.objects.create(
         client_ip="1.2.3.4")
     response = policy.passes(request)
     self.assertFalse(response.passing)
예제 #40
0
 def process_request(self, request):
     if not request.user.is_authenticated(
     ) or request.user == get_anonymous_user():
         if not any(path.match(request.path) for path in self.white_list):
             return HttpResponseRedirect(
                 '{login_path}?next={request_path}'.format(
                     login_path=self.redirect_to,
                     request_path=request.path))
예제 #41
0
    def is_public(self):
        """
        Returns True if anonymous (public) user can view map.
        """
        from guardian.shortcuts import get_anonymous_user

        user = get_anonymous_user()
        return user.has_perm("base.view_resourcebase", obj=self.resourcebase_ptr)
예제 #42
0
파일: tests.py 프로젝트: EOSIT/geonode
 def setUp(self):
     from django.contrib.auth.models import Group
     create_models(type='layer')
     create_models(type='map')
     create_models(type='document')
     self.norman = get_user_model().objects.get(username="******")
     self.norman.groups.add(Group.objects.get(name='anonymous'))
     self.bar = GroupProfile.objects.get(slug='bar')
     self.anonymous_user = get_anonymous_user()
예제 #43
0
파일: tests.py 프로젝트: GeoNode/geonode
    def setUp(self):
        super(SmokeTest, self).setUp()

        self.norman = get_user_model().objects.get(username="******")
        self.norman.groups.add(Group.objects.get(name='anonymous'))
        self.test_user = get_user_model().objects.get(username='******')
        self.test_user.groups.add(Group.objects.get(name='anonymous'))
        self.bar = GroupProfile.objects.get(slug='bar')
        self.anonymous_user = get_anonymous_user()
예제 #44
0
파일: tests.py 프로젝트: MapStory/geonode
    def setUp(self):
        super(PermissionsTest, self).setUp()
        if check_ogc_backend(geoserver.BACKEND_PACKAGE):
            settings.OGC_SERVER['default']['GEOFENCE_SECURITY_ENABLED'] = True

        self.user = '******'
        self.passwd = 'admin'
        create_layer_data()
        self.anonymous_user = get_anonymous_user()
예제 #45
0
    def test_group_add_member(self):
        "Test adding a user to a group"

        anon = get_anonymous_user()
        normal = get_user_model().objects.get(username="******")
        group = GroupProfile.objects.get(slug="bar")
        group.join(normal)
        self.assert_(group.user_is_member(normal))
        self.assertRaises(ValueError, lambda: group.join(anon))
예제 #46
0
파일: tests.py 프로젝트: atenekom/geonode
 def test_assign_change_layer_data_perm(self):
     """
     Ensure set_permissions supports the change_layer_data permission.
     """
     layer = Layer.objects.first()
     user = get_anonymous_user()
     layer.set_permissions({'users': {user.username: ['change_layer_data']}})
     perms = layer.get_all_level_info()
     self.assertIn('change_layer_data', perms['users'][user])
예제 #47
0
    def test_group_is_member(self):
        "Test checking group membership"

        anon = get_anonymous_user()
        normal = get_user_model().objects.get(username="******")
        group = GroupProfile.objects.get(slug="bar")

        self.assert_(not group.user_is_member(anon))
        self.assert_(not group.user_is_member(normal))
예제 #48
0
 def setUp(self):
     self.user = '******'
     self.passwd = 'admin'
     create_models(type='document')
     self.anonymous_user = get_anonymous_user()
     self.u = get_user_model().objects.get(username=self.user)
     self.u.email = '*****@*****.**'
     self.u.is_active = True
     self.u.save()
     self.setup_notifications_for(DocumentsAppConfig.NOTIFICATIONS, self.u)
예제 #49
0
파일: tests.py 프로젝트: artists974/geonode
 def setUp(self):
     create_models(type="layer")
     create_models(type="map")
     create_models(type="document")
     self.norman = get_user_model().objects.get(username="******")
     self.norman.groups.add(Group.objects.get(name="anonymous"))
     self.test_user = get_user_model().objects.get(username="******")
     self.test_user.groups.add(Group.objects.get(name="anonymous"))
     self.bar = GroupProfile.objects.get(slug="bar")
     self.anonymous_user = get_anonymous_user()
예제 #50
0
파일: models.py 프로젝트: kiiproject/kii
    def assign_perm(self, permission, target):
        """This method is not a shortcut but adds custom logic to guardian
        `assign`, so you have to use it
        """

        if target.pk == get_anonymous_user().pk:
            # add also permission to all_users_group
            assign(permission, user_models.get_all_users_group(), self)

        return assign(permission, target, self)
예제 #51
0
파일: forms.py 프로젝트: kiiproject/kii
    def __init__(self, *args, **kwargs):

        super(PermissionMixinForm, self).__init__(**kwargs)

        instance = kwargs.get('instance')

        if instance is not None:
            if instance.readable_by(get_anonymous_user()):
                self.fields['readable_by'].initial = "everybody"
            else:
                self.fields['readable_by'].initial = "owner"
예제 #52
0
파일: tests.py 프로젝트: atenekom/geonode
    def setUp(self):
        super(LayerModerationTestCase, self).setUp()

        self.user = '******'
        self.passwd = 'admin'
        create_layer_data()
        self.anonymous_user = get_anonymous_user()
        self.u = get_user_model().objects.get(username=self.user)
        self.u.email = '*****@*****.**'
        self.u.is_active = True
        self.u.save()
예제 #53
0
파일: tests.py 프로젝트: atenekom/geonode
    def setUp(self):
        super(LayerNotificationsTestCase, self).setUp()

        self.user = '******'
        self.passwd = 'admin'
        create_layer_data()
        self.anonymous_user = get_anonymous_user()
        self.u = get_user_model().objects.get(username=self.user)
        self.u.email = '*****@*****.**'
        self.u.is_active = True
        self.u.save()
        self.setup_notifications_for(LayersAppConfig.NOTIFICATIONS, self.u)
예제 #54
0
파일: tests.py 프로젝트: alaw005/geonode
    def setUp(self):
        self.user = '******'
        self.passwd = 'admin'
        create_models(type='layer')
        create_layer_data()
        create_notifications()
        self.anonymous_user = get_anonymous_user()

        self.list_url = reverse(
            'api_dispatch_list',
            kwargs={
                'api_name': 'api',
                'resource_name': 'layers'})
        all_public()
예제 #55
0
    def test_decline_invitation(self):
        "Test declining an invitation"

        anon = get_anonymous_user()
        normal = get_user_model().objects.get(username="******")
        admin = get_user_model().objects.get(username="******")
        group = GroupProfile.objects.get(slug="bar")
        group.invite(normal, admin, role="member", send=False)

        invitation = GroupInvitation.objects.get(user=normal, from_user=admin, group=group)

        self.assertRaises(ValueError, lambda: invitation.decline(anon))
        self.assertRaises(ValueError, lambda: invitation.decline(admin))
        invitation.decline(normal) 

        self.assert_(not group.user_is_member(normal))
        self.assert_(invitation.state == "declined")
예제 #56
0
 def setUp(self):
     #create_models()
     self.user = get_user_model().objects.create(username="******",password="******", is_superuser=True)
     pprint(self.user)
     self.password = '******'
     self.anonymous_user = get_anonymous_user()
     self.item_list = []
 
     r = HttpRequest()
     r.session = {}
     r.user = self.user
     
     cart = CartProxy(r)
     self.cart=cart
     self.cart_model = cart.get_cart(r)
     
     self.request = r
     self._populate_test_data()
예제 #57
0
    def test_invite_user(self):
        "Test inviting a registered user"

        anon = get_anonymous_user()
        normal = get_user_model().objects.get(username="******")
        admin = get_user_model().objects.get(username="******")
        group = GroupProfile.objects.get(slug="bar")
        group.invite(normal, admin, role="member", send=False)

        self.assert_(
            GroupInvitation.objects.filter(user=normal, from_user=admin, group=group).exists()
        )

        invite = GroupInvitation.objects.get(user=normal, from_user=admin, group=group)

        # Test that the user can access the token url.
        c = Client()
        c.login(username="******", password="******")
        response = c.get("/groups/group/{group}/invite/{token}/".format(group=group, token=invite.token))
        self.assertEqual(200, response.status_code)
예제 #58
0
파일: models.py 프로젝트: kiiproject/kii
 def remove_perm(self, permission, target):
     if target.pk == get_anonymous_user().pk:
         # add also remove all_user_group permission
         remove_perm(permission, get_anonymous_user(), self)
         remove_perm(permission, user_models.get_all_users_group(), self)
예제 #59
0
파일: models.py 프로젝트: kiiproject/kii
 def read_permission(self):
     if self.readable_by(get_anonymous_user()):
         return "everybody"
     return "you"