コード例 #1
0
def test_authorized_signup_valid_user(app, example_globus):
    """Test authorized callback with sign-up."""

    with app.test_client() as c:
        # User login with email 'info'
        ioc = app.extensions['oauthlib.client']

        # Ensure remote apps have been loaded (due to before first request)
        resp = c.get(url_for('invenio_oauthclient.login', remote_app='globus'))
        assert resp.status_code == 302

        example_info, example_token, example_account_id = example_globus
        mock_response(app.extensions['oauthlib.client'], 'globus',
                      example_token)
        example_info.update(example_account_id)
        oauth_resp = OAuthResponse(resp=None,
                                   content=json.dumps(example_info),
                                   content_type='application/json')
        mock_remote_get(ioc, 'globus', oauth_resp)

        # User authorized the requests and is redirect back
        resp = c.get(
            url_for('invenio_oauthclient.authorized',
                    remote_app='globus',
                    code='test',
                    state=_get_state()))
        assert resp.status_code == 302
        assert resp.location == ('http://localhost/account/settings/' +
                                 'linkedaccounts/')

        # Assert database state (Sign-up complete)
        user = User.query.filter_by(email='*****@*****.**').one()
        remote = RemoteAccount.query.filter_by(user_id=user.id).one()
        RemoteToken.query.filter_by(id_remote_account=remote.id).one()
        assert user.active

        # Disconnect link
        resp = c.get(
            url_for('invenio_oauthclient.disconnect', remote_app='globus'))
        assert resp.status_code == 302

        # User exists
        user = User.query.filter_by(email='*****@*****.**').one()
        assert 0 == UserIdentity.query.filter_by(method='orcid',
                                                 id_user=user.id,
                                                 id='globususer').count()
        assert RemoteAccount.query.filter_by(user_id=user.id).count() == 0
        assert RemoteToken.query.count() == 0

        # User authorized the requests and is redirect back
        resp = c.get(
            url_for('invenio_oauthclient.authorized',
                    remote_app='globus',
                    code='test',
                    state=_get_state()))
        assert resp.status_code == 302
        assert resp.location == ('http://localhost/' +
                                 'account/settings/linkedaccounts/')

        # check that exist only one account
        user = User.query.filter_by(email='*****@*****.**').one()
        assert User.query.count() == 1
コード例 #2
0
    def request(
        self,
        url,
        data=None,
        headers=None,
        format="urlencoded",
        method="GET",
        content_type=None,
        token=None,
        discord=False,
    ):
        """
        Sends a request to the remote server with OAuth tokens attached.

        :param data: the data to be sent to the server.
        :param headers: an optional dictionary of headers.
        :param format: the format for the `data`. Can be `urlencoded` for
                       URL encoded data or `json` for JSON.
        :param method: the HTTP request method to use.
        :param content_type: an optional content type. If a content type
                             is provided, the data is passed as it, and
                             the `format` is ignored.
        :param token: an optional token to pass, if it is None, token will
                      be generated by tokengetter.
        """

        headers = dict(headers or {})
        if token is None:
            token = self.get_request_token()

        client = self.make_client(token)
        url = self.expand_url(url)
        if method == "GET":
            assert format == "urlencoded"
            if data:
                url = add_params_to_uri(url, data)
                data = None
        else:
            if content_type is None:
                data, content_type = OAuth.encode_request_data(data, format)
            if content_type is not None:
                headers["Content-Type"] = content_type

        if self.request_token_url:
            # oauth1
            uri, headers, body = client.sign(url,
                                             http_method=method,
                                             body=data,
                                             headers=headers)
        else:
            # oauth2
            uri, headers, body = client.add_token(url,
                                                  http_method=method,
                                                  body=data,
                                                  headers=headers)

        if hasattr(self, "pre_request"):
            # This is designed for some rubbish services like weibo.
            # Since they don't follow the standards, we need to
            # change the uri, headers, or body.
            uri, headers, body = self.pre_request(uri, headers, body)

        if body:
            data = to_bytes(body, self.encoding)
        else:
            data = None
        if discord:
            response = requests.request(method,
                                        uri,
                                        headers=headers,
                                        data=to_bytes(body, self.encoding))
            if response.status_code not in (200, 201):
                raise OAuthException("Invalid response from %s" % self.name,
                                     type="invalid_response",
                                     data=data)
            return jsonify(response.text.encode("utf8"))

        resp, content = self.http_request(uri,
                                          headers,
                                          data=to_bytes(body, self.encoding),
                                          method=method)
        return OAuthResponse(resp, content, self.content_type)
コード例 #3
0
def test_authorized_already_authenticated(models_fixture, example_globus):
    """Test authorized callback with sign-up."""
    app = models_fixture

    datastore = app.extensions['invenio-accounts'].datastore
    login_manager = app.login_manager

    existing_email = '*****@*****.**'
    user = datastore.find_user(email=existing_email)

    @login_manager.user_loader
    def load_user(user_id):
        return user

    @app.route('/foo_login')
    def login():
        login_user(user)
        return 'Logged In'

    with app.test_client() as client:

        # make a fake login (using my login function)
        client.get('/foo_login', follow_redirects=True)
        # Ensure remote apps have been loaded (due to before first request)
        client.get(url_for('invenio_oauthclient.login', remote_app='globus'))

        ioc = app.extensions['oauthlib.client']
        example_info, example_token, example_account_id = example_globus
        mock_response(app.extensions['oauthlib.client'], 'globus',
                      example_token)
        example_info.update(example_account_id)
        oauth_resp = OAuthResponse(resp=None,
                                   content=json.dumps(example_info),
                                   content_type='application/json')
        mock_remote_get(ioc, 'globus', oauth_resp)

        # User then goes to 'Linked accounts' and clicks 'Connect'
        resp = client.get(
            url_for('invenio_oauthclient.login',
                    remote_app='globus',
                    next='/someurl/'))
        assert resp.status_code == 302

        # User authorized the requests and is redirected back
        resp = client.get(
            url_for('invenio_oauthclient.authorized',
                    remote_app='globus',
                    code='test',
                    state=_get_state()))

        # Assert database state (Sign-up complete)
        u = User.query.filter_by(email=existing_email).one()
        remote = RemoteAccount.query.filter_by(user_id=u.id).one()
        RemoteToken.query.filter_by(id_remote_account=remote.id).one()

        # Disconnect link
        resp = client.get(
            url_for('invenio_oauthclient.disconnect', remote_app='globus'))
        assert resp.status_code == 302

        # User exists
        u = User.query.filter_by(email=existing_email).one()
        assert 0 == UserIdentity.query.filter_by(method='globus',
                                                 id_user=u.id,
                                                 id='globususer').count()
        assert RemoteAccount.query.filter_by(user_id=u.id).count() == 0
        assert RemoteToken.query.count() == 0