def test_multiple_shared_works(self):
        request = RequestFactory().post(
            '/api',
            HTTP_AUTHORIZATION='mkt-shared-secret '
            '[email protected],56b6f1a3dd735d962c56'
            'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
            '9c68c31b3371aa8130317815c89e5072e31bb94b4'
            '121c5c165f3515838d4d6c60c4,165d631d3c3045'
            '458b4516242dad7ae')
        request.user = AnonymousUser()
        drf_request = Request(request)

        # Start with an AnonymousUser on the request, because that's a classic
        # situation: we already went through a middleware, it didn't find a
        # session cookie, if set request.user = AnonymousUser(), and now we
        # are going through the authentication code in the API.
        request.user = AnonymousUser()

        # Call middleware as they would normally be called.
        APIBaseMiddleware().process_request(request)
        RestSharedSecretMiddleware().process_request(request)
        RestOAuthMiddleware().process_request(request)

        drf_request.authenticators = (
                authentication.RestSharedSecretAuthentication(),
                authentication.RestOAuthAuthentication())

        eq_(drf_request.user, self.profile)
        eq_(drf_request._request.user, self.profile)
        eq_(drf_request.user.is_authenticated(), True)
        eq_(drf_request._request.user.is_authenticated(), True)
        eq_(drf_request.user.pk, self.profile.pk)
        eq_(drf_request._request.user.pk, self.profile.pk)
Exemplo n.º 2
0
    def test_multiple_shared_works(self):
        request = RequestFactory().post(
            '/api',
            HTTP_AUTHORIZATION='mkt-shared-secret '
            '[email protected],56b6f1a3dd735d962c56'
            'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
            '9c68c31b3371aa8130317815c89e5072e31bb94b4'
            '121c5c165f3515838d4d6c60c4,165d631d3c3045'
            '458b4516242dad7ae')
        request.user = AnonymousUser()
        drf_request = Request(request)

        # Start with an AnonymousUser on the request, because that's a classic
        # situation: we already went through a middleware, it didn't find a
        # session cookie, if set request.user = AnonymousUser(), and now we
        # are going through the authentication code in the API.
        request.user = AnonymousUser()

        # Call middleware as they would normally be called.
        APIBaseMiddleware().process_request(request)
        RestSharedSecretMiddleware().process_request(request)
        RestOAuthMiddleware().process_request(request)

        drf_request.authenticators = (
            authentication.RestSharedSecretAuthentication(),
            authentication.RestOAuthAuthentication())

        eq_(drf_request.user, self.profile)
        eq_(drf_request._request.user, self.profile)
        eq_(drf_request.user.is_authenticated(), True)
        eq_(drf_request._request.user.is_authenticated(), True)
        eq_(drf_request.user.pk, self.profile.pk)
        eq_(drf_request._request.user.pk, self.profile.pk)
Exemplo n.º 3
0
 def get_request(self, profile):
     request = RequestFactory().post('/')
     if not profile:
         request.user = AnonymousUser()
     else:
         request.user = profile.user
         request.amo_user = profile
     return request
Exemplo n.º 4
0
 def get_request(self, profile):
     request = RequestFactory().post('/')
     if not profile:
         request.user = AnonymousUser()
     else:
         request.user = profile.user
         request.amo_user = profile
     return request
Exemplo n.º 5
0
    def test_multiple_fail(self):
        request = RequestFactory().post('/api')
        request.user = AnonymousUser()
        drf_request = Request(request)
        request.user = AnonymousUser()
        drf_request.authenticators = (
            authentication.RestSharedSecretAuthentication(),
            authentication.RestOAuthAuthentication())

        eq_(drf_request.user.is_authenticated(), False)
        eq_(drf_request._request.user.is_authenticated(), False)
    def test_multiple_fail(self):
        request = RequestFactory().post('/api')
        request.user = AnonymousUser()
        drf_request = Request(request)
        request.user = AnonymousUser()
        drf_request.authenticators = (
                authentication.RestSharedSecretAuthentication(),
                authentication.RestOAuthAuthentication())

        eq_(drf_request.user.is_authenticated(), False)
        eq_(drf_request._request.user.is_authenticated(), False)
Exemplo n.º 7
0
 def test_session_auth_no_post(self):
     req = RequestFactory().post('/api/')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(not self.auth.authenticate(Request(req)))
     ok_(not req.user.is_authenticated())
Exemplo n.º 8
0
def dump_app(id, **kw):
    # Because @robhudson told me to.
    from mkt.api.resources import AppResource
    # Note: not using storage because all these operations should be local.
    target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
                              str(id / 1000))
    target_file = os.path.join(target_dir, str(id) + '.json')

    try:
        obj = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        task_log.info(u'Webapp does not exist: {0}'.format(id))
        return

    req = RequestFactory().get('/')
    req.user = AnonymousUser()
    req.REGION = WORLDWIDE

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    task_log.info('Dumping app {0} to {1}'.format(id, target_file))
    res = AppResource().dehydrate_objects([obj], request=req)
    json.dump(res[0], open(target_file, 'w'), cls=JSONEncoder)
    return target_file
Exemplo n.º 9
0
def req_factory_factory(url, user=None):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory().get(url)
    if user:
        req.user = user.user
        req.groups = req.user.get_profile().groups.all()
    return req
 def test_session_auth_no_post(self):
     req = RequestFactory().post('/api/')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(not self.auth.authenticate(Request(req)))
     ok_(not req.user.is_authenticated())
Exemplo n.º 11
0
def dump_app(id, **kw):
    from mkt.webapps.api import AppSerializer
    # Because @robhudson told me to.
    # Note: not using storage because all these operations should be local.
    target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
                              str(id / 1000))
    target_file = os.path.join(target_dir, str(id) + '.json')

    try:
        obj = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        task_log.info(u'Webapp does not exist: {0}'.format(id))
        return

    req = RequestFactory().get('/')
    req.user = AnonymousUser()
    req.REGION = RESTOFWORLD

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    task_log.info('Dumping app {0} to {1}'.format(id, target_file))
    res = AppSerializer(obj, context={'request': req}).data
    json.dump(res, open(target_file, 'w'), cls=JSONEncoder)
    return target_file
Exemplo n.º 12
0
 def _create_mocked_tweet_request(self):
     request = RequestFactory().post(
         reverse('customercare.twitter_post'), {
             'reply_to': 1,
             'content': '@foobar try Aurora! #fxhelp'
         })
     request.session = {}
     request.twitter = Mock()
     request.twitter.authed = True
     request.twitter.api = Mock()
     return_value = {
         'id':
         123456790,
         'text':
         '@foobar try Aurora! #fxhelp',
         'created_at':
         datetime.strftime(datetime.utcnow(), '%a %b %d %H:%M:%S +0000 %Y'),
         'user': {
             'lang': 'en',
             'id': 42,
             'screen_name': 'r1cky',
             'profile_image_url': 'http://example.com/profile.jpg',
             'profile_image_url_https': 'https://example.com/profile.jpg',
         }
     }
     request.twitter.api.update_status.return_value = return_value
     credentials = {'screen_name': 'r1cky'}
     request.twitter.api.verify_credentials.return_value = credentials
     request.user = Mock()
     request.user.is_authenticated.return_value = False
     return request
Exemplo n.º 13
0
def req_factory_factory(url, user=None):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory().get(url)
    if user:
        req.user = user.user
        req.groups = req.user.get_profile().groups.all()
    return req
Exemplo n.º 14
0
def dump_app(id, **kw):
    from mkt.webapps.api import AppSerializer
    # Because @robhudson told me to.
    # Note: not using storage because all these operations should be local.
    target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
                              str(id / 1000))
    target_file = os.path.join(target_dir, str(id) + '.json')

    try:
        obj = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        task_log.info(u'Webapp does not exist: {0}'.format(id))
        return

    req = RequestFactory().get('/')
    req.user = AnonymousUser()
    req.REGION = RESTOFWORLD

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    task_log.info('Dumping app {0} to {1}'.format(id, target_file))
    res = AppSerializer(obj, context={'request': req}).data
    json.dump(res, open(target_file, 'w'), cls=JSONEncoder)
    return target_file
Exemplo n.º 15
0
 def _create_mocked_tweet_request(self):
     request = RequestFactory().post(
         reverse('customercare.twitter_post'),
         {'reply_to': 1,
          'content': '@foobar try Aurora! #fxhelp'})
     request.session = {}
     request.twitter = Mock()
     request.twitter.authed = True
     request.twitter.api = Mock()
     return_value = {
         'id': 123456790,
         'text': '@foobar try Aurora! #fxhelp',
         'created_at': datetime.strftime(datetime.utcnow(),
                                         '%a %b %d %H:%M:%S +0000 %Y'),
         'user': {
             'lang': 'en',
             'id': 42,
             'screen_name': 'r1cky',
             'profile_image_url': 'http://example.com/profile.jpg',
             'profile_image_url_https': 'https://example.com/profile.jpg',
         }
     }
     request.twitter.api.update_status.return_value = return_value
     credentials = {'screen_name': 'r1cky'}
     request.twitter.api.verify_credentials.return_value = credentials
     request.user = Mock()
     request.user.is_authenticated.return_value = False
     return request
Exemplo n.º 16
0
 def get_request(self, data=None):
     if data is None:
         data = {}
     request = RequestFactory().get("/", data)
     request.REGION = mkt.regions.RESTOFWORLD
     request.API = True
     request.user = AnonymousUser()
     return request
Exemplo n.º 17
0
 def get_request(self, data=None):
     if data is None:
         data = {}
     request = RequestFactory().get('/', data)
     request.REGION = mkt.regions.RESTOFWORLD
     request.API = True
     request.user = AnonymousUser()
     return request
Exemplo n.º 18
0
 def test_get_username_no_username_field(self):
     req = RequestFactory().get('/')
     req.user = mock.Mock()
     del req.user.USERNAME_FIELD
     req.user.username = '******'
     eq_(get_username(), '<anon>')
     self.middleware.process_request(req)
     eq_(get_username(), 'my-username')
Exemplo n.º 19
0
 def test_get_username_with_username_field(self):
     req = RequestFactory().get('/')
     req.user = mock.Mock()
     req.user.USERNAME_FIELD = 'myfield'
     req.user.myfield = 'my-new-username'
     eq_(get_username(), '<anon>')
     self.middleware.process_request(req)
     eq_(get_username(), 'my-new-username')
Exemplo n.º 20
0
 def test_failed_session_auth(self):
     req = RequestFactory().post(
         '/api/', HTTP_AUTHORIZATION='mkt-shared-secret bogus')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(not self.auth.authenticate(Request(req)))
     ok_(not req.user.is_authenticated())
Exemplo n.º 21
0
    def check_permissions(self):
        req = RequestFactory().get(reverse('comm-thread-detail',
                                           kwargs={'pk': self.thread.pk}))
        req.user = self.user
        req.amo_user = self.profile
        req.groups = req.amo_user.groups.all()

        return ThreadPermission().has_object_permission(
            req, 'comm-thread-detail', self.thread)
Exemplo n.º 22
0
 def process(self, authenticated, view=None, lang='en-US', app='firefox'):
     if not view:
         view = normal_view
     request = RequestFactory().get('/', HTTP_X_PJAX=True)
     request.user = Mock()
     request.APP = amo.APPS[app]
     request.LANG = lang
     request.user.is_authenticated.return_value = authenticated
     return LoginRequiredMiddleware().process_view(request, view, [], {})
Exemplo n.º 23
0
 def test_require_permission(self):
     '''
     Test that user without 'conference.delete_attendee' permission can't access the view
     '''
     perm = Permission.objects.get(pk=1)
     req = RequestFactory()
     req.user = self.user
     req.path = '/'
     rsp = export_csv(req, User.objects.all(), self.export_data,
                      require_permission='auth.add_permission')
     self.assertEqual(rsp.status_code, 302)
     
     u = User.objects.get(pk=self.user.pk)
     u.user_permissions.add(perm)
     req.user = u
     rsp = export_csv(req, User.objects.all(), self.export_data,
                      require_permission='auth.add_permission')
     self.assertEqual(rsp.status_code, 200)
Exemplo n.º 24
0
    def check_permissions(self):
        req = RequestFactory().get(reverse('comm-thread-detail',
                                           kwargs={'pk': self.thread.pk}))
        req.user = self.user
        req.amo_user = self.profile
        req.groups = req.amo_user.groups.all()

        return ThreadPermission().has_object_permission(
            req, 'comm-thread-detail', self.thread)
 def test_failed_session_auth(self):
     req = RequestFactory().post(
         '/api/',
         HTTP_AUTHORIZATION='mkt-shared-secret bogus')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(not self.auth.authenticate(Request(req)))
     ok_(not req.user.is_authenticated())
Exemplo n.º 26
0
    def test_multiple_passes(self):
        req = RequestFactory().get('/')
        req.user = AnonymousUser()
        self.resource._meta.authentication = (
            authentication.SharedSecretAuthentication(),
            # Optional auth passes because there are not auth headers.
            authentication.OptionalOAuthAuthentication())

        eq_(self.resource.is_authenticated(req), None)
Exemplo n.º 27
0
    def test_multiple_passes(self):
        req = RequestFactory().get('/')
        req.user = AnonymousUser()
        self.resource._meta.authentication = (
                authentication.SharedSecretAuthentication(),
                # Optional auth passes because there are not auth headers.
                authentication.OptionalOAuthAuthentication())

        eq_(self.resource.is_authenticated(req), None)
Exemplo n.º 28
0
 def process(self, authenticated, view=None, lang='en-US', app='firefox'):
     if not view:
         view = normal_view
     request = RequestFactory().get('/', HTTP_X_PJAX=True)
     request.user = Mock()
     request.APP = amo.APPS[app]
     request.LANG = lang
     request.user.is_authenticated.return_value = authenticated
     return LoginRequiredMiddleware().process_view(request, view, [], {})
Exemplo n.º 29
0
def req_factory_factory(url='', user=None, post=False, data=None, **kwargs):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory()
    if post:
        req = req.post(url, data or {})
    else:
        req = req.get(url, data or {})
    if user:
        req.user = UserProfile.objects.get(id=user.id)
        req.groups = user.groups.all()
    else:
        req.user = AnonymousUser()
    req.check_ownership = partial(check_ownership, req)
    req.REGION = kwargs.pop('region', mkt.regions.REGIONS_CHOICES[0][1])
    req.API_VERSION = 2

    for key in kwargs:
        setattr(req, key, kwargs[key])
    return req
Exemplo n.º 30
0
def req_factory_factory(url='', user=None, post=False, data=None, **kwargs):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory()
    if post:
        req = req.post(url, data or {})
    else:
        req = req.get(url, data or {})
    if user:
        req.user = UserProfile.objects.get(id=user.id)
        req.groups = user.groups.all()
    else:
        req.user = AnonymousUser()
    req.check_ownership = partial(check_ownership, req)
    req.REGION = kwargs.pop('region', mkt.regions.REGIONS_CHOICES[0][1])
    req.API_VERSION = 2

    for key in kwargs:
        setattr(req, key, kwargs[key])
    return req
 def test_session_auth_query(self):
     req = RequestFactory().post(
         '/api/[email protected],56b6f1a3dd735d962c56ce7d8f46e02ec1d4748d'
         '2c00c407d75f0969d08bb9c68c31b3371aa8130317815c89e5072e31bb94b4121'
         'c5c165f3515838d4d6c60c4,165d631d3c3045458b4516242dad7ae')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(self.auth.authenticate(Request(req)))
     ok_(req.user.is_authenticated())
     eq_(self.profile.pk, req.user.pk)
Exemplo n.º 32
0
 def test_session_auth_query(self):
     req = RequestFactory().post(
         '/api/[email protected],56b6f1a3dd735d962c56ce7d8f46e02ec1d4748d'
         '2c00c407d75f0969d08bb9c68c31b3371aa8130317815c89e5072e31bb94b4121'
         'c5c165f3515838d4d6c60c4,165d631d3c3045458b4516242dad7ae')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(self.auth.authenticate(Request(req)))
     ok_(req.user.is_authenticated())
     eq_(self.profile.pk, req.user.pk)
 def call(self, client=None):
     client = client or OAuthClient(self.access)
     # Make a fake POST somewhere. We use POST in order to properly test db
     # pinning after auth.
     url = absolutify('/api/whatever')
     req = RequestFactory().post(url,
         HTTP_HOST='testserver',
         HTTP_AUTHORIZATION=client.sign('POST', url)[1]['Authorization'])
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     return req
Exemplo n.º 34
0
 def test_waffle_fallback_anon(self):
     flag = waffle.models.Flag.objects.get(name='override-app-purchase')
     flag.everyone = True
     flag.save()
     self.make_premium(self.app, price='0.99')
     req = RequestFactory().get('/')
     req.user = AnonymousUser()
     with self.settings(PURCHASE_LIMITED=True):
         res = self.serialize(self.app, region=regions.US.id, request=req)
     eq_(res['price'], Decimal('0.99'))
     eq_(res['price_locale'], '$0.99')
     eq_(res['payment_required'], True)
Exemplo n.º 35
0
 def test_waffle_fallback_anon(self):
     flag = waffle.models.Flag.objects.get(name='override-app-purchase')
     flag.everyone = True
     flag.save()
     self.make_premium(self.app, price='0.99')
     req = RequestFactory().get('/')
     req.user = AnonymousUser()
     with self.settings(PURCHASE_LIMITED=True):
         res = self.serialize(self.app, region=regions.US.id, request=req)
     eq_(res['price'], Decimal('0.99'))
     eq_(res['price_locale'], '$0.99')
     eq_(res['payment_required'], True)
Exemplo n.º 36
0
 def test_waffle_fallback_anon(self):
     flag = waffle.models.Flag.objects.get(name='allow-paid-app-search')
     flag.everyone = True
     flag.save()
     self.make_premium(self.app, price='0.99')
     req = RequestFactory().get('/')
     req.user = AnonymousUser()
     with self.settings(PURCHASE_ENABLED_REGIONS=[]):
         res = app_to_dict(self.app, region=regions.US.id, request=req)
     eq_(res['price'], Decimal('0.99'))
     eq_(res['price_locale'], '$0.99')
     eq_(res['payment_required'], True)
Exemplo n.º 37
0
def req_factory_factory(url, user=None, post=False, data=None):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory()
    if post:
        req = req.post(url, data or {})
    else:
        req = req.get(url, data or {})
    if user:
        req.amo_user = user
        req.user = user.user
        req.groups = req.user.get_profile().groups.all()
    return req
Exemplo n.º 38
0
def req_factory_factory(url, user=None, post=False, data=None):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory()
    if post:
        req = req.post(url, data or {})
    else:
        req = req.get(url, data or {})
    if user:
        req.amo_user = UserProfile.objects.get(id=user.id)
        req.user = user
        req.groups = user.groups.all()
    req.check_ownership = partial(check_ownership, req)
    return req
Exemplo n.º 39
0
 def call(self, client=None):
     client = client or OAuthClient(self.access)
     # Make a fake POST somewhere. We use POST in order to properly test db
     # pinning after auth.
     url = absolutify('/api/whatever')
     req = RequestFactory().post(url,
                                 HTTP_HOST='testserver',
                                 HTTP_AUTHORIZATION=client.sign(
                                     'POST', url)[1]['Authorization'])
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     return req
Exemplo n.º 40
0
 def test_fail(self):
     url = absolutify(reverse('app-list'))
     url, auth_header = self._oauth_request_info(
         url, client_key=self.access.key,
         client_secret="none")
     auth = authentication.RestOAuthAuthentication()
     req = RequestFactory().get(
         url, HTTP_HOST='testserver',
         HTTP_AUTHORIZATION=auth_header)
     req.API = True
     req.user = AnonymousUser()
     RestOAuthMiddleware().process_request(req)
     ok_(not auth.authenticate(Request(req)))
     ok_(not req.user.is_authenticated())
Exemplo n.º 41
0
    def test_waffle_fallback(self):
        self.make_premium(self.app, price="0.99")
        flag = waffle.models.Flag.objects.get(name="allow-paid-app-search")
        flag.everyone = None
        flag.users.add(self.profile.user)
        flag.save()

        req = RequestFactory().get("/")
        req.user = self.profile.user
        with self.settings(PURCHASE_ENABLED_REGIONS=[]):
            res = app_to_dict(self.app, region=regions.US.id, request=req)
        eq_(res["price"], Decimal("0.99"))
        eq_(res["price_locale"], "$0.99")
        eq_(res["payment_required"], True)
Exemplo n.º 42
0
def req_factory_factory(url, user=None, post=False, data=None):
    """Creates a request factory, logged in with the user."""
    req = RequestFactory()
    if post:
        req = req.post(url, data or {})
    else:
        req = req.get(url, data or {})
    if user:
        req.amo_user = RequestUser.objects.get(id=user.id)
        req.user = user.user
        req.groups = req.user.get_profile().groups.all()
    req.APP = None
    req.check_ownership = partial(check_ownership, req)
    return req
Exemplo n.º 43
0
 def test_session_auth(self):
     req = RequestFactory().post('/api/',
                                 HTTP_AUTHORIZATION='mkt-shared-secret '
                                 '[email protected],56b6f1a3dd735d962c56'
                                 'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
                                 '9c68c31b3371aa8130317815c89e5072e31bb94b4'
                                 '121c5c165f3515838d4d6c60c4,165d631d3c3045'
                                 '458b4516242dad7ae')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(self.auth.authenticate(Request(req)))
     ok_(req.user.is_authenticated())
     eq_(self.profile.pk, req.user.pk)
Exemplo n.º 44
0
    def test_waffle_fallback(self):
        self.make_premium(self.app, price='0.99')
        flag = waffle.models.Flag.objects.get(name='override-app-purchase')
        flag.everyone = None
        flag.users.add(self.profile.user)
        flag.save()

        req = RequestFactory().get('/')
        req.user = self.profile.user
        with self.settings(PURCHASE_LIMITED=True):
            res = app_to_dict(self.app, region=regions.US.id, request=req)
        eq_(res['price'], Decimal('0.99'))
        eq_(res['price_locale'], '$0.99')
        eq_(res['payment_required'], True)
Exemplo n.º 45
0
    def _test_auth(self, pk, is_authenticated, two_legged=True):
        request = RequestFactory().get('/en-US/firefox/2/api/2/user/',
                                       data={'authenticate_as': pk})
        request.user = None

        def alter_request(*args, **kw):
            request.user = self.admin
            return True
        is_authenticated.return_value = True
        is_authenticated.side_effect = alter_request

        auth = AMOOAuthAuthentication()
        auth.two_legged = two_legged
        auth.is_authenticated(request)
        return request
 def test_session_auth(self):
     req = RequestFactory().post(
         '/api/',
         HTTP_AUTHORIZATION='mkt-shared-secret '
         '[email protected],56b6f1a3dd735d962c56'
         'ce7d8f46e02ec1d4748d2c00c407d75f0969d08bb'
         '9c68c31b3371aa8130317815c89e5072e31bb94b4'
         '121c5c165f3515838d4d6c60c4,165d631d3c3045'
         '458b4516242dad7ae')
     req.user = AnonymousUser()
     for m in self.middlewares:
         m().process_request(req)
     ok_(self.auth.authenticate(Request(req)))
     ok_(req.user.is_authenticated())
     eq_(self.profile.pk, req.user.pk)
Exemplo n.º 47
0
    def _test_auth(self, pk, is_authenticated, two_legged=True):
        request = RequestFactory().get('/en-US/firefox/2/api/2/user/',
                                       data={'authenticate_as': pk})
        request.user = None

        def alter_request(*args, **kw):
            request.user = self.admin
            return True
        is_authenticated.return_value = True
        is_authenticated.side_effect = alter_request

        auth = AMOOAuthAuthentication()
        auth.two_legged = two_legged
        auth.is_authenticated(request)
        return request
Exemplo n.º 48
0
 def test_bad_access_token(self):
     url = absolutify(reverse('app-list'))
     Token.generate_new(ACCESS_TOKEN, creds=self.access, user=self.user2)
     url, auth_header = self._oauth_request_info(
         url, client_key=self.access.key,
         client_secret=self.access.secret, resource_owner_key=generate(),
         resource_owner_secret=generate())
     auth = authentication.RestOAuthAuthentication()
     req = RequestFactory().get(
         url, HTTP_HOST='testserver',
         HTTP_AUTHORIZATION=auth_header)
     req.API = True
     req.user = AnonymousUser()
     RestOAuthMiddleware().process_request(req)
     ok_(not auth.authenticate(Request(req)))
     ok_(not req.user.is_authenticated())
Exemplo n.º 49
0
    def test_multiple_fails(self):
        client = OAuthClient(Mock(key='foo', secret='bar'))
        req = RequestFactory().get('/',
                HTTP_HOST='api',
                HTTP_AUTHORIZATION=client.header('GET', 'http://foo/'))
        req.user = AnonymousUser()
        next_auth = Mock()
        self.resource._meta.authentication = (
                # OAuth fails because there are bogus auth headers.
                authentication.OAuthAuthentication(),
                next_auth)

        with self.assertRaises(ImmediateHttpResponse):
            eq_(self.resource.is_authenticated(req), None)
        # This never even got called.
        ok_(not next_auth.is_authenticated.called)
Exemplo n.º 50
0
    def test_post_reply(self):
        # Create a Tweet to reply to.
        Tweet.objects.create(pk=1,
                             raw_json='{}',
                             locale='en',
                             created=datetime.now())

        # Create a request and mock all the required properties and methods.
        request = RequestFactory().post(
            reverse('customercare.twitter_post'), {
                'reply_to': 1,
                'content': '@foobar try Aurora! #fxhelp'
            })
        request.session = {}
        request.twitter = Mock()
        request.twitter.authed = True
        request.twitter.api = Mock()
        return_value = {
            'id':
            123456790,
            'text':
            '@foobar try Aurora! #fxhelp',
            'created_at':
            datetime.strftime(datetime.utcnow(), '%a %b %d %H:%M:%S +0000 %Y'),
            'user': {
                'lang': 'en',
                'id': 42,
                'screen_name': 'r1cky',
                'profile_image_url': 'http://example.com/profile.jpg',
                'profile_image_url_https': 'https://example.com/profile.jpg',
            }
        }
        request.twitter.api.update_status.return_value = return_value
        credentials = {'screen_name': 'r1cky'}
        request.twitter.api.verify_credentials.return_value = credentials
        request.user = Mock()
        request.user.is_authenticated.return_value = False

        # Pass the request to the view and verify response.
        response = twitter_post(request)
        eq_(200, response.status_code)

        # Verify the reply was inserted with the right data.
        reply = Reply.objects.all()[0]
        eq_('r1cky', reply.twitter_username)
        eq_(1, reply.reply_to_tweet_id)
        eq_('@foobar try Aurora! #fxhelp', json.loads(reply.raw_json)['text'])
Exemplo n.º 51
0
    def test_multiple_fails(self):
        client = OAuthClient(Mock(key='foo', secret='bar'))
        req = RequestFactory().get('/',
                                   HTTP_HOST='api',
                                   HTTP_AUTHORIZATION=client.header(
                                       'GET', 'http://foo/'))
        req.user = AnonymousUser()
        next_auth = Mock()
        self.resource._meta.authentication = (
            # OAuth fails because there are bogus auth headers.
            authentication.OAuthAuthentication(),
            next_auth)

        with self.assertRaises(ImmediateHttpResponse):
            eq_(self.resource.is_authenticated(req), None)
        # This never even got called.
        ok_(not next_auth.is_authenticated.called)
Exemplo n.º 52
0
 def test_session_auth_no_post(self):
     req = RequestFactory().post('/')
     req.user = self.profile.user
     assert not self.auth.is_authenticated(req)
Exemplo n.º 53
0
def get():
    request = RequestFactory().get('/foo')
    request.user = AnonymousUser()
    return request
Exemplo n.º 54
0
 def test_session_auth_no_post(self):
     req = RequestFactory().post('/api/')
     for m in self.middlewares:
         m().process_request(req)
     req.user = self.profile.user
     assert not self.auth.authenticate(Request(req))
Exemplo n.º 55
0
def get(**kw):
    request = RequestFactory().get('/foo', data=kw)
    request.user = AnonymousUser()
    return request