Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support unauthenticated access to the Github API #47

Merged
merged 1 commit into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,19 @@ async with AppClient(app_id, privkey) as session:
resp = await session.get("/octocat")
```

### No Authentication

Finally you can create a client without any authentication. This is mainly
provided for cases where supplying an authentication method is optional, e.g to
increase rate limits. This allows for simpler implementations.

```python
from simple_github import PublicClient

async with PublicClient() as session:
resp = await session.get("/octocat")
```

### Query the REST API

simple-github provides only a very basic wrapper around Github's REST API. You can
Expand Down
17 changes: 16 additions & 1 deletion src/simple_github/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio
from typing import List, Optional, Union

from .auth import AppAuth, AppInstallationAuth, TokenAuth
from .auth import AppAuth, AppInstallationAuth, PublicAuth, TokenAuth
from .client import AsyncClient, Client, SyncClient


Expand Down Expand Up @@ -60,3 +60,18 @@ def TokenClient(token: str) -> Client:

auth = TokenAuth(token)
return AsyncClient(auth=auth) if is_async else SyncClient(auth=auth)


def PublicClient() -> Client:
"""Convenience function to create an unauthenticated `Client` instance.

Returns:
Client: A client without any authentication."""
try:
asyncio.get_running_loop()
is_async = True
except RuntimeError:
is_async = False

auth = PublicAuth()
return AsyncClient(auth=auth) if is_async else SyncClient(auth=auth)
7 changes: 7 additions & 0 deletions src/simple_github/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ async def close(self) -> None:
pass


class PublicAuth(Auth):
"""Shim for unauthenticated API access."""

async def get_token(self) -> str:
return ""


class TokenAuth(Auth):
def __init__(self, token: str):
"""Authentication for an access token.
Expand Down
8 changes: 6 additions & 2 deletions src/simple_github/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,10 @@ def _get_gql_session(self) -> SyncClientSession:

headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
}
if token:
headers["Authorization"] = f"Bearer {token}"

transport = RequestsHTTPTransport(url=GITHUB_GRAPHQL_ENDPOINT, headers=headers)
self._gql_client = GqlClient(
transport=transport, fetch_schema_from_transport=False
Expand Down Expand Up @@ -242,8 +244,10 @@ async def _get_gql_session(self) -> ReconnectingAsyncClientSession:

headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
}
if token:
headers["Authorization"] = f"Bearer {token}"

transport = AIOHTTPTransport(url=GITHUB_GRAPHQL_ENDPOINT, headers=headers)
self._gql_client = GqlClient(
transport=transport, fetch_schema_from_transport=False
Expand Down
8 changes: 7 additions & 1 deletion test/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@
import jwt
import pytest

from simple_github.auth import AppAuth, AppInstallationAuth, TokenAuth
from simple_github.auth import AppAuth, AppInstallationAuth, PublicAuth, TokenAuth
from simple_github.client import GITHUB_API_ENDPOINT


@pytest.mark.asyncio
async def test_public_auth_get_token():
auth = PublicAuth()
assert await auth.get_token() == ""


@pytest.mark.asyncio
async def test_token_auth_get_token():
token = "123"
Expand Down
19 changes: 19 additions & 0 deletions test/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ async def test_async_client_get_session(async_client):
}


@pytest.mark.asyncio
async def test_async_client_get_session_no_token(async_client):
client = async_client
client.auth._token = ""
session = await client._get_aiohttp_session()
assert dict(session._default_headers) == {
"Accept": "application/vnd.github+json",
}


def test_sync_client_get_session(sync_client):
client = sync_client
assert client._gql_client is None
Expand Down Expand Up @@ -87,6 +97,15 @@ def test_sync_client_get_session(sync_client):
}


def test_sync_client_get_session_no_token(sync_client):
client = sync_client
client.auth._token = ""
client._get_requests_session()
assert dict(client._gql_session.transport.headers) == {
"Accept": "application/vnd.github+json",
}


@pytest.mark.asyncio
async def test_async_client_rest(aioresponses, async_client):
client = async_client
Expand Down
14 changes: 13 additions & 1 deletion test/test_simple_github.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
import pytest

from simple_github import AppClient, TokenClient
from simple_github import AppClient, PublicClient, TokenClient
from simple_github.client import GITHUB_API_ENDPOINT


@pytest.mark.asyncio
async def test_public_client(aioresponses):
aioresponses.get(
f"{GITHUB_API_ENDPOINT}/octocat", status=200, payload={"foo": "bar"}
)

async with PublicClient() as client:
resp = await client.get("/octocat")
result = await resp.json()
assert result == {"foo": "bar"}


@pytest.mark.asyncio
async def test_token_client(aioresponses):
aioresponses.get(
Expand Down
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading