Authentication API
Overview
The Authentication module provides unified credential management for Global Knowledge Commons services. Currently it supports Wikimedia projects (Wikidata, Wikipedia, Wikimedia Commons) using bot password authentication, with planned support for OpenStreetMap and other external services.
Current implementations: Wikimedia projects (Wikidata production, test instance, Wikipedia, Commons); OpenStreetMap auth framework
Future implementations: OpenStreetMap API authentication, additional service integrations
Quick Start
from gkc import WikiverseAuth
# Authenticate to Wikidata using bot password
auth = WikiverseAuth(
username="MyUsername@MyBot",
password="abc123def456ghi789"
)
auth.login()
print(f"Logged in as: {auth.get_account_name()}")
Classes
AuthenticationError
Bases: Exception
Raised when authentication fails.
Source code in gkc/auth.py
| class AuthenticationError(Exception):
"""Raised when authentication fails."""
pass
|
AuthBase
Base class for authentication.
Source code in gkc/auth.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 | class AuthBase:
"""Base class for authentication."""
def __init__(self, username: Optional[str] = None, password: Optional[str] = None):
"""
Initialize authentication.
Args:
username: Username for authentication. If not provided, will try to
read from environment variable.
password: Password for authentication. If not provided, will try to
read from environment variable.
"""
self.username = username
self.password = password
def is_authenticated(self) -> bool:
"""Check if credentials are available."""
return bool(self.username and self.password)
|
__init__(username=None, password=None)
Initialize authentication.
Parameters:
| Name |
Type |
Description |
Default |
username
|
Optional[str]
|
Username for authentication. If not provided, will try to
read from environment variable.
|
None
|
password
|
Optional[str]
|
Password for authentication. If not provided, will try to
read from environment variable.
|
None
|
Source code in gkc/auth.py
45
46
47
48
49
50
51
52
53
54
55
56 | def __init__(self, username: Optional[str] = None, password: Optional[str] = None):
"""
Initialize authentication.
Args:
username: Username for authentication. If not provided, will try to
read from environment variable.
password: Password for authentication. If not provided, will try to
read from environment variable.
"""
self.username = username
self.password = password
|
is_authenticated()
Check if credentials are available.
Source code in gkc/auth.py
| def is_authenticated(self) -> bool:
"""Check if credentials are available."""
return bool(self.username and self.password)
|
WikiverseAuth
Bases: AuthBase
Authentication for Wikimedia projects (Wikidata, Wikipedia, Wikimedia Commons).
Designed for bot accounts using bot passwords. The same credentials work
across all Wikimedia projects due to Single User Login (SUL).
Supports both default Wikimedia instances and custom MediaWiki installations.
Credentials can be provided in three ways (in order of precedence):
1. Direct parameters
2. Environment variables (WIKIVERSE_USERNAME, WIKIVERSE_PASSWORD, WIKIVERSE_API_URL)
3. Interactive prompt
Example
Authenticate to Wikidata (default)
auth = WikiverseAuth()
auth.login()
auth = WikiverseAuth(
... username="MyUsername@MyBot",
... password="abc123def456ghi789",
... api_url="https://www.wikidata.org/w/api.php"
... )
auth.login()
auth = WikiverseAuth(
... username="MyUsername@MyBot",
... password="abc123def456ghi789",
... api_url="https://my-wiki.example.com/w/api.php"
... )
auth.login()
IMPORTANT: Use auth.session for API requests to maintain authentication
token = auth.get_csrf_token()
response = auth.session.post(auth.api_url, data={
... "action": "edit",
... "title": "Test",
... "text": "content",
... "token": token,
... "format": "json"
... })
Source code in gkc/auth.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502 | class WikiverseAuth(AuthBase):
"""
Authentication for Wikimedia projects (Wikidata, Wikipedia, Wikimedia Commons).
Designed for bot accounts using bot passwords. The same credentials work
across all Wikimedia projects due to Single User Login (SUL).
Supports both default Wikimedia instances and custom MediaWiki installations.
Credentials can be provided in three ways (in order of precedence):
1. Direct parameters
2. Environment variables (WIKIVERSE_USERNAME, WIKIVERSE_PASSWORD, WIKIVERSE_API_URL)
3. Interactive prompt
Example:
>>> # Authenticate to Wikidata (default)
>>> auth = WikiverseAuth()
>>> auth.login()
>>> # Direct parameters (bot password format)
>>> auth = WikiverseAuth(
... username="MyUsername@MyBot",
... password="abc123def456ghi789",
... api_url="https://www.wikidata.org/w/api.php"
... )
>>> auth.login()
>>> # Custom MediaWiki instance
>>> auth = WikiverseAuth(
... username="MyUsername@MyBot",
... password="abc123def456ghi789",
... api_url="https://my-wiki.example.com/w/api.php"
... )
>>> auth.login()
>>> # IMPORTANT: Use auth.session for API requests to maintain authentication
>>> token = auth.get_csrf_token()
>>> response = auth.session.post(auth.api_url, data={
... "action": "edit",
... "title": "Test",
... "text": "content",
... "token": token,
... "format": "json"
... })
"""
def __init__(
self,
username: Optional[str] = None,
password: Optional[str] = None,
api_url: Optional[str] = None,
interactive: bool = False,
):
"""
Initialize Wikiverse authentication for bot accounts.
Args:
username: Bot password username in format "Username@BotName".
If not provided, reads from WIKIVERSE_USERNAME
environment variable.
password: Bot password. If not provided, reads from
WIKIVERSE_PASSWORD environment variable.
api_url: MediaWiki API endpoint URL. If not provided, reads from
WIKIVERSE_API_URL environment variable, or defaults to Wikidata.
Can also use shortcuts: "wikidata", "wikipedia", "commons"
interactive: If True and credentials are not found, prompt user for input.
"""
# Try provided parameters first
username = username or os.environ.get("WIKIVERSE_USERNAME")
password = password or os.environ.get("WIKIVERSE_PASSWORD")
api_url = api_url or os.environ.get("WIKIVERSE_API_URL")
# If credentials still not available and interactive mode is requested
if interactive and not (username and password):
print("Bot password credentials not found in environment.")
username = input(
"Enter Wikiverse username (format: Username@BotName): "
).strip()
password = getpass.getpass("Enter Wikiverse password: ").strip()
if not api_url:
api_url_input = input(
"Enter API URL (or 'wikidata', 'wikipedia', 'commons') "
"[default: wikidata]: "
).strip()
api_url = api_url_input if api_url_input else "wikidata"
super().__init__(username, password)
# Resolve API URL shortcuts to full URLs
if api_url and api_url.lower() in DEFAULT_WIKIMEDIA_APIS:
self.api_url = DEFAULT_WIKIMEDIA_APIS[api_url.lower()]
elif api_url:
self.api_url = api_url
else:
# Default to Wikidata
self.api_url = DEFAULT_WIKIMEDIA_APIS["wikidata"]
# Initialize session for authenticated requests
self.session = requests.Session()
self.session.headers.update(
{"User-Agent": "GKC-Python-Client/0.1 (https://github.com/skybristol/gkc)"}
)
self._logged_in = False
def login(self) -> bool:
"""
Perform login to MediaWiki API using bot password credentials.
Returns:
True if login successful, False otherwise.
Raises:
AuthenticationError: If login fails with detailed error message.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> if auth.login():
... print("Successfully logged in!")
"""
if not self.is_authenticated():
raise AuthenticationError(
"Cannot login: credentials not provided. "
"Please provide username and password."
)
try:
# Step 1: Get login token
token_params = {
"action": "query",
"meta": "tokens",
"type": "login",
"format": "json",
}
token_response = self.session.get(self.api_url, params=token_params)
token_response.raise_for_status()
token_data = token_response.json()
if "query" not in token_data or "tokens" not in token_data["query"]:
raise AuthenticationError(
f"Failed to get login token from {self.api_url}. "
f"Response: {token_data}"
)
login_token = token_data["query"]["tokens"]["logintoken"]
# Step 2: Perform login with credentials and token
login_params = {
"action": "login",
"lgname": self.username,
"lgpassword": self.password,
"lgtoken": login_token,
"format": "json",
}
login_response = self.session.post(self.api_url, data=login_params)
login_response.raise_for_status()
login_data = login_response.json()
# Check login result
if "login" not in login_data:
raise AuthenticationError(
f"Unexpected login response from {self.api_url}. "
f"Response: {login_data}"
)
result = login_data["login"]["result"]
if result == "Success":
self._logged_in = True
# Verify we have session cookies
if not self.session.cookies:
raise AuthenticationError(
"Login reported success but no session cookies were set. "
"This may indicate a network or API configuration issue."
)
return True
else:
# Provide detailed error message
reason = login_data["login"].get("reason", "Unknown reason")
raise AuthenticationError(
f"Login failed with result '{result}'. Reason: {reason}. "
f"Check your bot password credentials and permissions."
)
except requests.RequestException as e:
raise AuthenticationError(
f"Network error during login to {self.api_url}: {str(e)}"
)
def is_logged_in(self) -> bool:
"""
Check if currently logged in to MediaWiki API.
Returns:
True if logged in, False otherwise.
"""
return self._logged_in
def logout(self) -> None:
"""
Logout from MediaWiki API and clear session.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> # ... do some work ...
>>> auth.logout()
"""
if self._logged_in:
try:
# Get CSRF token for logout
token_params = {
"action": "query",
"meta": "tokens",
"type": "csrf",
"format": "json",
}
token_response = self.session.get(self.api_url, params=token_params)
token_data = token_response.json()
csrf_token = token_data["query"]["tokens"]["csrftoken"]
# Perform logout
logout_params = {
"action": "logout",
"token": csrf_token,
"format": "json",
}
self.session.post(self.api_url, data=logout_params)
except Exception:
# Ignore logout errors, just clear session
pass
finally:
self._logged_in = False
self.session.cookies.clear()
def get_csrf_token(self) -> str:
"""
Get a CSRF token for making edits.
IMPORTANT: The token must be used with auth.session for requests.
The token alone is not sufficient - you need the authenticated session cookies.
Returns:
CSRF token string.
Raises:
AuthenticationError: If not logged in or token retrieval fails.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> token = auth.get_csrf_token()
>>> # Use token with auth.session (not a new requests call)
>>> response = auth.session.post(auth.api_url, data={
... "action": "edit",
... "title": "Page",
... "text": "content",
... "token": token,
... "format": "json"
... })
"""
if not self.is_logged_in():
raise AuthenticationError(
"Not logged in. Call login() first before getting CSRF token."
)
try:
token_params = {
"action": "query",
"meta": "tokens",
"type": "csrf",
"format": "json",
}
# Use POST to ensure cookies are properly handled
response = self.session.post(self.api_url, data=token_params)
response.raise_for_status()
data = response.json()
if "query" in data and "tokens" in data["query"]:
csrf_token: str = data["query"]["tokens"]["csrftoken"]
return csrf_token
else:
raise AuthenticationError(f"Failed to get CSRF token. Response: {data}")
except requests.RequestException as e:
raise AuthenticationError(f"Network error getting CSRF token: {str(e)}")
def __repr__(self) -> str:
status = (
"logged in"
if self._logged_in
else ("authenticated" if self.is_authenticated() else "not authenticated")
)
return (
f"WikiverseAuth(username={self.username!r}, "
f"api_url={self.api_url!r}, {status})"
)
def get_bot_name(self) -> Optional[str]:
"""
Extract bot name from username.
Returns:
Bot name if username is in bot password format, None otherwise.
Example:
>>> auth = WikiverseAuth(username="Alice@MyBot")
>>> auth.get_bot_name()
'MyBot'
"""
if self.username and "@" in self.username:
return self.username.split("@", 1)[1]
return None
def get_account_name(self) -> Optional[str]:
"""
Extract account name from username.
Returns:
Account name if username is in bot password format, None otherwise.
Example:
>>> auth = WikiverseAuth(username="Alice@MyBot")
>>> auth.get_account_name()
'Alice'
"""
if self.username and "@" in self.username:
return self.username.split("@", 1)[0]
return None
def should_mark_bot_edits(self) -> bool:
"""Return whether edits should default to bot-tagged.
Plain meaning: If credentials are in bot-password username format
(Account@BotName), default write operations to bot mode.
"""
return bool(self.username and "@" in self.username)
def test_authentication(self) -> dict:
"""
Test authentication and return diagnostic information.
Returns:
Dictionary with authentication status, session details, and token info.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> info = auth.test_authentication()
>>> print(info)
"""
info = {
"credentials_provided": self.is_authenticated(),
"logged_in": self.is_logged_in(),
"api_url": self.api_url,
"username": self.username,
"bot_name": self.get_bot_name(),
"session_cookies": list(self.session.cookies.keys()),
"csrf_token_retrieved": False,
"csrf_token_preview": None,
"error": None,
}
if self.is_logged_in():
try:
token = self.get_csrf_token()
info["csrf_token_retrieved"] = True
preview = token[:20] + "..." if len(token) > 20 else token
info["csrf_token_preview"] = preview
except Exception as e:
info["error"] = str(e)
return info
def get_user_rights(self) -> list[str]:
"""Return the list of user rights from the API userinfo endpoint.
Calls action=query&meta=userinfo&uiprop=rights on the authenticated
session and returns the raw rights list. Useful for capability
detection before making API calls with limits that depend on user tier.
Returns:
List of right name strings (e.g. ``["apihighlimits", "read", ...]``).
Raises:
AuthenticationError: If not logged in or the API request fails.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> rights = auth.get_user_rights()
>>> "apihighlimits" in rights
True
"""
if not self.is_logged_in():
raise AuthenticationError(
"Not logged in. Call login() first before checking user rights."
)
try:
response = self.session.get(
self.api_url,
params={
"action": "query",
"meta": "userinfo",
"uiprop": "rights",
"format": "json",
},
)
response.raise_for_status()
data = response.json()
rights = data.get("query", {}).get("userinfo", {}).get("rights", [])
return rights if isinstance(rights, list) else []
except requests.RequestException as exc:
raise AuthenticationError(
f"Network error fetching user rights: {exc}"
) from exc
def has_api_high_limits(self) -> bool:
"""Return True if the authenticated user has the apihighlimits right.
The ``apihighlimits`` right elevates per-request API caps from 50 to
500 items for actions such as ``wbgetentities``. Returns False if the
user is not logged in or if the rights check fails for any reason, so
callers can safely use this as a capability flag without extra error
handling.
Returns:
True when ``apihighlimits`` is present in the user's rights, False
otherwise.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> limit = 500 if auth.has_api_high_limits() else 50
"""
try:
return "apihighlimits" in self.get_user_rights()
except AuthenticationError:
return False
|
__init__(username=None, password=None, api_url=None, interactive=False)
Initialize Wikiverse authentication for bot accounts.
Parameters:
| Name |
Type |
Description |
Default |
username
|
Optional[str]
|
Bot password username in format "Username@BotName".
If not provided, reads from WIKIVERSE_USERNAME
environment variable.
|
None
|
password
|
Optional[str]
|
Bot password. If not provided, reads from
WIKIVERSE_PASSWORD environment variable.
|
None
|
api_url
|
Optional[str]
|
MediaWiki API endpoint URL. If not provided, reads from
WIKIVERSE_API_URL environment variable, or defaults to Wikidata.
Can also use shortcuts: "wikidata", "wikipedia", "commons"
|
None
|
interactive
|
bool
|
If True and credentials are not found, prompt user for input.
|
False
|
Source code in gkc/auth.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165 | def __init__(
self,
username: Optional[str] = None,
password: Optional[str] = None,
api_url: Optional[str] = None,
interactive: bool = False,
):
"""
Initialize Wikiverse authentication for bot accounts.
Args:
username: Bot password username in format "Username@BotName".
If not provided, reads from WIKIVERSE_USERNAME
environment variable.
password: Bot password. If not provided, reads from
WIKIVERSE_PASSWORD environment variable.
api_url: MediaWiki API endpoint URL. If not provided, reads from
WIKIVERSE_API_URL environment variable, or defaults to Wikidata.
Can also use shortcuts: "wikidata", "wikipedia", "commons"
interactive: If True and credentials are not found, prompt user for input.
"""
# Try provided parameters first
username = username or os.environ.get("WIKIVERSE_USERNAME")
password = password or os.environ.get("WIKIVERSE_PASSWORD")
api_url = api_url or os.environ.get("WIKIVERSE_API_URL")
# If credentials still not available and interactive mode is requested
if interactive and not (username and password):
print("Bot password credentials not found in environment.")
username = input(
"Enter Wikiverse username (format: Username@BotName): "
).strip()
password = getpass.getpass("Enter Wikiverse password: ").strip()
if not api_url:
api_url_input = input(
"Enter API URL (or 'wikidata', 'wikipedia', 'commons') "
"[default: wikidata]: "
).strip()
api_url = api_url_input if api_url_input else "wikidata"
super().__init__(username, password)
# Resolve API URL shortcuts to full URLs
if api_url and api_url.lower() in DEFAULT_WIKIMEDIA_APIS:
self.api_url = DEFAULT_WIKIMEDIA_APIS[api_url.lower()]
elif api_url:
self.api_url = api_url
else:
# Default to Wikidata
self.api_url = DEFAULT_WIKIMEDIA_APIS["wikidata"]
# Initialize session for authenticated requests
self.session = requests.Session()
self.session.headers.update(
{"User-Agent": "GKC-Python-Client/0.1 (https://github.com/skybristol/gkc)"}
)
self._logged_in = False
|
get_account_name()
Extract account name from username.
Returns:
| Type |
Description |
Optional[str]
|
Account name if username is in bot password format, None otherwise.
|
Example
auth = WikiverseAuth(username="Alice@MyBot")
auth.get_account_name()
'Alice'
Source code in gkc/auth.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390 | def get_account_name(self) -> Optional[str]:
"""
Extract account name from username.
Returns:
Account name if username is in bot password format, None otherwise.
Example:
>>> auth = WikiverseAuth(username="Alice@MyBot")
>>> auth.get_account_name()
'Alice'
"""
if self.username and "@" in self.username:
return self.username.split("@", 1)[0]
return None
|
get_bot_name()
Extract bot name from username.
Returns:
| Type |
Description |
Optional[str]
|
Bot name if username is in bot password format, None otherwise.
|
Example
auth = WikiverseAuth(username="Alice@MyBot")
auth.get_bot_name()
'MyBot'
Source code in gkc/auth.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374 | def get_bot_name(self) -> Optional[str]:
"""
Extract bot name from username.
Returns:
Bot name if username is in bot password format, None otherwise.
Example:
>>> auth = WikiverseAuth(username="Alice@MyBot")
>>> auth.get_bot_name()
'MyBot'
"""
if self.username and "@" in self.username:
return self.username.split("@", 1)[1]
return None
|
get_csrf_token()
Get a CSRF token for making edits.
IMPORTANT: The token must be used with auth.session for requests.
The token alone is not sufficient - you need the authenticated session cookies.
Returns:
Raises:
Example
auth = WikiverseAuth(username="User@Bot", password="secret")
auth.login()
token = auth.get_csrf_token()
Use token with auth.session (not a new requests call)
response = auth.session.post(auth.api_url, data={
... "action": "edit",
... "title": "Page",
... "text": "content",
... "token": token,
... "format": "json"
... })
Source code in gkc/auth.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347 | def get_csrf_token(self) -> str:
"""
Get a CSRF token for making edits.
IMPORTANT: The token must be used with auth.session for requests.
The token alone is not sufficient - you need the authenticated session cookies.
Returns:
CSRF token string.
Raises:
AuthenticationError: If not logged in or token retrieval fails.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> token = auth.get_csrf_token()
>>> # Use token with auth.session (not a new requests call)
>>> response = auth.session.post(auth.api_url, data={
... "action": "edit",
... "title": "Page",
... "text": "content",
... "token": token,
... "format": "json"
... })
"""
if not self.is_logged_in():
raise AuthenticationError(
"Not logged in. Call login() first before getting CSRF token."
)
try:
token_params = {
"action": "query",
"meta": "tokens",
"type": "csrf",
"format": "json",
}
# Use POST to ensure cookies are properly handled
response = self.session.post(self.api_url, data=token_params)
response.raise_for_status()
data = response.json()
if "query" in data and "tokens" in data["query"]:
csrf_token: str = data["query"]["tokens"]["csrftoken"]
return csrf_token
else:
raise AuthenticationError(f"Failed to get CSRF token. Response: {data}")
except requests.RequestException as e:
raise AuthenticationError(f"Network error getting CSRF token: {str(e)}")
|
get_user_rights()
Return the list of user rights from the API userinfo endpoint.
Calls action=query&meta=userinfo&uiprop=rights on the authenticated
session and returns the raw rights list. Useful for capability
detection before making API calls with limits that depend on user tier.
Returns:
| Type |
Description |
list[str]
|
List of right name strings (e.g. ["apihighlimits", "read", ...]).
|
Raises:
Example
auth = WikiverseAuth(username="User@Bot", password="secret")
auth.login()
rights = auth.get_user_rights()
"apihighlimits" in rights
True
Source code in gkc/auth.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479 | def get_user_rights(self) -> list[str]:
"""Return the list of user rights from the API userinfo endpoint.
Calls action=query&meta=userinfo&uiprop=rights on the authenticated
session and returns the raw rights list. Useful for capability
detection before making API calls with limits that depend on user tier.
Returns:
List of right name strings (e.g. ``["apihighlimits", "read", ...]``).
Raises:
AuthenticationError: If not logged in or the API request fails.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> rights = auth.get_user_rights()
>>> "apihighlimits" in rights
True
"""
if not self.is_logged_in():
raise AuthenticationError(
"Not logged in. Call login() first before checking user rights."
)
try:
response = self.session.get(
self.api_url,
params={
"action": "query",
"meta": "userinfo",
"uiprop": "rights",
"format": "json",
},
)
response.raise_for_status()
data = response.json()
rights = data.get("query", {}).get("userinfo", {}).get("rights", [])
return rights if isinstance(rights, list) else []
except requests.RequestException as exc:
raise AuthenticationError(
f"Network error fetching user rights: {exc}"
) from exc
|
has_api_high_limits()
Return True if the authenticated user has the apihighlimits right.
The apihighlimits right elevates per-request API caps from 50 to
500 items for actions such as wbgetentities. Returns False if the
user is not logged in or if the rights check fails for any reason, so
callers can safely use this as a capability flag without extra error
handling.
Returns:
| Type |
Description |
bool
|
True when apihighlimits is present in the user's rights, False
|
bool
|
|
Example
auth = WikiverseAuth(username="User@Bot", password="secret")
auth.login()
limit = 500 if auth.has_api_high_limits() else 50
Source code in gkc/auth.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502 | def has_api_high_limits(self) -> bool:
"""Return True if the authenticated user has the apihighlimits right.
The ``apihighlimits`` right elevates per-request API caps from 50 to
500 items for actions such as ``wbgetentities``. Returns False if the
user is not logged in or if the rights check fails for any reason, so
callers can safely use this as a capability flag without extra error
handling.
Returns:
True when ``apihighlimits`` is present in the user's rights, False
otherwise.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> limit = 500 if auth.has_api_high_limits() else 50
"""
try:
return "apihighlimits" in self.get_user_rights()
except AuthenticationError:
return False
|
is_logged_in()
Check if currently logged in to MediaWiki API.
Returns:
| Type |
Description |
bool
|
True if logged in, False otherwise.
|
Source code in gkc/auth.py
251
252
253
254
255
256
257
258 | def is_logged_in(self) -> bool:
"""
Check if currently logged in to MediaWiki API.
Returns:
True if logged in, False otherwise.
"""
return self._logged_in
|
login()
Perform login to MediaWiki API using bot password credentials.
Returns:
| Type |
Description |
bool
|
True if login successful, False otherwise.
|
Raises:
Example
auth = WikiverseAuth(username="User@Bot", password="secret")
if auth.login():
... print("Successfully logged in!")
Source code in gkc/auth.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249 | def login(self) -> bool:
"""
Perform login to MediaWiki API using bot password credentials.
Returns:
True if login successful, False otherwise.
Raises:
AuthenticationError: If login fails with detailed error message.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> if auth.login():
... print("Successfully logged in!")
"""
if not self.is_authenticated():
raise AuthenticationError(
"Cannot login: credentials not provided. "
"Please provide username and password."
)
try:
# Step 1: Get login token
token_params = {
"action": "query",
"meta": "tokens",
"type": "login",
"format": "json",
}
token_response = self.session.get(self.api_url, params=token_params)
token_response.raise_for_status()
token_data = token_response.json()
if "query" not in token_data or "tokens" not in token_data["query"]:
raise AuthenticationError(
f"Failed to get login token from {self.api_url}. "
f"Response: {token_data}"
)
login_token = token_data["query"]["tokens"]["logintoken"]
# Step 2: Perform login with credentials and token
login_params = {
"action": "login",
"lgname": self.username,
"lgpassword": self.password,
"lgtoken": login_token,
"format": "json",
}
login_response = self.session.post(self.api_url, data=login_params)
login_response.raise_for_status()
login_data = login_response.json()
# Check login result
if "login" not in login_data:
raise AuthenticationError(
f"Unexpected login response from {self.api_url}. "
f"Response: {login_data}"
)
result = login_data["login"]["result"]
if result == "Success":
self._logged_in = True
# Verify we have session cookies
if not self.session.cookies:
raise AuthenticationError(
"Login reported success but no session cookies were set. "
"This may indicate a network or API configuration issue."
)
return True
else:
# Provide detailed error message
reason = login_data["login"].get("reason", "Unknown reason")
raise AuthenticationError(
f"Login failed with result '{result}'. Reason: {reason}. "
f"Check your bot password credentials and permissions."
)
except requests.RequestException as e:
raise AuthenticationError(
f"Network error during login to {self.api_url}: {str(e)}"
)
|
logout()
Logout from MediaWiki API and clear session.
Example
auth = WikiverseAuth(username="User@Bot", password="secret")
auth.login()
... do some work ...
auth.logout()
Source code in gkc/auth.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295 | def logout(self) -> None:
"""
Logout from MediaWiki API and clear session.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> # ... do some work ...
>>> auth.logout()
"""
if self._logged_in:
try:
# Get CSRF token for logout
token_params = {
"action": "query",
"meta": "tokens",
"type": "csrf",
"format": "json",
}
token_response = self.session.get(self.api_url, params=token_params)
token_data = token_response.json()
csrf_token = token_data["query"]["tokens"]["csrftoken"]
# Perform logout
logout_params = {
"action": "logout",
"token": csrf_token,
"format": "json",
}
self.session.post(self.api_url, data=logout_params)
except Exception:
# Ignore logout errors, just clear session
pass
finally:
self._logged_in = False
self.session.cookies.clear()
|
should_mark_bot_edits()
Return whether edits should default to bot-tagged.
Plain meaning: If credentials are in bot-password username format
(Account@BotName), default write operations to bot mode.
Source code in gkc/auth.py
392
393
394
395
396
397
398
399 | def should_mark_bot_edits(self) -> bool:
"""Return whether edits should default to bot-tagged.
Plain meaning: If credentials are in bot-password username format
(Account@BotName), default write operations to bot mode.
"""
return bool(self.username and "@" in self.username)
|
test_authentication()
Test authentication and return diagnostic information.
Returns:
| Type |
Description |
dict
|
Dictionary with authentication status, session details, and token info.
|
Example
auth = WikiverseAuth(username="User@Bot", password="secret")
auth.login()
info = auth.test_authentication()
print(info)
Source code in gkc/auth.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435 | def test_authentication(self) -> dict:
"""
Test authentication and return diagnostic information.
Returns:
Dictionary with authentication status, session details, and token info.
Example:
>>> auth = WikiverseAuth(username="User@Bot", password="secret")
>>> auth.login()
>>> info = auth.test_authentication()
>>> print(info)
"""
info = {
"credentials_provided": self.is_authenticated(),
"logged_in": self.is_logged_in(),
"api_url": self.api_url,
"username": self.username,
"bot_name": self.get_bot_name(),
"session_cookies": list(self.session.cookies.keys()),
"csrf_token_retrieved": False,
"csrf_token_preview": None,
"error": None,
}
if self.is_logged_in():
try:
token = self.get_csrf_token()
info["csrf_token_retrieved"] = True
preview = token[:20] + "..." if len(token) > 20 else token
info["csrf_token_preview"] = preview
except Exception as e:
info["error"] = str(e)
return info
|
OpenStreetMapAuth
Bases: AuthBase
Authentication for OpenStreetMap.
Credentials can be provided in three ways (in order of precedence):
1. Direct parameters
2. Environment variables (OPENSTREETMAP_USERNAME, OPENSTREETMAP_PASSWORD)
3. Interactive prompt
Example
Using environment variables
auth = OpenStreetMapAuth()
Direct parameters
auth = OpenStreetMapAuth(username="myuser", password="mypass")
Interactive prompt
auth = OpenStreetMapAuth(interactive=True)
Enter OpenStreetMap username: myuser
Enter OpenStreetMap password: ****
Source code in gkc/auth.py
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557 | class OpenStreetMapAuth(AuthBase):
"""
Authentication for OpenStreetMap.
Credentials can be provided in three ways (in order of precedence):
1. Direct parameters
2. Environment variables (OPENSTREETMAP_USERNAME, OPENSTREETMAP_PASSWORD)
3. Interactive prompt
Example:
>>> # Using environment variables
>>> auth = OpenStreetMapAuth()
>>> # Direct parameters
>>> auth = OpenStreetMapAuth(username="myuser", password="mypass")
>>> # Interactive prompt
>>> auth = OpenStreetMapAuth(interactive=True)
Enter OpenStreetMap username: myuser
Enter OpenStreetMap password: ****
"""
def __init__(
self,
username: Optional[str] = None,
password: Optional[str] = None,
interactive: bool = False,
):
"""
Initialize OpenStreetMap authentication.
Args:
username: OpenStreetMap username. If not provided, reads from
OPENSTREETMAP_USERNAME environment variable.
password: OpenStreetMap password. If not provided, reads from
OPENSTREETMAP_PASSWORD environment variable.
interactive: If True and credentials are not found, prompt user for input.
"""
# Try provided parameters first
username = username or os.environ.get("OPENSTREETMAP_USERNAME")
password = password or os.environ.get("OPENSTREETMAP_PASSWORD")
# If credentials still not available and interactive mode is requested
if interactive and not (username and password):
print("OpenStreetMap credentials not found in environment.")
username = input("Enter OpenStreetMap username: ").strip()
password = getpass.getpass("Enter OpenStreetMap password: ").strip()
super().__init__(username, password)
def __repr__(self) -> str:
status = "authenticated" if self.is_authenticated() else "not authenticated"
return f"OpenStreetMapAuth(username={self.username!r}, {status})"
|
__init__(username=None, password=None, interactive=False)
Initialize OpenStreetMap authentication.
Parameters:
| Name |
Type |
Description |
Default |
username
|
Optional[str]
|
OpenStreetMap username. If not provided, reads from
OPENSTREETMAP_USERNAME environment variable.
|
None
|
password
|
Optional[str]
|
OpenStreetMap password. If not provided, reads from
OPENSTREETMAP_PASSWORD environment variable.
|
None
|
interactive
|
bool
|
If True and credentials are not found, prompt user for input.
|
False
|
Source code in gkc/auth.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553 | def __init__(
self,
username: Optional[str] = None,
password: Optional[str] = None,
interactive: bool = False,
):
"""
Initialize OpenStreetMap authentication.
Args:
username: OpenStreetMap username. If not provided, reads from
OPENSTREETMAP_USERNAME environment variable.
password: OpenStreetMap password. If not provided, reads from
OPENSTREETMAP_PASSWORD environment variable.
interactive: If True and credentials are not found, prompt user for input.
"""
# Try provided parameters first
username = username or os.environ.get("OPENSTREETMAP_USERNAME")
password = password or os.environ.get("OPENSTREETMAP_PASSWORD")
# If credentials still not available and interactive mode is requested
if interactive and not (username and password):
print("OpenStreetMap credentials not found in environment.")
username = input("Enter OpenStreetMap username: ").strip()
password = getpass.getpass("Enter OpenStreetMap password: ").strip()
super().__init__(username, password)
|
Examples
Authenticate to Wikidata using environment variables
This is the recommended approach for production workflows and CI/CD environments:
from gkc import WikiverseAuth
# Set environment variables first:
# export WIKIVERSE_USERNAME="MyUsername@MyBot"
# export WIKIVERSE_PASSWORD="abc123def456ghi789"
auth = WikiverseAuth()
auth.login()
print(f"Successfully logged in to: {auth.api_url}")
Authenticate to test.wikidata.org for testing
Use the new wikidata_test endpoint for development and testing:
from gkc import WikiverseAuth
auth = WikiverseAuth(
username="TestBot@BotAccount",
password="test_password_123",
api_url="wikidata_test" # Points to test.wikidata.org/w/api.php
)
if auth.login():
token = auth.get_csrf_token()
# Use token for test edits
print(f"Got CSRF token for test edits")
The same bot password credentials work across all Wikimedia projects thanks to Single User Login (SUL):
from gkc import WikiverseAuth
# Create auth once with default Wikidata endpoint
auth = WikiverseAuth(
username="MyUsername@MyBot",
password="abc123def456ghi789"
)
auth.login()
# Later, query Wikipedia instead
auth.api_url = "https://en.wikipedia.org/w/api.php"
# The session is already authenticated for all Wikimedia projects
# Or use shortcuts for common projects
from gkc.auth import DEFAULT_WIKIMEDIA_APIS
auth.api_url = DEFAULT_WIKIMEDIA_APIS["commons"] # Wikimedia Commons
Use authentication session for API requests
The authenticated session can be used directly for making API calls:
from gkc import WikiverseAuth
auth = WikiverseAuth(
username="MyUsername@MyBot",
password="abc123def456ghi789",
api_url="wikidata"
)
auth.login()
# Use the authenticated session for queries
response = auth.session.get(auth.api_url, params={
"action": "query",
"meta": "userinfo",
"format": "json"
})
userinfo = response.json()
print(f"Logged in as: {userinfo['query']['userinfo']['name']}")
Extract account and bot names
Parse bot password format to extract components:
from gkc import WikiverseAuth
auth = WikiverseAuth(username="Alice@MyBot")
# Before login - still able to parse username
account_name = auth.get_account_name() # "Alice"
bot_name = auth.get_bot_name() # "MyBot"
print(f"Account: {account_name}, Bot: {bot_name}")
# Credentials can be provided via environment or password prompt
auth.login()
token = auth.get_csrf_token()
Capability Detection
After login, the WikiverseAuth object can query the MediaWiki API for the authenticated user's rights and use those to adjust workflow behavior automatically.
get_user_rights()
Returns the set of rights granted to the authenticated user.
from gkc import WikiverseAuth
auth = WikiverseAuth()
auth.login()
rights = auth.get_user_rights()
print(rights) # e.g. {"read", "edit", "apihighlimits", ...}
has_api_high_limits()
Returns True when the authenticated user holds the apihighlimits right, which raises the MediaWiki API's maximum batch size from 50 to 500 items per request.
Bot accounts are typically granted this right; anonymous and standard user sessions are not.
from gkc import WikiverseAuth
auth = WikiverseAuth()
auth.login()
batch_size = 500 if auth.has_api_high_limits() else 50
print(f"Using batch size: {batch_size}")
full_sync_wikibase_entity_cache() uses this check automatically when an authenticated WikiverseAuth instance is provided, so high-volume cache operations get the larger batch without manual configuration.
Error Handling
Missing credentials
from gkc import WikiverseAuth, AuthenticationError
auth = WikiverseAuth() # No credentials provided
try:
auth.login()
except AuthenticationError as e:
print(f"Login failed: {e}")
# Output: Login failed: Cannot login: credentials not provided...
Invalid bot password credentials
from gkc import WikiverseAuth, AuthenticationError
auth = WikiverseAuth(
username="Alice@BadBot",
password="wrong_password"
)
try:
auth.login()
except AuthenticationError as e:
print(f"Authentication error: {e}")
# Output will describe the specific failure reason
Network errors
from gkc import WikiverseAuth, AuthenticationError
# Invalid API URL
auth = WikiverseAuth(
username="Alice@MyBot",
password="secret",
api_url="https://invalid-wiki-site.example.com/w/api.php"
)
try:
auth.login()
except AuthenticationError as e:
print(f"Network error: {e}")
# Output: Network error during login to https://invalid-wiki-site.example.com/w/api.php: ...
Missing CSRF token (not logged in)
from gkc import WikiverseAuth, AuthenticationError
auth = WikiverseAuth(username="Alice@MyBot", password="secret")
# Forgot to login first!
try:
token = auth.get_csrf_token()
except AuthenticationError as e:
print(f"Error: {e}")
# Output: Error: Not logged in. Call login() first before getting CSRF token.
Available Endpoints
The auth module includes shortcuts for common Wikimedia instances:
| Shortcut |
Full URL |
wikidata |
https://www.wikidata.org/w/api.php |
wikidata_test |
https://test.wikidata.org/w/api.php |
wikipedia |
https://en.wikipedia.org/w/api.php |
commons |
https://commons.wikimedia.org/w/api.php |
Custom MediaWiki instances can be used by providing the full API URL.
See Also