| 343 | | |
|---|
| 344 | | import cherrypy |
|---|
| 345 | | from cherrypy._cptools import Tool |
|---|
| 346 | | |
|---|
| 347 | | def check_auth(realm, users): |
|---|
| 348 | | # Check if the user-agent provides an authorization header |
|---|
| 349 | | # containing credentials |
|---|
| 350 | | if 'authorization' in cherrypy.request.headers: |
|---|
| 351 | | # make sure the provided credentials are correctly set |
|---|
| 352 | | ah = parseAuthorization(cherrypy.request.headers['authorization']) |
|---|
| 353 | | if ah is None: |
|---|
| 354 | | raise cherrypy.HTTPError(400, 'Bad Request') |
|---|
| 355 | | |
|---|
| 356 | | # fetch the user password |
|---|
| 357 | | password = users.get(ah["username"], None) |
|---|
| 358 | | |
|---|
| 359 | | # validate the authorization by re-computing it here |
|---|
| 360 | | # and compare it with what the user-agent provided |
|---|
| 361 | | if checkResponse(ah, password, method=cherrypy.request.method): |
|---|
| 362 | | return True |
|---|
| 363 | | |
|---|
| 364 | | return False |
|---|
| 365 | | |
|---|
| 366 | | def basic_auth(realm, users): |
|---|
| 367 | | if check_auth(realm, users): |
|---|
| 368 | | return |
|---|
| 369 | | |
|---|
| 370 | | # inform the user-agent this path is protected |
|---|
| 371 | | cherrypy.response.headers['www-authenticate'] = basicAuth(realm) |
|---|
| 372 | | |
|---|
| 373 | | raise cherrypy.HTTPError(401, "You are not authorized to access that resource") |
|---|
| 374 | | |
|---|
| 375 | | def digest_auth(realm, users): |
|---|
| 376 | | if check_auth(realm, users): |
|---|
| 377 | | return |
|---|
| 378 | | |
|---|
| 379 | | # inform the user-agent this path is protected |
|---|
| 380 | | cherrypy.response.headers['www-authenticate'] = digestAuth(realm) |
|---|
| 381 | | |
|---|
| 382 | | raise cherrypy.HTTPError(401, "You are not authorized to access that resource") |
|---|
| 383 | | |
|---|