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
36 37 38 39 | |
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 | |
__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 | |
is_authenticated()
Check if credentials are available.
Source code in gkc/auth.py
58 59 60 | |
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()
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" ... })
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 | |
__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 | |
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 | |
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 | |
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:
| Type | Description |
|---|---|
str
|
CSRF token string. |
Raises:
| Type | Description |
|---|---|
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" ... })
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 | |
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. |
Raises:
| Type | Description |
|---|---|
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
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 | |
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 |
bool
|
otherwise. |
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 | |
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 | |
login()
Perform login to MediaWiki API using bot password credentials.
Returns:
| Type | Description |
|---|---|
bool
|
True if login successful, False otherwise. |
Raises:
| Type | Description |
|---|---|
AuthenticationError
|
If login fails with detailed error message. |
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 | |
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 | |
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 | |
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 | |
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 | |
__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 | |
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")
Switch between Wikimedia projects
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()
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
- Authentication Guide - Conceptual overview and setup instructions
- SPARQL API - Query Wikidata and other SPARQL endpoints