Пример #1
0
    def test_get_user(self):
        """get_user() makes a GET request to /Users/<id>"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.get_user('foo')
        m.assert_called_with(urljoin('/Users', 'foo'), 'GET')
Пример #2
0
    def oauth_login():
        """Called at the end of the oauth flow.  We'll receive an auth code from UAA and use it to
        retrieve a bearer token that we can use to actually do stuff
        """

        uaac = UAAClient(app.config['UAA_BASE_URL'], None, verify_tls=app.config['VERIFY_TLS'])
        token = uaac.oauth_token(request.args['code'], app.config['UAA_CLIENT_ID'], app.config['UAA_CLIENT_SECRET'])

        session['UAA_TOKEN'] = token['access_token']
        session['UAA_TOKEN_EXPIRES'] = datetime.utcnow() + timedelta(seconds=token['expires_in'])
        session['UAA_TOKEN_SCOPES'] = token['scope'].split(' ')

        return redirect(url_for('ui.index'))
Пример #3
0
    def have_uaa_token():
        """Before each request, make sure we have a valid token from UAA.

        If we don't send them to UAA to start the oauth process.

        Technically we should bounce them through the renew token process if we already have one,
        but this app will be used sparingly, so it's fine to push them back through the authorize flow
        each time we need to renew our token.

        """

        # don't authenticate the oauth code receiver, or we'll never get the code back from UAA
        if request.endpoint and request.endpoint == 'oauth_login':
            return

        # check our token, and expirary date
        token = session.get('UAA_TOKEN', None)
        token_expires = session.get('UAA_TOKEN_EXPIRES', None)

        # if all looks good, setup the client
        if token and token_expires and token_expires > datetime.utcnow():
            g.uaac = UAAClient(app.config['UAA_BASE_URL'],
                               session['UAA_TOKEN'],
                               verify_tls=app.config['VERIFY_TLS'])
        else:
            # if not forget the token, it's bad (if we have one)
            session.clear()

            # if we aren't an API request, then start the oauth flow
            # if we are, do nothing, the API will raise a 403, when g.uaac doesn't exist
            if not request.endpoint.startswith('api'):
                return redirect('{0}/oauth/authorize?client_id={1}'.format(
                    app.config['UAA_BASE_URL'], app.config['UAA_CLIENT_ID']))
Пример #4
0
    def oauth_login():
        """Called at the end of the oauth flow.  We'll receive an auth code from UAA and use it to
        retrieve a bearer token that we can use to actually do stuff
        """

        uaac = UAAClient(app.config['UAA_BASE_URL'],
                         None,
                         verify_tls=app.config['VERIFY_TLS'])
        token = uaac.oauth_token(request.args['code'],
                                 app.config['UAA_CLIENT_ID'],
                                 app.config['UAA_CLIENT_SECRET'])

        session['UAA_TOKEN'] = token['access_token']
        session['UAA_TOKEN_EXPIRES'] = datetime.utcnow() + timedelta(
            seconds=token['expires_in'])
        session['UAA_TOKEN_SCOPES'] = token['scope'].split(' ')

        return redirect(url_for('ui.index'))
Пример #5
0
    def test_request_bad(self, requests):
        """UAAError is reaised when it occurs"""

        r = Mock()
        r.status_code = 500
        r.text = json.dumps({'error_description': 'oh no'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', True)

        with self.assertRaises(UAAError):
            uaac._request('/bar', 'GET')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params=None,
            auth=None,
            verify=True
        )
Пример #6
0
    def test_oauth_token(self):
        """oauth_token() makes a POST to /oauth/token with the appropriate headers and query params"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.oauth_token('foo', 'bar', 'baz')

        args, kwargs = m.call_args

        assert args == ('/oauth/token', 'POST')

        assert kwargs['params'] == {
            'code': 'foo',
            'grant_type': 'authorization_code',
            'response_type': 'token'
        }

        assert isinstance(kwargs['auth'], HTTPBasicAuth)
        assert kwargs['auth'].username == 'bar'
        assert kwargs['auth'].password == 'baz'
Пример #7
0
    def test_put_user(self):
        """put_user() makes a PUT request to /Users/<id> with appropriate headers"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        user = {
            'id': 'foo',
            'meta': {
                'version': '123'
            }
        }

        uaac.put_user(user)

        m.assert_called_with(
            urljoin('/Users', 'foo'),
            'PUT',
            body=user,
            headers={'If-Match': '123'}
        )
Пример #8
0
    def test_request_post_body(self, requests):
        """Body is included in request if provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.post.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'POST', body='hi')

        requests.post.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json='hi',
            params=None,
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Пример #9
0
    def test_request_get_auth(self, requests):
        """Auth value is passed directly to requests"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET', auth='this should be basic')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={},
            json=None,
            params=None,
            auth='this should be basic',
            verify=False
        )

        assert resp['test'] == 'value'
Пример #10
0
    def test_request_get_params(self, requests):
        """Query string is sent if params are provided"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET', params={'omg': 'lol'})

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params={'omg': 'lol'},
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Пример #11
0
    def test_request_get_insecure(self, requests):
        """Insecure GET request is made"""

        r = Mock()
        r.status_code = 200
        r.text = json.dumps({'test': 'value'})
        requests.get.return_value = r

        uaac = UAAClient('http://example.com', 'foo', False)

        resp = uaac._request('/bar', 'GET')

        requests.get.assert_called_with(
            'http://example.com/bar',
            headers={'Authorization': 'Bearer foo'},
            json=None,
            params=None,
            auth=None,
            verify=False
        )

        assert resp['test'] == 'value'
Пример #12
0
    def test_users(self):
        """users() makes a GET request to /Users"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.users()
        m.assert_called_with('/Users', 'GET', params=None)

        uaac.users('test filter')
        m.assert_called_with('/Users', 'GET', params={'filter': 'test filter'})
Пример #13
0
    def test_idps(self):
        """idps() makes a GET request to /identity-providers"""

        uaac = UAAClient('http://example.com', 'foo', False)
        m = Mock()
        uaac._request = m

        uaac.idps(active_only=True)
        m.assert_called_with('/identity-providers', 'GET', params={'active_only': 'true'})

        uaac.idps(active_only=False)
        m.assert_called_with('/identity-providers', 'GET', params={'active_only': 'false'})