Beispiel #1
0
    def test_api_search_languages(self):
        """Test API search languages."""
        self.app.is_mozilla_app = True
        self.app.is_active = True
        self.app.save()
        url = reverse('api_dispatch_list', kwargs={'api_name': 'v1',
                                                   'resource_name': 'users'})

        new_url = urlparams(
            url, app_name=self.app.name, app_key=self.app.key,
            languages=self.auto_user.userprofile.languages.all()[0])
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEqual(data['meta']['total_count'], 1)

        # Search nonexistent term
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key,
                            languages='random')
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEqual(data['meta']['total_count'], 0)
Beispiel #2
0
    def test_api_search_name(self):
        """Test API search name."""
        self.app.is_mozilla_app = True
        self.app.is_active = True
        self.app.save()
        url = reverse('api_dispatch_list', kwargs={'api_name': 'v1',
                                                   'resource_name': 'users'})

        # Search name using
        for name in [self.auto_user.userprofile.full_name,
                     self.auto_user.userprofile.full_name.split(' ')[0],
                     self.auto_user.userprofile.full_name.split(' ')[1]]:
            new_url = urlparams(url, app_name=self.app.name,
                                app_key=self.app.key, name=name)
            response = self.client.get(new_url, follow=True)
            self.assertEqual(response.status_code, 200)
            data = json.loads(response.content)
            self.assertEqual(data['meta']['total_count'], 1)

        # Search nonexistent term
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key,
                            name='random')
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEqual(data['meta']['total_count'], 0)
Beispiel #3
0
    def setUp(self):
        voucher = UserFactory.create(userprofile={'is_vouched': True})
        self.user = UserFactory.create(userprofile={
            'is_vouched': True,
            'vouched_by': voucher.userprofile
        })
        group = GroupFactory.create()
        self.user.userprofile.groups.add(group)
        skill = SkillFactory.create()
        self.user.userprofile.skills.add(skill)
        language = LanguageFactory.create()
        self.user.userprofile.languages.add(language)

        self.resource_url = reverse('api_dispatch_list',
                                    kwargs={
                                        'api_name': 'v1',
                                        'resource_name': 'users'
                                    })
        self.mozilla_app = APIAppFactory.create(owner=self.user,
                                                is_mozilla_app=True)
        self.mozilla_resource_url = urlparams(self.resource_url,
                                              app_name=self.mozilla_app.name,
                                              app_key=self.mozilla_app.key)
        self.community_app = APIAppFactory.create(owner=self.user,
                                                  is_mozilla_app=False)
        self.community_resource_url = urlparams(
            self.resource_url,
            app_name=self.community_app.name,
            app_key=self.community_app.key)
Beispiel #4
0
def get_avatar_url(user, size=50):
    """Get a url pointing to user's avatar.

    The libravatar network is used for avatars. Return cached value if
    its last update was less than 24 hours before. Optional argument
    size can be provided to set the avatar size.

    """
    if not user:
        return None

    default_img_url = reduce(
        lambda u, x: urlparse.urljoin(u, x), [settings.SITE_URL, settings.STATIC_URL, "base/img/remo/remo_avatar.png"]
    )

    user_avatar, created = UserAvatar.objects.get_or_create(user=user)
    now = timezone.now()

    if (user_avatar.last_update < now - timedelta(days=7)) or created:
        user_avatar.avatar_url = libravatar_url(email=user.email, https=True)
        user_avatar.save()

    avatar_url = urlparams(user_avatar.avatar_url, default=default_img_url)
    if size != -1:
        avatar_url = urlparams(avatar_url, size=size)

    return avatar_url
Beispiel #5
0
    def setUp(self):
        voucher = UserFactory.create()
        self.user = UserFactory.create(
            userprofile={'is_vouched': True,
                         'vouched_by': voucher.userprofile})
        group = GroupFactory.create()
        group.add_member(self.user.userprofile)
        skill = SkillFactory.create()
        self.user.userprofile.skills.add(skill)
        self.user.userprofile.externalaccount_set.create(type=ExternalAccount.TYPE_SUMO,
                                                         identifier='Apitest')

        self.resource_url = reverse(
            'api_dispatch_list',
            kwargs={'api_name': 'v1', 'resource_name': 'users'})
        self.mozilla_app = APIAppFactory.create(
            owner=self.user, is_mozilla_app=True)
        self.mozilla_resource_url = urlparams(
            self.resource_url, app_name=self.mozilla_app.name,
            app_key=self.mozilla_app.key)
        self.community_app = APIAppFactory.create(
            owner=self.user, is_mozilla_app=False)
        self.community_resource_url = urlparams(
            self.resource_url, app_name=self.community_app.name,
            app_key=self.community_app.key)
Beispiel #6
0
    def test_api_search_languages(self):
        """Test API search languages."""
        self.app.is_mozilla_app = True
        self.app.is_active = True
        self.app.save()
        url = reverse('api_dispatch_list',
                      kwargs={
                          'api_name': 'v1',
                          'resource_name': 'users'
                      })

        new_url = urlparams(
            url,
            app_name=self.app.name,
            app_key=self.app.key,
            languages=self.auto_user.userprofile.languages.all()[0])
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEqual(data['meta']['total_count'], 1)

        # Search nonexistent term
        new_url = urlparams(url,
                            app_name=self.app.name,
                            app_key=self.app.key,
                            languages='random')
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEqual(data['meta']['total_count'], 0)
Beispiel #7
0
    def setUp(self):
        voucher = UserFactory.create(userprofile={'is_vouched': True})
        self.user = UserFactory.create(
            userprofile={'is_vouched': True,
                         'vouched_by': voucher.userprofile})
        group = GroupFactory.create()
        self.user.userprofile.groups.add(group)
        skill = SkillFactory.create()
        self.user.userprofile.skills.add(skill)
        language = LanguageFactory.create()
        self.user.userprofile.languages.add(language)

        self.resource_url = reverse(
            'api_dispatch_list',
            kwargs={'api_name': 'v1', 'resource_name': 'users'})
        self.mozilla_app = APIAppFactory.create(
            owner=self.user, is_mozilla_app=True)
        self.mozilla_resource_url = urlparams(
            self.resource_url, app_name=self.mozilla_app.name,
            app_key=self.mozilla_app.key)
        self.community_app = APIAppFactory.create(
            owner=self.user, is_mozilla_app=False)
        self.community_resource_url = urlparams(
            self.resource_url, app_name=self.community_app.name,
            app_key=self.community_app.key)
Beispiel #8
0
    def setUp(self):
        voucher = UserFactory.create()
        self.user = UserFactory.create(userprofile={
            'is_vouched': True,
            'vouched_by': voucher.userprofile
        })
        group = GroupFactory.create()
        group.add_member(self.user.userprofile)
        skill = SkillFactory.create()
        self.user.userprofile.skills.add(skill)
        self.user.userprofile.externalaccount_set.create(
            type=ExternalAccount.TYPE_SUMO, identifier='Apitest')

        self.resource_url = reverse('api_dispatch_list',
                                    kwargs={
                                        'api_name': 'v1',
                                        'resource_name': 'users'
                                    })
        self.mozilla_app = APIAppFactory.create(owner=self.user,
                                                is_mozilla_app=True)
        self.mozilla_resource_url = urlparams(self.resource_url,
                                              app_name=self.mozilla_app.name,
                                              app_key=self.mozilla_app.key)
        self.community_app = APIAppFactory.create(owner=self.user,
                                                  is_mozilla_app=False)
        self.community_resource_url = urlparams(
            self.resource_url,
            app_name=self.community_app.name,
            app_key=self.community_app.key)
Beispiel #9
0
def get_avatar_url(user, size=50):
    """Get a url pointing to user's avatar.

    The libravatar network is used for avatars. Return cached value if
    its last update was less than 24 hours before. Optional argument
    size can be provided to set the avatar size.

    """
    if not user:
        return None

    default_img_url = reduce(
        lambda u, x: urlparse.urljoin(u, x),
        [settings.SITE_URL, settings.MEDIA_URL, 'img/remo/remo_avatar.png'])

    user_avatar, created = UserAvatar.objects.get_or_create(user=user)
    now = timezone.now()

    if (user_avatar.last_update < now - timedelta(days=7)) or created:
        user_avatar.avatar_url = libravatar_url(email=user.email)
        user_avatar.save()

    avatar_url = urlparams(user_avatar.avatar_url, default=default_img_url)
    if size != -1:
        avatar_url = urlparams(avatar_url, size=size)

    return avatar_url
Beispiel #10
0
def get_event_filtered_url(category=None, initiative=None):
    """Returns events list page of given category or initiative."""

    url = reverse('events_list_events')
    if category:
        return urlparams(url, '/category/%s/' % category.lower())
    elif initiative:
        return urlparams(url, '/initiative/%s/' % initiative.lower())
    else:
        return url
Beispiel #11
0
def get_event_filtered_url(category=None, initiative=None):
    """Returns events list page of given category or initiative."""

    url = reverse('events_list_events')
    if category:
        return urlparams(url, '/category/%s/' % category.lower())
    elif initiative:
        return urlparams(url, '/initiative/%s/' % initiative.lower())
    else:
        return url
Beispiel #12
0
    def test_view_reports_list(self):
        """Test view report list page."""
        c = Client()
        response = c.get(reverse('reports_list_reports'))
        self.assertTemplateUsed(response, 'reports_list.html')

        for sort_key in LIST_REPORTS_VALID_SHORTS:
            response = c.get(
                urlparams(reverse('reports_list_reports'), sort_key=sort_key))
            self.assertTemplateUsed(response, 'reports_list.html')

        # Test pagination.
        response = c.get(urlparams(reverse('reports_list_reports'), page=1))
        self.assertTemplateUsed(response, 'reports_list.html')
Beispiel #13
0
    def test_view_reports_list(self):
        """Test view report list page."""
        c = Client()
        response = c.get(reverse('reports_list_reports'))
        self.assertTemplateUsed(response, 'reports_list.html')

        for sort_key in LIST_REPORTS_VALID_SORTS:
            response = c.get(urlparams(reverse('reports_list_reports'),
                                       sort_key=sort_key))
            self.assertTemplateUsed(response, 'reports_list.html')

        # Test pagination.
        response = c.get(urlparams(reverse('reports_list_reports'), page=1))
        self.assertTemplateUsed(response, 'reports_list.html')
Beispiel #14
0
        def wrapper(request, *args, **kwargs):

            def _check_if_user_has_permissions():
                if (((permissions and request.user.has_perms(permissions)) or
                     request.user.groups.filter(name=group).exists())):
                    return True
                return False

            def _check_if_user_owns_page():
                if owner_field and model:
                    if not kwargs.get(filter_field):
                        return True

                    obj = get_object_or_none(model, **{filter_field:
                                                       kwargs[filter_field]})
                    if obj and getattr(obj, owner_field) == request.user:
                        return True
                return False

            if request.user.is_authenticated():
                if (((not permissions and not group and not filter_field) or
                     request.user.is_superuser or
                     _check_if_user_owns_page() or
                     _check_if_user_has_permissions())):
                    return func(request, *args, **kwargs)
                else:
                    messages.error(request, 'Permission denied.')
                    return redirect('main')
            else:
                messages.warning(request, 'Please login.')
                next_url = urlparams(reverse('main'), next=request.path)
                return HttpResponseRedirect(next_url)
Beispiel #15
0
 def test_public_search_with_unvouched(self):
     url = urlparams(reverse('search'), include_non_vouched='on')
     response = self.anonymous_client.get(url, follow=True)
     paginator = response.context['people'].paginator
     eq_(paginator.count, 2)
     self.assertIn(self.mozillian2.userprofile, paginator.object_list)
     self.assertIn(self.pending.userprofile, paginator.object_list)
Beispiel #16
0
 def test_get_detail_mozilla_app(self):
     client = Client()
     url = reverse('api_dispatch_detail',
                   kwargs={'api_name': 'v1', 'resource_name': 'users',
                           'pk': self.user.userprofile.id})
     url = urlparams(url, app_name=self.mozilla_app.name,
                     app_key=self.mozilla_app.key)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     profile = self.user.userprofile
     eq_(response.status_code, 200)
     eq_(data['id'], profile.id)
     eq_(data['full_name'], profile.full_name)
     eq_(data['is_vouched'], profile.is_vouched)
     eq_(data['vouched_by'], profile.vouched_by.id)
     # eq_(data['date_vouched'], profile.date_vouched)
     eq_(data['groups'], list(profile.groups.values_list('name', flat=True)))
     eq_(data['skills'], list(profile.skills.values_list('name', flat=True)))
     eq_(data['accounts'],
         [{'identifier': a.identifier, 'type': a.type}
          for a in profile.externalaccount_set.all()])
     eq_(data['bio'], profile.bio)
     eq_(data['photo'], profile.photo)
     eq_(data['ircname'], profile.ircname)
     eq_(data['country'], profile.geo_country.code)
     eq_(data['region'], profile.geo_region.name)
     eq_(data['city'], profile.geo_city.name)
     eq_(data['date_mozillian'], profile.date_mozillian)
     eq_(data['timezone'], profile.timezone)
     eq_(data['email'], profile.email)
     eq_(data['url'],
         absolutify(reverse('phonebook:profile_view',
                            args=[profile.user.username])))
Beispiel #17
0
 def test_request_with_normal_limit(self):
     client = Client()
     url = urlparams(self.mozilla_resource_url, limit=5)
     response = client.get(url, follow=True)
     eq_(response.status_code, 200)
     data = json.loads(response.content)
     eq_(data["meta"]["limit"], 5)
Beispiel #18
0
def gravatar(email, default_avatar_url=settings.DEFAULT_AVATAR_URL,
             size=175, rating='pg'):
    """Return the Gravatar URL for an email address."""
    url = GRAVATAR_URL.format(emaildigest=md5(email).hexdigest())
    url = urlparams(url, d=utils.absolutify(default_avatar_url),
                    s=size, r=rating)
    return url
Beispiel #19
0
 def test_search_no_ajax(self):
     user = UserFactory.create(userprofile={'is_vouched': True})
     group = GroupFactory.create()
     url = urlparams(reverse('groups:search_groups'), term=group.name)
     with self.login(user) as client:
         response = client.get(url, follow=True)
     ok_(isinstance(response, HttpResponseBadRequest))
Beispiel #20
0
 def test_get_detail_mozilla_app(self):
     client = Client()
     url = reverse('api_dispatch_detail',
                   kwargs={'api_name': 'v1', 'resource_name': 'users',
                           'pk': self.user.userprofile.id})
     url = urlparams(url, app_name=self.mozilla_app.name,
                     app_key=self.mozilla_app.key)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     profile = self.user.userprofile
     eq_(response.status_code, 200)
     eq_(data['id'], unicode(profile.id))
     eq_(data['full_name'], profile.full_name)
     eq_(data['is_vouched'], profile.is_vouched)
     eq_(data['website'], profile.website)
     eq_(data['vouched_by'], profile.vouched_by.user.id)
     eq_(data['date_vouched'], profile.date_vouched)
     eq_(data['groups'], unicode(profile.groups.values_list('name')))
     eq_(data['skills'], unicode(profile.skills.values_list('name')))
     eq_(data['languages'], unicode(profile.languages.values_list('name')))
     eq_(data['bio'], profile.bio)
     eq_(data['photo'], profile.photo)
     eq_(data['ircname'], profile.ircname)
     eq_(data['country'], profile.country)
     eq_(data['region'], profile.region)
     eq_(data['city'], profile.city)
     eq_(data['date_mozillian'], profile.date_mozillian)
     eq_(data['timezone'], profile.timezone)
     eq_(data['tshirt'], profile.tshirt)
     eq_(data['email'], profile.email)
     eq_(data['url'],
         absolutify(reverse('phonebook:profile_view',
                            args=[profile.user.username])))
Beispiel #21
0
def gravatar(email, default_avatar_url=settings.DEFAULT_AVATAR_URL,
             size=175, rating='pg'):
    """Return the Gravatar URL for an email address."""
    url = GRAVATAR_URL.format(emaildigest=md5(email).hexdigest())
    url = urlparams(url, d=utils.absolutify(default_avatar_url),
                    s=size, r=rating)
    return url
Beispiel #22
0
        def wrapper(request, *args, **kwargs):
            def _check_if_user_has_permissions():
                if (((permissions and request.user.has_perms(permissions))
                     or request.user.groups.filter(name=group).exists())):
                    return True
                return False

            def _check_if_user_owns_page():
                if owner_field and model:
                    if not kwargs.get(filter_field):
                        return True

                    obj = get_object_or_none(
                        model, **{filter_field: kwargs[filter_field]})
                    if obj and getattr(obj, owner_field) == request.user:
                        return True
                return False

            if request.user.is_authenticated():
                if (((not permissions and not group and not filter_field)
                     or request.user.is_superuser
                     or _check_if_user_owns_page()
                     or _check_if_user_has_permissions())):
                    return func(request, *args, **kwargs)
                else:
                    messages.error(request, 'Permission denied.')
                    return redirect('main')
            else:
                messages.warning(request, 'Please login.')
                next_url = urlparams(reverse('main'), next=request.path)
                return HttpResponseRedirect(next_url)
Beispiel #23
0
    def form_valid(self, form):
        """Custom form validation to support email changing.

        If user is already authenticated and reaches this points, it's
        an email changing procedure. Validate that email is good and
        save it in the database.

        Otherwise continue with the default django-browserid verification.
        """
        if not self.request.user.is_authenticated():
            return super(BrowserIDVerify, self).form_valid(form)

        failure_url = urlparams(reverse('phonebook:profile_edit'), bid_login_failed=1)
        self.assertion = form.cleaned_data['assertion']
        self.audience = get_audience(self.request)
        result = verify(self.assertion, self.audience)
        if not result:
            messages.error(self.request, _('Authentication failed.'))
            return redirect(failure_url)

        email = result['email']

        if User.objects.filter(email=email).exists():
            messages.error(self.request, _('Email already exists in the database.'))
            return redirect('phonebook:logout')

        user = self.request.user
        user.email = email
        user.save()
        return redirect('phonebook:profile_view', user.username)
Beispiel #24
0
 def test_get_detail_mozilla_app(self):
     client = Client()
     url = reverse(
         "api_dispatch_detail", kwargs={"api_name": "v1", "resource_name": "users", "pk": self.user.userprofile.id}
     )
     url = urlparams(url, app_name=self.mozilla_app.name, app_key=self.mozilla_app.key)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     profile = self.user.userprofile
     eq_(response.status_code, 200)
     eq_(data["id"], profile.id)
     eq_(data["full_name"], profile.full_name)
     eq_(data["is_vouched"], profile.is_vouched)
     eq_(data["vouched_by"], profile.vouched_by.id)
     # eq_(data['date_vouched'], profile.date_vouched)
     eq_(data["groups"], list(profile.groups.values_list("name", flat=True)))
     eq_(data["skills"], list(profile.skills.values_list("name", flat=True)))
     eq_(data["accounts"], [{"identifier": a.identifier, "type": a.type} for a in profile.externalaccount_set.all()])
     eq_(data["bio"], profile.bio)
     eq_(data["photo"], profile.photo)
     eq_(data["ircname"], profile.ircname)
     eq_(data["country"], profile.geo_country.code)
     eq_(data["region"], profile.geo_region.name)
     eq_(data["city"], profile.geo_city.name)
     eq_(data["date_mozillian"], profile.date_mozillian)
     eq_(data["timezone"], profile.timezone)
     eq_(data["email"], profile.email)
     eq_(data["url"], absolutify(reverse("phonebook:profile_view", args=[profile.user.username])))
Beispiel #25
0
 def test_get_detail_mozilla_app(self):
     client = Client()
     url = reverse('api_dispatch_detail',
                   kwargs={'api_name': 'v1', 'resource_name': 'users',
                           'pk': self.user.userprofile.id})
     url = urlparams(url, app_name=self.mozilla_app.name,
                     app_key=self.mozilla_app.key)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     profile = self.user.userprofile
     eq_(response.status_code, 200)
     eq_(data['id'], profile.id)
     eq_(data['full_name'], profile.full_name)
     eq_(data['is_vouched'], profile.is_vouched)
     eq_(data['vouched_by'], profile.vouched_by.id)
     # eq_(data['date_vouched'], profile.date_vouched)
     eq_(data['groups'], list(profile.groups.values_list('name', flat=True)))
     eq_(data['skills'], list(profile.skills.values_list('name', flat=True)))
     eq_(data['accounts'],
         [{'identifier': a.identifier, 'type': a.type}
          for a in profile.externalaccount_set.all()])
     eq_(data['bio'], profile.bio)
     eq_(data['photo'], profile.photo)
     eq_(data['ircname'], profile.ircname)
     eq_(data['country'], profile.country)
     eq_(data['region'], profile.region)
     eq_(data['city'], profile.city)
     eq_(data['date_mozillian'], profile.date_mozillian)
     eq_(data['timezone'], profile.timezone)
     eq_(data['email'], profile.email)
     eq_(data['url'],
         absolutify(reverse('phonebook:profile_view',
                            args=[profile.user.username])))
Beispiel #26
0
 def test_get_detail_mozilla_app(self):
     client = Client()
     url = reverse('api_dispatch_detail',
                   kwargs={'api_name': 'v1', 'resource_name': 'users',
                           'pk': self.user.userprofile.id})
     url = urlparams(url, app_name=self.mozilla_app.name,
                     app_key=self.mozilla_app.key)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     profile = self.user.userprofile
     eq_(response.status_code, 200)
     eq_(data['id'], unicode(profile.id))
     eq_(data['full_name'], profile.full_name)
     eq_(data['is_vouched'], profile.is_vouched)
     eq_(data['website'], profile.website)
     eq_(data['vouched_by'], profile.vouched_by.user.id)
     eq_(data['date_vouched'], profile.date_vouched)
     eq_(data['groups'], list(profile.groups.values_list('name', flat=True)))
     eq_(data['skills'], list(profile.skills.values_list('name', flat=True)))
     eq_(data['languages'], list(profile.languages.values_list('name', flat=True)))
     eq_(data['bio'], profile.bio)
     eq_(data['photo'], profile.photo)
     eq_(data['ircname'], profile.ircname)
     eq_(data['country'], profile.country)
     eq_(data['region'], profile.region)
     eq_(data['city'], profile.city)
     eq_(data['date_mozillian'], profile.date_mozillian)
     eq_(data['timezone'], profile.timezone)
     eq_(data['email'], profile.email)
     eq_(data['url'],
         absolutify(reverse('phonebook:profile_view',
                            args=[profile.user.username])))
Beispiel #27
0
 def test_public_search_with_unvouched(self):
     url = urlparams(reverse('search'), include_non_vouched='on')
     response = self.anonymous_client.get(url, follow=True)
     paginator = response.context['people'].paginator
     eq_(paginator.count, 2)
     self.assertIn(self.mozillian2.userprofile, paginator.object_list)
     self.assertIn(self.pending.userprofile, paginator.object_list)
Beispiel #28
0
 def test_pagination_range_middle_page(self):
     response = self.client.get(
         urlparams(reverse('base.index_json'), page=5))
     pagination_range = response.context['pagination_range']
     eq_(pagination_range[0], 3)
     eq_(pagination_range[-1], 7)
     eq_(len(pagination_range), 5)
Beispiel #29
0
 def test_non_integer_page_number(self):
     """Test that a non integer page number returns the first page."""
     response = self.client.get(
         urlparams(reverse('base.index_json'), page='k'))
     eq_(response.status_code, 200)
     eq_(response.context['snippets'].number, 1)
     eq_(response.context['snippets'].paginator.num_pages, 10)
Beispiel #30
0
 def test_empty_page_number(self):
     """Test that empty page number returns the last page."""
     response = self.client.get(
         urlparams(reverse('base.index_json'), page=20))
     eq_(response.status_code, 200)
     eq_(response.context['snippets'].number, 10)
     eq_(response.context['snippets'].paginator.num_pages, 10)
Beispiel #31
0
 def test_get_detail_mozilla_app(self):
     client = Client()
     url = reverse(
         "api_dispatch_detail", kwargs={"api_name": "v1", "resource_name": "users", "pk": self.user.userprofile.id}
     )
     url = urlparams(url, app_name=self.mozilla_app.name, app_key=self.mozilla_app.key)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     profile = self.user.userprofile
     eq_(response.status_code, 200)
     eq_(data["id"], unicode(profile.id))
     eq_(data["full_name"], profile.full_name)
     eq_(data["is_vouched"], profile.is_vouched)
     eq_(data["website"], profile.website)
     eq_(data["vouched_by"], profile.vouched_by.user.id)
     eq_(data["date_vouched"], profile.date_vouched)
     eq_(data["groups"], unicode(profile.groups.values_list("name")))
     eq_(data["skills"], unicode(profile.skills.values_list("name")))
     eq_(data["languages"], unicode(profile.languages.values_list("name")))
     eq_(data["bio"], profile.bio)
     eq_(data["photo"], profile.photo)
     eq_(data["ircname"], profile.ircname)
     eq_(data["country"], profile.country)
     eq_(data["region"], profile.region)
     eq_(data["city"], profile.city)
     eq_(data["date_mozillian"], profile.date_mozillian)
     eq_(data["timezone"], profile.timezone)
     eq_(data["email"], profile.email)
     eq_(data["url"], absolutify(reverse("phonebook:profile_view", args=[profile.user.username])))
Beispiel #32
0
def view_ng_report(request, display_name, year, month, day=None, id=None):
    if not day and not id:
        url = reverse('list_ng_reports_rep', kwargs={'rep': display_name})
        return redirect(urlparams(url, year=year, month=month))

    user = get_object_or_404(User, userprofile__display_name=display_name)
    report = get_object_or_404(NGReport, id=id)
    comment_form = forms.NGReportCommentForm()
    verification_form = forms.NGVerifyReportForm(instance=report)

    editable = False
    if ((request.user == user or request.user.has_perm('change_ngreport'))
            and report.activity.name not in UNLISTED_ACTIVITIES):
        editable = True

    ctx_data = {'pageuser': user,
                'user_profile': user.userprofile,
                'report': report,
                'editable': editable,
                'comment_form': comment_form,
                'verification_form': verification_form}
    template = 'view_ng_report.html'

    if request.method == 'POST':
        # Process comment form
        if 'comment' in request.POST:
            comment_form = forms.NGReportCommentForm(request.POST)
            if comment_form.is_valid():
                if not request.user.is_authenticated():
                    messages.error(request, 'Permission denied.')
                    return redirect('main')
                obj = comment_form.save(commit=False)
                obj.user = request.user
                obj.report = report
                obj.save()
                messages.success(request, 'Comment saved successfully.')
                statsd.incr('reports.create_comment')
                ctx_data['comment_form'] = forms.NGReportCommentForm()

        # Process verification form
        else:
            verification_form = forms.NGVerifyReportForm(request.POST,
                                                         instance=report)
            if verification_form.is_valid():
                if ((not request.user.is_authenticated()) or
                    (not request.user.groups.filter(
                        Q(name='Council') | Q(name='Mentor')).exists())):
                    messages.error(request, 'Permission denied.')
                    return redirect('main')
                if verification_form.cleaned_data['verified_activity']:
                    messages.success(request,
                                     ('Activity verified successfully.'))
                else:
                    messages.success(request,
                                     ('Activiy invalidated successfully.'))
                verification_form.save()
                ctx_data['verification_form'] = forms.NGVerifyReportForm(
                    instance=report)

    return render(request, template, ctx_data)
Beispiel #33
0
 def test_search_no_ajax(self):
     user = UserFactory.create()
     group = GroupFactory.create()
     url = urlparams(reverse('groups:search_groups'), term=group.name)
     with self.login(user) as client:
         response = client.get(url, follow=True)
     ok_(isinstance(response, HttpResponseBadRequest))
Beispiel #34
0
 def test_request_with_huge_limit(self):
     client = Client()
     url = urlparams(self.mozilla_resource_url, limit=200000000000000000000)
     response = client.get(url, follow=True)
     eq_(response.status_code, 200)
     data = json.loads(response.content)
     eq_(data['meta']['limit'], 1)
Beispiel #35
0
 def test_request_with_huge_limit(self):
     client = Client()
     url = urlparams(self.mozilla_resource_url, limit=200000000000000000000)
     response = client.get(url, follow=True)
     eq_(response.status_code, 200)
     data = json.loads(response.content)
     eq_(data['meta']['limit'], 1)
Beispiel #36
0
    def form_valid(self, form):
        """Custom form validation to support email changing.

        If user is already authenticated and reaches this point, it's
        an email changing procedure. Validate that email is good and
        save it in the database.

        Otherwise continue with the default django-browserid verification.
        """
        if not self.request.user.is_authenticated():
            return super(BrowserIDVerify, self).form_valid(form)

        failure_url = urlparams(reverse('phonebook:profile_edit'),
                                bid_login_failed=1)
        self.assertion = form.cleaned_data['assertion']
        self.audience = get_audience(self.request)
        result = verify(self.assertion, self.audience)
        if not result:
            messages.error(self.request, _('Authentication failed.'))
            return redirect(failure_url)

        email = result['email']

        if User.objects.filter(email=email).exists():
            messages.error(self.request,
                           _('Email already exists in the database.'))
            return redirect('phonebook:logout')

        user = self.request.user
        user.email = email
        user.save()
        return redirect('phonebook:profile_view', user.username)
Beispiel #37
0
def view_ng_report(request, display_name, year, month, day=None, id=None):
    if not day and not id:
        url = reverse('list_ng_reports_rep', kwargs={'rep': display_name})
        return redirect(urlparams(url, year=year, month=month))

    user = get_object_or_404(User, userprofile__display_name=display_name)
    report = get_object_or_404(NGReport, id=id)
    comment_form = forms.NGReportCommentForm(request.POST or None)

    editable = False
    if ((request.user == user or request.user.has_perm('change_ngreport'))
            and not report.activity.name in UNLISTED_ACTIVITIES):
        editable = True

    ctx_data = {'pageuser': user,
                'user_profile': user.userprofile,
                'report': report,
                'editable': editable,
                'comment_form': comment_form}
    template = 'view_ng_report.html'

    if comment_form.is_valid():
        if not request.user.is_authenticated():
            messages.error(request, 'Permission denied.')
            return redirect('main')
        obj = comment_form.save(commit=False)
        obj.user = request.user
        obj.report = report
        obj.save()
        messages.success(request, 'Comment saved successfully.')
        statsd.incr('reports.create_comment')
        ctx_data['comment_form'] = forms.NGReportCommentForm()

    return render(request, template, ctx_data)
Beispiel #38
0
 def test_filtering(self, filter_mock):
     url = urlparams(self.resource_url, city='athens')
     client = Client()
     client.get(url, follow=True)
     ok_(filter_mock.called)
     call_arg = filter_mock.call_args[0][0]
     eq_(call_arg.children, [('city__iexact', 'athens')])
Beispiel #39
0
 def test_filtering(self, filter_mock):
     url = urlparams(self.resource_url, city='athens')
     client = Client()
     client.get(url, follow=True)
     ok_(filter_mock.called)
     call_arg = filter_mock.call_args[0][0]
     eq_(call_arg.children, [('city__iexact', 'athens')])
Beispiel #40
0
 def setUp(self):
     self.settings_data = {'receive_email_on_add_report': False,
                           'receive_email_on_edit_report': True,
                           'receive_email_on_add_comment': True}
     self.user_edit_settings_url = reverse('edit_settings')
     self.failed_url = urlparams(settings.LOGIN_REDIRECT_URL_FAILURE,
                                 bid_login_failed=1)
Beispiel #41
0
 def test_base(self, mocked_month2number):
     user = UserFactory.create(groups="Rep")
     reports_url = reverse("list_ng_reports_rep", args=(user.userprofile.display_name,))
     reports_url = urlparams(reports_url, year="2014", month="Apri")
     response = self.client.get(reports_url, follow=True)
     mocked_month2number.assert_called_once_with(u"Apri")
     eq_(response.status_code, 404)
Beispiel #42
0
 def test_community_app_does_not_allow_community_sites(self):
     user = UserFactory.create(userprofile={'allows_community_sites': False})
     client = Client()
     url = urlparams(self.community_resource_url, email=user.email)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(response.status_code, 200)
     eq_(len(data['objects']), 0)
Beispiel #43
0
 def test_query_with_space(self):
     user = UserFactory.create(userprofile={'city': 'Mountain View'})
     client = Client()
     url = urlparams(self.mozilla_resource_url, city='mountain view')
     request = client.get(url, follow=True)
     data = json.loads(request.content)
     eq_(len(data['objects']), 1)
     eq_(data['objects'][0]['id'], unicode(user.userprofile.id))
Beispiel #44
0
 def test_search_name(self):
     user = UserFactory.create(userprofile={"full_name": u"Νίκος Κούκος"})
     client = Client()
     url = urlparams(self.mozilla_resource_url, name=user.userprofile.full_name)
     request = client.get(url, follow=True)
     data = json.loads(request.content)
     eq_(len(data["objects"]), 1)
     eq_(data["objects"][0]["id"], user.userprofile.id)
Beispiel #45
0
 def test_search_username(self):
     user = UserFactory.create(userprofile={'is_vouched': True})
     url = urlparams(self.mozilla_resource_url, username=user.username)
     client = Client()
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(len(data['objects']), 1)
     eq_(data['objects'][0]['id'], unicode(user.userprofile.id))
Beispiel #46
0
 def test_search_ircname(self):
     user = UserFactory.create(userprofile={"ircname": "nikos"})
     url = urlparams(self.mozilla_resource_url, ircname=user.userprofile.ircname)
     client = Client()
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(len(data["objects"]), 1)
     eq_(data["objects"][0]["id"], user.userprofile.id)
Beispiel #47
0
 def test_search_city(self):
     user = UserFactory.create(userprofile={"is_vouched": True, "city": u"αθήνα"})
     url = urlparams(self.mozilla_resource_url, city=user.userprofile.city)
     client = Client()
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(len(data["objects"]), 1)
     eq_(data["objects"][0]["id"], unicode(user.userprofile.id))
Beispiel #48
0
 def test_search_city(self):
     user = UserFactory.create(userprofile={'city': u'αθήνα'})
     url = urlparams(self.mozilla_resource_url, city=user.userprofile.city)
     client = Client()
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(len(data['objects']), 1)
     eq_(data['objects'][0]['id'], user.userprofile.id)
Beispiel #49
0
 def test_get_detail_community_app(self):
     client = Client()
     url = reverse(
         "api_dispatch_detail", kwargs={"api_name": "v1", "resource_name": "users", "pk": self.user.userprofile.id}
     )
     url = urlparams(url, app_name=self.community_app.name, app_key=self.community_app.key)
     response = client.get(url, follow=True)
     eq_(response.status_code, 403)
Beispiel #50
0
 def test_base(self, mocked_month2number):
     user = UserFactory.create(groups='Rep')
     reports_url = reverse('list_ng_reports_rep',
                           args=(user.userprofile.display_name, ))
     reports_url = urlparams(reports_url, year='2014', month='Apri')
     response = self.client.get(reports_url, follow=True)
     mocked_month2number.assert_called_once_with(u'Apri')
     eq_(response.status_code, 404)
Beispiel #51
0
 def test_community_app_does_not_allow_community_sites(self):
     user = UserFactory.create(userprofile={'allows_community_sites': False})
     client = Client()
     url = urlparams(self.community_resource_url, email=user.email)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(response.status_code, 200)
     eq_(len(data['objects']), 0)
Beispiel #52
0
 def test_search_username(self):
     user = UserFactory.create(userprofile={'is_vouched': True})
     url = urlparams(self.mozilla_resource_url, username=user.username)
     client = Client()
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(len(data['objects']), 1)
     eq_(data['objects'][0]['id'], unicode(user.userprofile.id))
Beispiel #53
0
 def test_query_with_space(self):
     user = UserFactory.create(userprofile={'city': 'Mountain View'})
     client = Client()
     url = urlparams(self.mozilla_resource_url, city='mountain view')
     request = client.get(url, follow=True)
     data = json.loads(request.content)
     eq_(len(data['objects']), 1)
     eq_(data['objects'][0]['id'], user.userprofile.id)
Beispiel #54
0
    def test_get_users(self):
        """Test permissions of API dispatch list of 'users' resource."""
        # No app
        url = reverse('api_dispatch_list', kwargs={'api_name': 'v1',
                                                   'resource_name': 'users'})
        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 401,
                         'Unauthorized call gets results.')

        # Invalid app
        new_url = urlparams(url, app_name='invalid', app_key='xxx')
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 401,
                         'Invalid App call gets results.')

        # Inactive app
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key)
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 401,
                         'Inactive App call gets results.')

        # Valid community app with filtering
        self.app.is_active = True
        self.app.save()
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key,
                            email=self.mozillian.email)
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200,
                         'Community App w/ filtering does not get results.')

        # Valid community app with filtering, email capitalized
        self.app.is_active = True
        self.app.save()
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key,
                            email=self.auto_user.email.capitalize())
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200,
                         ('Community App w/ filtering does not '
                          'get results with capitalized email.'))

        # Valid community app without filtering
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key)
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 403,
                         'Community App w/o filters does get results.')

        # Valid Mozilla app with filtering
        self.app.is_mozilla_app = True
        self.app.save()
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key,
                            email=self.mozillian.email)
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200,
                         'Mozilla App w/ filtering does not get results.')

        # Valid Mozilla app without filtering
        new_url = urlparams(url, app_name=self.app.name, app_key=self.app.key)
        response = self.client.get(new_url, follow=True)
        self.assertEqual(response.status_code, 200,
                         'Mozilla App w/o filtering does not get results.')
Beispiel #55
0
def multiple_event_ical(request, period, start=None, end=None, search=None):
    """Redirect iCal URL to API query."""

    # Create API query
    url = reverse('api_dispatch_list',
                  kwargs={
                      'api_name': 'v1',
                      'resource_name': 'event'
                  })
    if period == 'all':
        url = urlparams(url, start__gt='1970-01-01')
    elif period == 'future':
        url = urlparams(url, start__gte=now().strftime("%Y-%m-%d"))
    elif period == 'past':
        url = urlparams(url, start__lt=now().strftime("%Y-%m-%d"))
    elif period == 'custom':
        if start:
            url = urlparams(url, start__gte=start)
        if end:
            url = urlparams(url, end__lte=end)
    else:
        raise Http404

    if search:
        url = urlparams(url, query=search)

    statsd.incr('events.export_multiple_ical')
    return redirect(urlparams(url, format='ical', offset=0, limit=0))
Beispiel #56
0
 def test_mozilla_app_does_allows_mozilla_sites(self):
     user = UserFactory.create(userprofile={'allows_mozilla_sites': True})
     client = Client()
     url = urlparams(self.mozilla_resource_url, email=user.email)
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     eq_(response.status_code, 200)
     eq_(len(data['objects']), 1)
     eq_(data['objects'][0]['email'], user.email)
Beispiel #57
0
 def test_get_detail_community_app(self):
     client = Client()
     url = reverse('api_dispatch_detail',
                   kwargs={'api_name': 'v1', 'resource_name': 'users',
                           'pk': self.user.userprofile.id})
     url = urlparams(url, app_name=self.community_app.name,
                     app_key=self.community_app.key)
     response = client.get(url, follow=True)
     eq_(response.status_code, 403)
Beispiel #58
0
 def test_request_with_huge_offset(self):
     UserFactory.create(userprofile={'is_vouched': True})
     UserFactory.create(userprofile={'is_vouched': True})
     client = Client()
     url = urlparams(self.mozilla_resource_url, offset=100000000)
     response = client.get(url, follow=True)
     eq_(response.status_code, 200)
     data = json.loads(response.content)
     eq_(data['meta']['offset'], data['meta']['total_count'])
Beispiel #59
0
 def test_is_vouched_true(self):
     UserFactory.create(userprofile={'is_vouched': True})
     UserFactory.create(userprofile={'is_vouched': False})
     client = Client()
     url = urlparams(self.mozilla_resource_url, is_vouched='true')
     response = client.get(url, follow=True)
     data = json.loads(response.content)
     for obj in data['objects']:
         ok_(obj['is_vouched'])
Beispiel #60
0
 def setUp(self):
     self.settings_data = {
         'receive_email_on_add_report': False,
         'receive_email_on_edit_report': True,
         'receive_email_on_add_comment': True
     }
     self.user_edit_settings_url = reverse('edit_settings')
     self.failed_url = urlparams(settings.LOGIN_REDIRECT_URL_FAILURE,
                                 bid_login_failed=1)