0
# Authentication
1
2
Authentication module providing OAuth device flow authentication, token management, and GitHub API scope handling for secure API access.
3
4
## Capabilities
5
6
### Device Flow Authentication
7
8
OAuth device flow authentication for obtaining GitHub access tokens interactively.
9
10
```python { .api }
11
class GhDeviceAuth:
12
def __init__(self, client_id=None, *scopes):
13
"""
14
Initialize OAuth device flow authentication.
15
16
Parameters:
17
- client_id: str, OAuth application client ID (optional)
18
- *scopes: GitHub OAuth scopes to request
19
"""
20
21
def url_docs(self) -> str:
22
"""
23
Get default authentication instructions.
24
25
Returns:
26
str: Instructions with user code and verification URL
27
"""
28
29
def open_browser(self):
30
"""
31
Open web browser with verification URL.
32
"""
33
34
def auth(self) -> str:
35
"""
36
Check if authentication is complete.
37
38
Returns:
39
str: Access token if complete, None if pending
40
41
Raises:
42
Exception: If authentication failed
43
"""
44
45
def wait(self, cb: callable = None, n_polls=9999) -> str:
46
"""
47
Wait for authentication completion.
48
49
Parameters:
50
- cb: callable, callback function called after each poll
51
- n_polls: int, maximum number of polls
52
53
Returns:
54
str: Access token when authentication completes
55
"""
56
```
57
58
### Interactive Authentication
59
60
Simplified interactive authentication function.
61
62
```python { .api }
63
def github_auth_device(wb='', n_polls=9999):
64
"""
65
Authenticate with GitHub using device flow.
66
67
Parameters:
68
- wb: str, whether to open browser ('y' to open automatically)
69
- n_polls: int, maximum polls to wait for completion
70
71
Returns:
72
str: GitHub access token
73
"""
74
```
75
76
### Scope Management
77
78
Utilities for working with GitHub OAuth scopes.
79
80
```python { .api }
81
def scope_str(*scopes) -> str:
82
"""
83
Convert scopes to comma-separated string.
84
85
Parameters:
86
- *scopes: GitHub OAuth scope objects or strings
87
88
Returns:
89
str: Comma-separated scope string
90
"""
91
```
92
93
### Available Scopes
94
95
GitHub OAuth scopes available through the Scope object.
96
97
```python { .api }
98
Scope = AttrDict({
99
'repo': 'repo', # Full repository access
100
'repo_status': 'repo:status', # Repository status access
101
'repo_deployment': 'repo_deployment', # Repository deployment access
102
'public_repo': 'public_repo', # Public repository access
103
'repo_invite': 'repo:invite', # Repository invitation access
104
'security_events': 'security_events', # Security events access
105
'admin_repo_hook': 'admin:repo_hook', # Repository webhook admin
106
'write_repo_hook': 'write:repo_hook', # Repository webhook write
107
'read_repo_hook': 'read:repo_hook', # Repository webhook read
108
'admin_org': 'admin:org', # Organization admin
109
'write_org': 'write:org', # Organization write
110
'read_org': 'read:org', # Organization read
111
'admin_public_key': 'admin:public_key', # Public key admin
112
'write_public_key': 'write:public_key', # Public key write
113
'read_public_key': 'read:public_key', # Public key read
114
'admin_org_hook': 'admin:org_hook', # Organization webhook admin
115
'gist': 'gist', # Gist access
116
'notifications': 'notifications', # Notification access
117
'user': 'user', # User profile access
118
'read_user': 'read:user', # User profile read
119
'user_email': 'user:email', # User email access
120
'user_follow': 'user:follow', # User follow access
121
'delete_repo': 'delete_repo', # Repository deletion
122
'write_discussion': 'write:discussion', # Discussion write
123
'read_discussion': 'read:discussion', # Discussion read
124
'write_packages': 'write:packages', # Package write
125
'read_packages': 'read:packages', # Package read
126
'delete_packages': 'delete:packages', # Package deletion
127
'admin_gpg_key': 'admin:gpg_key', # GPG key admin
128
'write_gpg_key': 'write:gpg_key', # GPG key write
129
'read_gpg_key': 'read:gpg_key', # GPG key read
130
'workflow': 'workflow' # GitHub Actions workflow
131
})
132
```
133
134
## Usage Examples
135
136
### Basic Token Authentication
137
138
```python
139
from ghapi.all import GhApi
140
141
# Using environment variable GITHUB_TOKEN
142
api = GhApi()
143
144
# Using explicit token
145
api = GhApi(token='ghp_your_personal_access_token')
146
147
# Using JWT token
148
api = GhApi(jwt_token='your_jwt_token')
149
150
# Disable authentication
151
api = GhApi(authenticate=False)
152
```
153
154
### Device Flow Authentication
155
156
```python
157
from ghapi.all import github_auth_device, GhApi
158
159
# Interactive device flow authentication
160
token = github_auth_device()
161
print(f"Obtained token: {token}")
162
163
# Use token with API client
164
api = GhApi(token=token)
165
user = api.users.get_authenticated()
166
print(f"Authenticated as: {user.login}")
167
```
168
169
### Advanced Device Flow
170
171
```python
172
from ghapi.all import GhDeviceAuth, Scope, scope_str
173
174
# Create device auth with specific scopes
175
scopes = [Scope.repo, Scope.user, Scope.gist]
176
auth = GhDeviceAuth(scopes=scopes)
177
178
print(f"User code: {auth.user_code}")
179
print(f"Verification URL: {auth.verification_uri}")
180
181
# Open browser automatically
182
auth.open_browser()
183
184
# Wait for completion with progress callback
185
def progress():
186
print(".", end="", flush=True)
187
188
token = auth.wait(cb=progress)
189
print(f"\\nAuthentication complete: {token}")
190
```
191
192
### Custom Client ID and Scopes
193
194
```python
195
from ghapi.all import GhDeviceAuth, Scope
196
197
# Use custom OAuth application
198
auth = GhDeviceAuth(
199
client_id='your_oauth_app_client_id',
200
Scope.repo,
201
Scope.write_org,
202
Scope.gist
203
)
204
205
# Display authentication instructions
206
print(auth.url_docs())
207
208
# Manual polling
209
while True:
210
token = auth.auth()
211
if token:
212
print(f"Got token: {token}")
213
break
214
time.sleep(5)
215
```
216
217
### Scope String Formatting
218
219
```python
220
from ghapi.all import Scope, scope_str
221
222
# Create scope string for multiple scopes
223
scopes = scope_str(Scope.repo, Scope.user, Scope.gist)
224
print(f"Scope string: {scopes}") # "repo,user,gist"
225
226
# Use with device auth
227
auth = GhDeviceAuth(
228
client_id='your_client_id',
229
Scope.repo,
230
Scope.admin_org,
231
Scope.workflow
232
)
233
```
234
235
### Environment Variable Setup
236
237
```bash
238
# Set token as environment variable
239
export GITHUB_TOKEN=ghp_your_personal_access_token
240
241
# Or for JWT tokens
242
export GITHUB_JWT_TOKEN=your_jwt_token
243
```
244
245
```python
246
from ghapi.all import GhApi
247
248
# Automatically uses GITHUB_TOKEN or GITHUB_JWT_TOKEN
249
api = GhApi()
250
251
# Check authentication status
252
try:
253
user = api.users.get_authenticated()
254
print(f"Authenticated as: {user.login}")
255
except Exception:
256
print("Not authenticated or invalid token")
257
```
258
259
### Token Validation
260
261
```python
262
from ghapi.all import GhApi
263
264
def validate_token(token):
265
"""Validate GitHub token by testing API access."""
266
try:
267
api = GhApi(token=token)
268
user = api.users.get_authenticated()
269
return True, user.login
270
except Exception as e:
271
return False, str(e)
272
273
# Test token
274
is_valid, result = validate_token('ghp_test_token')
275
if is_valid:
276
print(f"Token is valid for user: {result}")
277
else:
278
print(f"Token validation failed: {result}")
279
```