Skip to content

Commit f6b11e5

Browse files
authored
Authentication (#17)
1 parent c55a365 commit f6b11e5

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

src/async_python_youtube/youtube.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class YouTube:
3535
request_timeout: int = 10
3636
api_host: str = "youtube.googleapis.com"
3737
_close_session: bool = False
38+
_access_token: str | None = None
3839

3940
async def _request(
4041
self,
@@ -77,6 +78,9 @@ async def _request(
7778
"Accept": "application/json, text/plain, */*",
7879
}
7980

81+
if self._access_token:
82+
headers["Authorization"] = f"Bearer {self._access_token}"
83+
8084
if self.session is None:
8185
self.session = ClientSession()
8286
self._close_session = True
@@ -110,6 +114,10 @@ async def _request(
110114

111115
return cast(dict[str, Any], await response.json())
112116

117+
def authenticate(self, access_token: str) -> None:
118+
"""Apply authentication to the requests."""
119+
self._access_token = access_token
120+
113121
async def get_video(self, video_id: str) -> YouTubeVideo | None:
114122
"""Get a single video."""
115123
return await first(self.get_videos([video_id]))

tests/test_auth.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""Tests for the YouTube client."""
2+
3+
import aiohttp
4+
from aiohttp.web_request import BaseRequest
5+
from aresponses import Response, ResponsesMockServer
6+
7+
from async_python_youtube.youtube import YouTube
8+
9+
from . import load_fixture
10+
11+
YOUTUBE_URL = "youtube.googleapis.com"
12+
13+
14+
async def test_authentication(aresponses: ResponsesMockServer) -> None:
15+
"""Test request will be sending bearer token after authentication."""
16+
17+
async def response_handler(req: BaseRequest) -> Response:
18+
"""Response handler for this test."""
19+
assert req.headers.get("Authorization") == "Bearer abc"
20+
return aresponses.Response(
21+
status=200,
22+
headers={"Content-Type": "application/json"},
23+
text=load_fixture("video_response_snippet.json"),
24+
)
25+
26+
aresponses.add(
27+
YOUTUBE_URL,
28+
"/youtube/v3/videos",
29+
"GET",
30+
response_handler,
31+
)
32+
33+
async with aiohttp.ClientSession() as session:
34+
youtube = YouTube(session=session)
35+
youtube.authenticate("abc")
36+
assert await youtube.get_video(video_id="Ks-_Mh1QhMc")
37+
await youtube.close()

0 commit comments

Comments
 (0)