views:

211

answers:

3

My Django app, deployed in mod_wsgi under Apache using Django's standard WSGIHandler, authenticates users via form login on the Django side. So to Apache, the user is anonymous. This makes the Apache access log less useful.

Is there a way to pass the username back through the WSGI wrapper to Apache after handling the request, so that it appears in the Apache access log?

(Versions: Django 1.1.1, mod_wsgi 2.5, Apache 2.2.9)

+1  A: 

This probably isn't what you're expecting, but you could use the username in your URL scheme. That way the user will be in the path section of your apache logs.

You'd need to modify your authentication so that auth-required responses are obvious in the apache logs, otherwise when viewing the logs you may attribute unauthenticated requests to authenticated users. E.g. return a temporary redirect to the login page if the request isn't authenticated.

MattH
Login view redirecting to /loggedin/<username> redirecting to settings.LOGIN_REDIRECT_URL. It's hacky, but I like it.
muhuk
You're right — not what I'm expecting. :) Username in the URL is not acceptable for me.
Gunnlaugur Briem
+2  A: 

You can only do it if using embedded mode and only if you use a separate package called apswigpy, which provides a Python binding for original Apache request object. The mod_wsgi package provides an optional mechanism for allowing original Apache request object to be passed as Python CObject reference in WSGI environment. You use that in conjunction with apswigpy something like:

from apache.httpd import request_rec
r = request_rec(environ['apache.request_rec'])
r.user = user

At least I think that will setup the appropriate information which access logging can then use.

You should really take this discussion over to the mod_wsgi mailing list.

Graham Dumpleton
Thanks; I started a thread there and am accepting this answer as the closest we're likely to get here. :)
Gunnlaugur Briem
+2  A: 

You could use mod_auth_tkt. An auth_tkt is a signed cookie with the user id that Apache can understand. Your web application would have to set the cookie when the user logs in and out. Apache can derive a REMOTE_USER from the cookie, pass it to your web app or a non-Django web application running on the same server, include it in logs, whatever.

joeforker
Sounds like just the *cough* ticket. One minor difficulty may be the binding to the IP, could cause issues to anyone behind load balanced proxies. Also may make it tough to reverse proxy your application.
MattH
No, it doesn't cause problems. The cookie is optionally bound to the remote user's IP address. You can pass that with an X- header or some other means depending on the nature of your proxy.
joeforker
This does seem a fairly neat solution, actually; enables single-signon with other apps. Also would make it possible to log (and control) access to static media not handled by mod_wsgi; not a big thing for us but a nice added benefit. Thanks!
Gunnlaugur Briem