Apache mod_python handler
Today I wanted to secure a bunch of pdf files of a php web-app. The webapp takes care of user authentication, but the pdf-files to download are just served by apache without any authentication in between. It's plain easy to add some additional authentication by means of a mod_python apache handler. The handler checks for the existance of a specific cookie - if present access is granted otherwise not.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from mod_python import apache
from mod_python import util
import time
class _Handler:
""" simple handler, which checks for a specific .php file
and forwards to a different url
"""
def __init__(self,phase,status=apache.OK,delay=0):
self.__phase = phase
self.__status = status
self.__delay = delay
def __call__(self,req):
time.sleep(self.__delay)
## check the uri
if ".pdf" in req.uri:
# check for a usermanagemet-cookie
cookie_header = req.headers_in['COOKIE']
if 'usermanagement.session' in cookie_header:
return self.__status
# no cookie available - forbidden
req.log_error('access denied because no cookie available!')
return apache.HTTP_FORBIDDEN
else:
return self.__status
return self.__status
accesshandler = _Handler("accesshandler")The handler is placed in the python site-packages and referenced in the apache config.
## handle .pdf files via the python handler
PythonAccessHandler handler::accesshandler | .pdf