fastapi-twitch 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_twitch-0.1.0/.gitignore +218 -0
- fastapi_twitch-0.1.0/LICENSE +21 -0
- fastapi_twitch-0.1.0/PKG-INFO +461 -0
- fastapi_twitch-0.1.0/README.md +419 -0
- fastapi_twitch-0.1.0/examples/app.py +58 -0
- fastapi_twitch-0.1.0/examples/config.py +16 -0
- fastapi_twitch-0.1.0/examples/requirements.txt +5 -0
- fastapi_twitch-0.1.0/examples/storage.py +67 -0
- fastapi_twitch-0.1.0/fastapi_twitch/__init__.py +58 -0
- fastapi_twitch-0.1.0/fastapi_twitch/_constants.py +14 -0
- fastapi_twitch-0.1.0/fastapi_twitch/core.py +386 -0
- fastapi_twitch-0.1.0/fastapi_twitch/exceptions.py +52 -0
- fastapi_twitch-0.1.0/fastapi_twitch/integrations/__init__.py +0 -0
- fastapi_twitch-0.1.0/fastapi_twitch/integrations/fastapi.py +228 -0
- fastapi_twitch-0.1.0/fastapi_twitch/models.py +95 -0
- fastapi_twitch-0.1.0/fastapi_twitch/py.typed +0 -0
- fastapi_twitch-0.1.0/fastapi_twitch/state.py +108 -0
- fastapi_twitch-0.1.0/pyproject.toml +77 -0
- fastapi_twitch-0.1.0/tests/conftest.py +60 -0
- fastapi_twitch-0.1.0/tests/test_core.py +222 -0
- fastapi_twitch-0.1.0/tests/test_fastapi.py +213 -0
- fastapi_twitch-0.1.0/tests/test_models.py +112 -0
- fastapi_twitch-0.1.0/tests/test_state.py +99 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
.idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 drawiks
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fastapi-twitch
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async OAuth 2.0 / PKCE library for Twitch in FastAPI applications
|
|
5
|
+
Author: drawiks
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: auth,fastapi,helix,oauth,twitch
|
|
9
|
+
Classifier: Framework :: FastAPI
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Requires-Dist: pydantic>=2.5
|
|
22
|
+
Provides-Extra: all
|
|
23
|
+
Requires-Dist: fastapi>=0.110; extra == 'all'
|
|
24
|
+
Requires-Dist: itsdangerous>=2.0; extra == 'all'
|
|
25
|
+
Requires-Dist: redis>=5.0; extra == 'all'
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: fakeredis>=2.20; extra == 'dev'
|
|
28
|
+
Requires-Dist: fastapi>=0.110; extra == 'dev'
|
|
29
|
+
Requires-Dist: itsdangerous>=2.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
31
|
+
Requires-Dist: pydantic-settings>=2.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
33
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
34
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
35
|
+
Requires-Dist: types-redis; extra == 'dev'
|
|
36
|
+
Provides-Extra: fastapi
|
|
37
|
+
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
|
|
38
|
+
Requires-Dist: itsdangerous>=2.0; extra == 'fastapi'
|
|
39
|
+
Provides-Extra: redis
|
|
40
|
+
Requires-Dist: redis>=5.0; extra == 'redis'
|
|
41
|
+
Description-Content-Type: text/markdown
|
|
42
|
+
|
|
43
|
+
<div align="center">
|
|
44
|
+
<h1>โก fastapi-twitch</h1>
|
|
45
|
+
<a href="https://pypi.org/project/fastapi-twitch/">
|
|
46
|
+
<img alt="PyPI version" src="https://img.shields.io/pypi/v/fastapi-twitch?color=blue">
|
|
47
|
+
</a>
|
|
48
|
+
<a href="https://pypi.org/project/fastapi-twitch/">
|
|
49
|
+
<img alt="PyPI downloads" src="https://img.shields.io/pypi/dm/fastapi-twitch?color=blue">
|
|
50
|
+
</a>
|
|
51
|
+
<img height="20" alt="Python 3.10+" src="https://img.shields.io/badge/python-3.10+-blue">
|
|
52
|
+
<img height="20" alt="License MIT" src="https://img.shields.io/badge/license-MIT-green">
|
|
53
|
+
<img height="20" alt="Status" src="https://img.shields.io/badge/status-beta-orange">
|
|
54
|
+
<img alt="Ruff" src="https://img.shields.io/badge/code%20style-ruff-000000">
|
|
55
|
+
<p><strong>fastapi-twitch</strong> - async Twitch OAuth 2.0 (PKCE) authentication for FastAPI / Starlette</p>
|
|
56
|
+
<blockquote>(โโฟโฟโ)</blockquote>
|
|
57
|
+
</div>
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
โโโโโโโโ โโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ โโโโโโโ โโโ
|
|
63
|
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
64
|
+
โโโโโโ โโโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโโโ
|
|
65
|
+
โโโโโโ โโโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโ โโโ
|
|
66
|
+
โโโ โโโ โโโโโโโโโโโ โโโ โโโ โโโโโโ โโโ
|
|
67
|
+
โโโ โโโ โโโโโโโโโโโ โโโ โโโ โโโโโโ โโโ
|
|
68
|
+
|
|
69
|
+
โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโ โโโโ โโโโ
|
|
70
|
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโ
|
|
71
|
+
โโโโโโโโ โโโ โโโโโโ โโโโโโโโโโโโโโโโโโโ
|
|
72
|
+
โโโโโโโโ โโโ โโโโโโ โโโโโโโโโโโโโโโโโโโ
|
|
73
|
+
โโโโโโโโ โโโ โโโโโโโโโโโ โโโโโโ โโโ โโโ
|
|
74
|
+
โโโโโโโโ โโโ โโโโโโโโโโโ โโโโโโ โโโ
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## **๐ฆ installation**
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
pip install fastapi-twitch # core (httpx + pydantic)
|
|
83
|
+
pip install fastapi-twitch[fastapi] # FastAPI integration (TwitchAuth)
|
|
84
|
+
pip install fastapi-twitch[redis] # RedisStateStore for the CSRF state
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
> Full working examples are in the [`examples/`](examples/) directory - a complete app
|
|
88
|
+
> with both session- and Redis-backed state stores and a token-storage pattern.
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## **๐ quick start**
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from fastapi import FastAPI, Request
|
|
96
|
+
from fastapi.responses import RedirectResponse
|
|
97
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
98
|
+
|
|
99
|
+
from fastapi_twitch import TwitchAuth
|
|
100
|
+
|
|
101
|
+
twitch = TwitchAuth(
|
|
102
|
+
client_id="...", # your Twitch application credentials
|
|
103
|
+
client_secret="...",
|
|
104
|
+
redirect_uri="http://localhost:8000/auth/callback",
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
app = FastAPI()
|
|
108
|
+
app.add_middleware(SessionMiddleware, secret_key="change-me-in-prod")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@app.get("/login")
|
|
112
|
+
async def login(request: Request):
|
|
113
|
+
return await twitch.redirect_to_login(request) # 307 to id.twitch.tv
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@app.get("/auth/callback")
|
|
117
|
+
async def callback(request: Request, state: str):
|
|
118
|
+
token_set = await twitch.authenticate(request, expected_state=state)
|
|
119
|
+
# token_set.tokens + token_set.user - persist them wherever you want
|
|
120
|
+
return RedirectResponse("/me", status_code=307)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## **๐งฉ features**
|
|
126
|
+
|
|
127
|
+
- ๐ **OAuth 2.0 done right** - Authorization Code grant + **PKCE S256**, always on
|
|
128
|
+
- ๐ฏ **single-use CSRF state** - atomic read-and-delete (`GETDEL` in Redis, `pop` in the session); replaying a state answers `400`
|
|
129
|
+
- ๐ง **two state backends** - `SessionStateStore` (zero extra deps) and `RedisStateStore`
|
|
130
|
+
- ๐งฉ **framework-agnostic core** - `TwitchOAuthClient` has zero web-framework dependencies
|
|
131
|
+
- โก **FastAPI integration** - `TwitchAuth` shipped as an optional `[fastapi]` extra (lazy import, no hard dependency)
|
|
132
|
+
- ๐ **account data** - Helix `GET /users` for yourself or any user, with batching (max 100 per request)
|
|
133
|
+
- ๐ **token hygiene** - secrets masked in `repr`; `client_secret` sent as `client_secret_basic`
|
|
134
|
+
- โ
**fully typed** - `py.typed` marker, `mypy --strict` clean
|
|
135
|
+
- ๐ **Python 3.10+**
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## **โ๏ธ comparison with alternatives**
|
|
140
|
+
|
|
141
|
+
| Feature | fastapi-twitch | authlib | social-auth-core | manual (DIY) |
|
|
142
|
+
|-----------------------------------|:---:|:---:|:---:|:---:|
|
|
143
|
+
| Twitch OAuth 2.0 (Auth Code) | โ
| โ
| โ
| ๐ง |
|
|
144
|
+
| PKCE S256 built-in | โ
| โ ๏ธ opt-in | โ | ๐ง |
|
|
145
|
+
| Single-use CSRF state (atomic) | โ
| โ | โ | ๐ง |
|
|
146
|
+
| Async (asyncio / httpx) | โ
| โ
| โ (requests) | ๐ง |
|
|
147
|
+
| Framework-agnostic core | โ
| โ ๏ธ needs glue/storage | โ ๏ธ needs strategy/storage glue | - |
|
|
148
|
+
| FastAPI-native integration | โ
| โ ๏ธ manual wiring | โ | ๐ง |
|
|
149
|
+
| Account data via Helix `/users` | โ
built-in | โ | โ | ๐ง |
|
|
150
|
+
| Pydantic v2 models | โ
| โ | โ | - |
|
|
151
|
+
| `py.typed`, `mypy --strict` clean | โ
| โ | โ | - |
|
|
152
|
+
| Runtime deps (basic mode) | `httpx` + `pydantic` | `httpx` + more | `requests` + many | - |
|
|
153
|
+
| Python versions | 3.10+ | 3.10+ | 3.10+ | - |
|
|
154
|
+
|
|
155
|
+
Each library has its own strengths - choose what fits your use case.
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## **๐ usage**
|
|
160
|
+
|
|
161
|
+
### TwitchAuth (FastAPI integration)
|
|
162
|
+
|
|
163
|
+
`TwitchAuth` owns the OAuth client, the state store, and the redirect-URI
|
|
164
|
+
contract. State + PKCE are handled internally: starting a login stashes the
|
|
165
|
+
`code_verifier` (bound to the `state`) in the store, and `authenticate()` pops
|
|
166
|
+
it atomically.
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
from fastapi import FastAPI, Request
|
|
170
|
+
from fastapi.responses import RedirectResponse
|
|
171
|
+
from fastapi_twitch import TwitchAuth
|
|
172
|
+
|
|
173
|
+
twitch = TwitchAuth(
|
|
174
|
+
client_id="...",
|
|
175
|
+
client_secret="...",
|
|
176
|
+
redirect_uri="http://localhost:8000/auth/callback",
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@app.get("/login")
|
|
181
|
+
async def login(request: Request):
|
|
182
|
+
return await twitch.redirect_to_login(request) # 307 to Twitch consent
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@app.get("/auth/callback")
|
|
186
|
+
async def callback(request: Request, state: str):
|
|
187
|
+
token_set = await twitch.authenticate(request, expected_state=state)
|
|
188
|
+
return RedirectResponse("/me", status_code=307)
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Lifecycle: `TwitchAuth` owns an `httpx.AsyncClient`. Use it as an async context
|
|
192
|
+
manager or close it explicitly:
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
async with twitch: # closes the internal client on exit
|
|
196
|
+
token_set = await twitch.authenticate(request, expected_state=state)
|
|
197
|
+
# or, for a long-lived instance:
|
|
198
|
+
await twitch.aclose()
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Errors are regular FastAPI `HTTPException`s, straightforward to catch:
|
|
202
|
+
|
|
203
|
+
| Condition | Status code |
|
|
204
|
+
|---|---|
|
|
205
|
+
| empty / unknown / replayed `state`, missing `code` | `400` |
|
|
206
|
+
| Twitch rejects the code (`OAuthError`, e.g. `invalid_grant`) | `400` |
|
|
207
|
+
| Twitch API unavailable | `502` |
|
|
208
|
+
|
|
209
|
+
### Why are `state` and PKCE required?
|
|
210
|
+
|
|
211
|
+
Without a `state` token bound to the session, an attacker can launch a
|
|
212
|
+
**login CSRF** attack: they start a Twitch login in your app and trick the
|
|
213
|
+
victim into finishing it - logging the victim into the attacker's account.
|
|
214
|
+
The `state` token (plus the PKCE `code_verifier`) binds the callback to the
|
|
215
|
+
session that started the login. Replaying a consumed or unknown state is
|
|
216
|
+
rejected because the store deletes it on the first read.
|
|
217
|
+
|
|
218
|
+
PKCE additionally protects the code exchange: even if the authorization code
|
|
219
|
+
is intercepted, it cannot be redeemed without the `code_verifier` that was
|
|
220
|
+
stashed server-side when the login started.
|
|
221
|
+
|
|
222
|
+
### Framework-agnostic usage
|
|
223
|
+
|
|
224
|
+
`TwitchOAuthClient` is independent of any web framework:
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
from fastapi_twitch import TwitchOAuthClient
|
|
228
|
+
|
|
229
|
+
async def main() -> None:
|
|
230
|
+
client = TwitchOAuthClient(client_id="...", client_secret="...")
|
|
231
|
+
|
|
232
|
+
state = client.generate_state()
|
|
233
|
+
verifier, challenge = client.generate_pkce_pair()
|
|
234
|
+
|
|
235
|
+
login_url = client.login_url(
|
|
236
|
+
redirect_uri="https://example.com/auth/callback",
|
|
237
|
+
state=state,
|
|
238
|
+
code_challenge=challenge,
|
|
239
|
+
scopes=["user:read:email"],
|
|
240
|
+
)
|
|
241
|
+
# redirect the user's browser to `login_url`...
|
|
242
|
+
|
|
243
|
+
tokens = await client.exchange_code(
|
|
244
|
+
code=code,
|
|
245
|
+
redirect_uri="https://example.com/auth/callback",
|
|
246
|
+
code_verifier=verifier,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
user = await client.fetch_user(access_token=tokens.access_token)
|
|
250
|
+
print(user.display_name, user.email)
|
|
251
|
+
|
|
252
|
+
await client.aclose()
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
The core does not import `fastapi`; importing it never pulls in a web framework.
|
|
256
|
+
|
|
257
|
+
### Custom httpx client
|
|
258
|
+
|
|
259
|
+
A custom `httpx.AsyncClient` can be injected; the library will never close it:
|
|
260
|
+
|
|
261
|
+
```python
|
|
262
|
+
import httpx
|
|
263
|
+
|
|
264
|
+
transport = httpx.AsyncHTTPTransport(retries=3, pool_connections=20)
|
|
265
|
+
async with httpx.AsyncClient(transport=transport) as http:
|
|
266
|
+
twitch = TwitchAuth(
|
|
267
|
+
client_id="...",
|
|
268
|
+
client_secret="...",
|
|
269
|
+
redirect_uri="http://localhost:8000/auth/callback",
|
|
270
|
+
http_client=http,
|
|
271
|
+
)
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
### State stores
|
|
275
|
+
|
|
276
|
+
The default is the session (a cookie signed by Starlette's
|
|
277
|
+
`SessionMiddleware`) - zero external services. Omit `state_store` entirely and
|
|
278
|
+
add the middleware:
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
from fastapi import FastAPI
|
|
282
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
283
|
+
from fastapi_twitch import TwitchAuth
|
|
284
|
+
|
|
285
|
+
twitch = TwitchAuth(client_id="...", client_secret="...",
|
|
286
|
+
redirect_uri="http://localhost:8000/auth/callback")
|
|
287
|
+
|
|
288
|
+
app = FastAPI()
|
|
289
|
+
app.add_middleware(SessionMiddleware, secret_key="...")
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Redis gives atomic `GETDEL` reads across instances (multi-worker / multi-node):
|
|
293
|
+
|
|
294
|
+
```python
|
|
295
|
+
import redis.asyncio as aioredis
|
|
296
|
+
from fastapi_twitch import RedisStateStore, TwitchAuth
|
|
297
|
+
|
|
298
|
+
twitch = TwitchAuth(
|
|
299
|
+
client_id="...",
|
|
300
|
+
client_secret="...",
|
|
301
|
+
redirect_uri="http://localhost:8000/auth/callback",
|
|
302
|
+
state_store=RedisStateStore(aioredis.from_url("redis://localhost:6379")),
|
|
303
|
+
)
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Any store implementing the two-method `StateStore` protocol (`put`/`pop`)
|
|
307
|
+
works - write your own for Postgres, Memcached, or whatever fits.
|
|
308
|
+
|
|
309
|
+
---
|
|
310
|
+
|
|
311
|
+
## **๐ก๏ธ security**
|
|
312
|
+
|
|
313
|
+
The library enforces the following on every login:
|
|
314
|
+
|
|
315
|
+
1. **PKCE S256 is mandatory** - generated per login, not a flag you can disable.
|
|
316
|
+
2. **CSRF `state`** is `secrets.token_urlsafe(32)` with a 10-minute TTL, bound to
|
|
317
|
+
the session, and consumed **atomically** on callback (Redis `GETDEL` / session
|
|
318
|
+
`pop`). Reuse of a state answers `400`.
|
|
319
|
+
3. **`client_secret`** is sent as `client_secret_basic` (`Authorization` header,
|
|
320
|
+
RFC 6749 ยง2.3.1) - never in the URL or request body.
|
|
321
|
+
4. **Tokens are masked** in `repr()` - secrets never leak into logs.
|
|
322
|
+
5. **`redirect_uri` is HTTPS-only** except for `localhost` / `127.0.0.1` / `::1`
|
|
323
|
+
(local development).
|
|
324
|
+
6. **Refresh-token rotation** - each exchange/refresh returns a fresh
|
|
325
|
+
access/refresh pair as a new immutable instance; store the new one and drop
|
|
326
|
+
the old.
|
|
327
|
+
|
|
328
|
+
You should still encrypt refresh tokens at rest in your own storage.
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## **โ ๏ธ twitch's own limits**
|
|
333
|
+
|
|
334
|
+
- **Refresh tokens are single-use.** Every `/oauth2/token` call that uses a
|
|
335
|
+
refresh token rotates it: the old refresh token stops working. Handle
|
|
336
|
+
rotation races in your store (e.g. update-on-refresh with a single writer).
|
|
337
|
+
- **`/oauth2/validate` never returns email** - even with `user:read:email`.
|
|
338
|
+
Email comes only from Helix `GET /users`.
|
|
339
|
+
- **Helix public fields need no scope** (`display_name`, `description`,
|
|
340
|
+
`profile_image_url`, `view_count`, `broadcaster_type`, `created_at`) but
|
|
341
|
+
still require a valid token. **Email needs `user:read:email`.** Without it,
|
|
342
|
+
the library falls back to the `/validate` profile (`email=None`) instead of
|
|
343
|
+
crashing.
|
|
344
|
+
- **App access tokens** (server-to-server) are obtained via
|
|
345
|
+
`grant_type=client_credentials`, which this library does not wrap - but you
|
|
346
|
+
can pass such a token to `fetch_user`/`fetch_users` to read public profiles.
|
|
347
|
+
|
|
348
|
+
---
|
|
349
|
+
|
|
350
|
+
## **๐ models**
|
|
351
|
+
|
|
352
|
+
### `TwitchTokens`
|
|
353
|
+
|
|
354
|
+
The token set returned by `exchange_code`/`refresh_tokens`. Immutable (frozen)
|
|
355
|
+
- rotating produces a new instance.
|
|
356
|
+
|
|
357
|
+
| Field | Type | Description |
|
|
358
|
+
|-------|------|-------------|
|
|
359
|
+
| `access_token` | `str` | Twitch OAuth access token (Helix API) |
|
|
360
|
+
| `refresh_token` | `str` | refresh token (single-use; rotates on refresh) |
|
|
361
|
+
| `expires_in` | `int` | seconds until the access token expires |
|
|
362
|
+
| `scope` | `list[str]` | granted scopes |
|
|
363
|
+
| `token_type` | `Literal["bearer"]` | always `bearer` |
|
|
364
|
+
| `obtained_at` | `datetime` | UTC timestamp of issuance |
|
|
365
|
+
|
|
366
|
+
Methods: `expires_at` (property), `is_expired(leeway=60) -> bool`.
|
|
367
|
+
|
|
368
|
+
### `TwitchUser`
|
|
369
|
+
|
|
370
|
+
Merges `/oauth2/validate` (always present) with Helix `GET /users`
|
|
371
|
+
(`display_name`, `email`, ... may be `None` when unavailable).
|
|
372
|
+
|
|
373
|
+
| Field | Type | Source |
|
|
374
|
+
|-------|------|--------|
|
|
375
|
+
| `id` | `str` | `/oauth2/validate` `user_id` |
|
|
376
|
+
| `login` | `str` | account name (lowercase) |
|
|
377
|
+
| `scopes` | `list[str]` | granted scopes |
|
|
378
|
+
| `display_name` | `str \| None` | Helix |
|
|
379
|
+
| `email` | `str \| None` | Helix, needs `user:read:email` |
|
|
380
|
+
| `description` | `str \| None` | Helix bio |
|
|
381
|
+
| `profile_image_url` / `offline_image_url` | `str \| None` | Helix |
|
|
382
|
+
| `view_count` | `int \| None` | Helix |
|
|
383
|
+
| `type` | `str \| None` | `staff` / `admin` / ... |
|
|
384
|
+
| `broadcaster_type` | `str \| None` | `partner` / `affiliate` / `empty` |
|
|
385
|
+
| `created_at` | `datetime \| None` | Helix |
|
|
386
|
+
|
|
387
|
+
### `TokenSet`
|
|
388
|
+
|
|
389
|
+
What `authenticate()` returns: `tokens: TwitchTokens`, `user: TwitchUser`,
|
|
390
|
+
`validated_at: datetime`.
|
|
391
|
+
|
|
392
|
+
---
|
|
393
|
+
|
|
394
|
+
## **๐ API Reference**
|
|
395
|
+
|
|
396
|
+
### `TwitchAuth(client_id, client_secret, *, redirect_uri, scopes, state_store, http_client, state_ttl, enforce_https)`
|
|
397
|
+
|
|
398
|
+
FastAPI integration. Requires the `[fastapi]` extra.
|
|
399
|
+
|
|
400
|
+
| Parameter | Type | Default | Description |
|
|
401
|
+
|-----------|------|---------|-------------|
|
|
402
|
+
| `client_id` | `str` | - | Twitch application client id |
|
|
403
|
+
| `client_secret` | `str` | - | Twitch application client secret |
|
|
404
|
+
| `redirect_uri` | `str` | - | absolute URL of the `/auth/callback` route (HTTPS-only, except localhost) |
|
|
405
|
+
| `scopes` | `Sequence[str] \| None` | `("user:read:email",)` | scopes for the authorize URL |
|
|
406
|
+
| `state_store` | `StateStore \| None` | `SessionStateStore` | state/PKCE backend |
|
|
407
|
+
| `http_client` | `httpx.AsyncClient \| None` | `None` | inject your own client (never closed) |
|
|
408
|
+
| `state_ttl` | `timedelta` | `10 minutes` | CSRF state lifetime |
|
|
409
|
+
| `enforce_https` | `bool` | `True` | reject non-`https` `redirect_uri`, except localhost |
|
|
410
|
+
|
|
411
|
+
Methods:
|
|
412
|
+
- `generate_state()` โ `str` - fresh CSRF token
|
|
413
|
+
- `generate_pkce()` โ `tuple[str, str]` - fresh `(code_verifier, code_challenge)`
|
|
414
|
+
- `await login_url(request, *, scopes=None, state=None, code_verifier=None, code_challenge=None, extra=None)` โ `str` - stashes state + verifier, returns Twitch authorize URL
|
|
415
|
+
- `await redirect_to_login(request, *, scopes=None, extra=None)` โ `RedirectResponse` - 307 to Twitch
|
|
416
|
+
- `await authenticate(request, *, expected_state)` โ `TokenSet` - validates callback + exchanges code (raises `HTTPException` `400`/`502`)
|
|
417
|
+
- `await fetch_user(*, access_token, user_id=None, login=None)` โ `TwitchUser`
|
|
418
|
+
- `await fetch_users(*, access_token, ids=None, logins=None)` โ `list[TwitchUser]` - batches to max 100 ids/logins per request
|
|
419
|
+
- `await aclose()` / `async with twitch:` - lifecycle
|
|
420
|
+
|
|
421
|
+
### `TwitchOAuthClient(client_id, client_secret, *, http_client, timeout)`
|
|
422
|
+
|
|
423
|
+
Framework-agnostic core. No web-framework dependency.
|
|
424
|
+
|
|
425
|
+
| Parameter | Type | Default | Description |
|
|
426
|
+
|-----------|------|---------|-------------|
|
|
427
|
+
| `client_id` | `str` | - | Twitch application client id |
|
|
428
|
+
| `client_secret` | `str` | - | Twitch application client secret |
|
|
429
|
+
| `http_client` | `httpx.AsyncClient \| None` | `None` | inject your own client (never closed) |
|
|
430
|
+
| `timeout` | `float` | `10.0` | request timeout |
|
|
431
|
+
|
|
432
|
+
Methods:
|
|
433
|
+
- `generate_state()` โ `str` (static)
|
|
434
|
+
- `generate_pkce_pair()` โ `tuple[str, str]` (static)
|
|
435
|
+
- `login_url(*, redirect_uri, state, code_challenge, scopes)` โ `str`
|
|
436
|
+
- `await exchange_code(*, code, redirect_uri, code_verifier)` โ `TwitchTokens`
|
|
437
|
+
- `await refresh_tokens(*, refresh_token)` โ `TwitchTokens`
|
|
438
|
+
- `await validate(access_token)` โ `TwitchUser`
|
|
439
|
+
- `await revoke(*, token)` โ `None`
|
|
440
|
+
- `await fetch_user(*, access_token, user_id=None, login=None)` โ `TwitchUser`
|
|
441
|
+
- `await fetch_users(*, access_token, ids=None, logins=None)` โ `list[TwitchUser]`
|
|
442
|
+
- `await complete_login(*, code, redirect_uri, code_verifier)` โ `TokenSet` - exchange + validate + best-effort profile merge
|
|
443
|
+
- `await aclose()`
|
|
444
|
+
|
|
445
|
+
### Exceptions
|
|
446
|
+
|
|
447
|
+
| Exception | Description |
|
|
448
|
+
|-----------|-------------|
|
|
449
|
+
| `TwitchAuthError` | base class for all library errors |
|
|
450
|
+
| `TwitchAPIError` | non-2xx response (carries `.status_code`) |
|
|
451
|
+
| `OAuthError` | RFC 6749 error envelope (`invalid_grant`, ...); carries `.code`, `.description` |
|
|
452
|
+
| `InvalidStateError` | missing / expired / replayed CSRF state |
|
|
453
|
+
| `InvalidPKCEError` | missing or mismatched `code_verifier` |
|
|
454
|
+
| `ScopeMissingError` | requested data needs a scope the token lacks |
|
|
455
|
+
| `StateStoreError` | state backend failure / misconfiguration |
|
|
456
|
+
| `ConfigurationError` | bad library config (e.g. `http://` `redirect_uri`) |
|
|
457
|
+
|
|
458
|
+
---
|
|
459
|
+
|
|
460
|
+
## **๐ license**
|
|
461
|
+
[MIT](LICENSE)
|