def test_can_save_parent_then_child(self):
        response = yield self.http_client.fetch(
            self.get_url('/parent/'),
            method='POST',
            body='name=Bernardo%20Heynemann'
        )

        expect(response.code).to_equal(200)
        obj = utils.loads(response.body)
        expect(obj['name']).to_equal('Bernardo Heynemann')
        expect(response.headers).to_include('X-Created-Id')
        pk = response.headers['X-Created-Id']

        response = yield self.http_client.fetch(
            self.get_url('/parent/%s/child/' % pk),
            method='POST',
            body='first_name=Rodrigo&last_name=Lucena'
        )

        expect(response.code).to_equal(200)
        obj = utils.loads(response.body)
        expect(obj['first_name']).to_equal('Rodrigo')
        expect(obj['last_name']).to_equal('Lucena')

        parent = models.Parent.objects.get(id=pk)
        expect(parent.name).to_equal('Bernardo Heynemann')
        expect(parent.child).not_to_be_null()
        expect(parent.child.first_name).to_equal('Rodrigo')
        expect(parent.child.last_name).to_equal('Lucena')
    def test_can_save_parent_with_grandchild(self):
        response = yield self.http_client.fetch(
            self.get_url('/parent/'),
            method='POST',
            body='name=Bernardo%20Heynemann'
            '&child.first_name=Rodrigo'
            '&child.last_name=Lucena'
            '&child.child.first_name=Polo'
            '&child.child.last_name=Norte'
        )

        expect(response.code).to_equal(200)
        obj = utils.loads(response.body)
        expect(obj['name']).to_equal('Bernardo Heynemann')

        expect(obj['child']).not_to_be_null()
        expect(obj['child']['first_name']).to_equal('Rodrigo')
        expect(obj['child']['child']).not_to_be_null()
        expect(obj['child']['child']['first_name']).to_equal('Polo')

        expect(response.headers).to_include('X-Created-Id')
        expect(response.headers).to_include('location')

        parent = models.Parent.objects.get(id=response.headers['X-Created-Id'])
        expect(parent.name).to_equal('Bernardo Heynemann')

        expect(parent.child).not_to_be_null()
        expect(parent.child.first_name).to_equal('Rodrigo')
        expect(parent.child.last_name).to_equal('Lucena')

        expect(parent.child.child).not_to_be_null()
        expect(parent.child.child.first_name).to_equal('Polo')
        expect(parent.child.child.last_name).to_equal('Norte')
Esempio n. 3
0
    def test_can_signout_when_logged_out(self):
        response = yield self.http_client.fetch(
            self.get_url('/auth/signout/'), method='POST', body='',
        )

        expect(response.code).to_equal(200)
        expect(utils.loads(response.body)).to_equal({'loggedOut': True})
Esempio n. 4
0
    def authenticate(self, access_token, proxy_info=None, post_data=None):
        '''
        Try to get Google user info and returns it if
        the given access_token get`s a valid user info in a string
        json format. If the response was not an status code 200 or
        get an error on Json, None was returned.

        Example of return on success::

            {
                id: "1234567890abcdef",
                email: "*****@*****.**",
                name: "Ricardo L. Dani",
                provider: "google"
            }
        '''

        response = yield self._fetch_userinfo(access_token, proxy_info)

        if response.code == 200:
            body = utils.loads(response.body)
            if not body.get('error'):
                raise gen.Return({
                    'email': body.get("email"),
                    'name': body.get("name"),
                    'id': body.get("id"),
                    'provider': self.get_name()
                })

        raise gen.Return(None)
Esempio n. 5
0
    def post(self):
        '''
        Try to authenticate user with the access_token POST data.
        If the `self.authenticate` method returns the user, create a JSON
        Web Token (JWT) and set a `cookie_name` cookie with the encoded
        value. Otherwise returns a unauthorized request.
        '''
        post_data = utils.loads(self.request.body)
        access_token = post_data.get('access_token')

        user = yield self._authenticate(access_token)
        if user:
            payload = dict(
                sub=user['id'],
                iss=self.provider.get_name(),
                token=access_token,
                iat=datetime.utcnow(),
                exp=datetime.utcnow() + timedelta(seconds=self.expiration)
            )
            auth_token = self.jwt.encode(payload)

            self.set_cookie(self.cookie_name, auth_token)
            self.write(dict(authenticated=True))
        else:
            self.__set_unauthorized()
Esempio n. 6
0
    def test_can_send_signal_on_post_authentication(self):

        test_result = {}

        @signals.authorized_user.connect
        def test_signal(provider, user_data=None, handler=None):
            test_result['provider'] = 'google'
            expect(provider).to_equal('google')
            expect(user_data).to_equal({
                "authenticated": True,
                "provider": "google",
                "email": "*****@*****.**", "name": "Teste", "id": "56789"
            })
            user_data['something'] = 'else'

        with patch.object(GoogleProvider, '_fetch_userinfo') as provider_mock:
            result = gen.Future()
            response_mock = Mock(code=200, body=(
                '{"email":"*****@*****.**", "name":"Teste", "id":"56789"}'
            ))
            result.set_result(response_mock)
            provider_mock.return_value = result
            response = yield self.http_client.fetch(
                self.get_url('/auth/signin/'), method='POST',
                body=utils.dumps({
                    'access_token': 'VALID-TOKEN', 'provider': 'google'
                })
            )
            expect(response.code).to_equal(200)
            data = utils.loads(response.body)
            expect(data['authenticated']).to_be_true()
            expect(data['something']).to_equal('else')
            expect(test_result).to_include('provider')
Esempio n. 7
0
    def dump_instance(self, instance):
        if instance is None:
            return {}

        method = getattr(instance, 'to_dict', None)

        if method:
            return method()

        return utils.loads(instance.to_json())
Esempio n. 8
0
    def test_can_signout_when_logged_in(self):
        response = yield self.http_client.fetch(
            self.get_url('/auth/signout/'), method='POST', body='',
            headers={'Cookie': self.mock_auth_cookie(
                user_id=0, provider='mock', data={'id': 0}
            )}
        )

        expect(response.code).to_equal(200)
        expect(utils.loads(response.body)).to_equal({'loggedOut': True})
    def test_can_create_other_user(self):
        response = yield self.http_client.fetch(
            self.get_url('/other_user/'),
            method='POST',
            body='name=Bernardo%20Heynemann&[email protected]'
        )

        expect(response.code).to_equal(200)
        obj = utils.loads(response.body)
        expect(obj['user']).to_equal('Bernardo Heynemann <*****@*****.**>')
        expect(response.headers).to_include('X-Created-Id')
        expect(response.headers['X-Created-Id']).to_equal('bernardo-heynemann')
        expect(response.headers).to_include('location')

        expected_url = '/other_user/%s/' % response.headers['X-Created-Id']
        expect(response.headers['location']).to_equal(expected_url)
    def test_can_get_addresses_for_user_in_team(self):
        address = models.Address(street='Somewhere Else')
        address.save()
        user = models.User(name='Bernardo Heynemann', email='*****@*****.**', addresses=[address])
        user.save()
        team = models.Team(name="test-team", users=[user])
        team.save()

        response = yield self.http_client.fetch(
            self.get_url('/team/%s/users/%s/addresses' % (str(team.id), str(user.id))),
        )

        expect(response.code).to_equal(200)
        expect(response.body).not_to_be_empty()

        obj = utils.loads(response.body)
        expect(obj).to_length(1)
        expect(obj[0]['street']).to_equal(address.street)
    def test_can_get_users_list_in_team(self):
        user = models.User(name='Bernardo Heynemann', email='*****@*****.**')
        user.save()
        user2 = models.User(name='Rafael Floriano', email='*****@*****.**')
        user2.save()
        team = models.Team.objects.create(name="test-team", users=[user, user2])

        response = yield self.http_client.fetch(
            self.get_url('/team/%s/users/' % str(team.id)),
        )

        expect(response.code).to_equal(200)
        expect(response.body).not_to_be_empty()

        obj = utils.loads(response.body)
        expect(obj).to_length(2)
        expect(obj[0]['name']).to_equal('Bernardo Heynemann')
        expect(obj[0]['email']).to_equal('*****@*****.**')
        expect(obj[1]['name']).to_equal('Rafael Floriano')
        expect(obj[1]['email']).to_equal('*****@*****.**')
Esempio n. 12
0
    def test_can_authenticate_a_user_with_valid_google_plus_token(self):
        with patch.object(GoogleProvider, '_fetch_userinfo') as provider_mock:
            result = gen.Future()
            response_mock = Mock(code=200, body=(
                '{"email":"*****@*****.**", "name":"Teste", "id":"56789"}'
            ))
            result.set_result(response_mock)
            provider_mock.return_value = result
            try:
                response = yield self.http_client.fetch(
                    self.get_url('/authenticate/google/'), method='POST',
                    body=utils.dumps({
                        'access_token': 'VALID-TOKEN',
                    })
                )
            except HTTPError as e:
                response = e.response

            expect(response.code).to_equal(200)
            expect(utils.loads(response.body)['authenticated']).to_be_true()
Esempio n. 13
0
    def post(self):
        '''
        Try to authenticate user with the access_token POST data.
        If the `self.authenticate` method returns the user, create a JSON
        Web Token (JWT) and set a `cookie_name` cookie with the encoded
        value. Otherwise returns a unauthorized request.
        '''
        post_data = utils.loads(self.request.body)
        access_token = post_data.get('access_token')
        provider_name = post_data.get('provider')

        provider = self.providers.get(provider_name, None)
        if provider is None:
            AuthHandler._set_unauthorized(self)

        user_data = yield provider.authenticate(
            access_token, self.application.authentication_options['proxy_info'], post_data=post_data
        )
        if user_data:
            payload = dict(
                sub=user_data['id'],
                data=user_data,
                iss=provider_name,
                token=access_token,
                iat=datetime.utcnow(),
                exp=datetime.utcnow() + timedelta(seconds=self.expiration)
            )
            auth_token = self.jwt.encode(payload)

            user_data['authenticated'] = True
            signals.authorized_user.send(
                provider_name, user_data=user_data, handler=self
            )
            self.set_cookie(self.cookie_name, auth_token)
            self.write(user_data)
        else:
            signals.unauthorized_user.send(provider_name, handler=self)
            AuthHandler._set_unauthorized(self)
Esempio n. 14
0
    def test_can_fetch_userinfo_with_proxy_credentials(self):
        with patch.object(GoogleProvider, '_fetch_userinfo') as provider_mock:
            result = gen.Future()
            response_mock = Mock(code=200, body=(
                '{"email":"*****@*****.**", "name":"teste", "id":"56789"}'
            ))
            result.set_result(response_mock)
            provider_mock.return_value = result
            try:
                response = yield self.http_client.fetch(
                    self.get_url('/auth/signin/'), method='POST',
                    body=utils.dumps({
                        'access_token': 'VALID-TOKEN', 'provider': 'google'
                    })
                )
            except HTTPError as e:
                response = e.response

            expect(provider_mock.call_args[0][1]).to_equal(
                {'proxy_port': '666', 'proxy_username': '******',
                 'proxy_password': '******', 'proxy_host': '10.10.10.10'}
            )
            expect(response.code).to_equal(200)
            expect(utils.loads(response.body)['authenticated']).to_be_true()
def load_json(json_string):
    try:
        return utils.loads(json_string)
    except ValueError:
        return utils.loads(json_string.decode('utf-8'))