views:

73

answers:

3

I want to make my User objects all have the same base behaviour and to do so I need to add a couple of methods / properties to Anonymous User.

I've already subclassed User to make richer user objects but I was wondering if anyone has done the same for Anonymous User? And if there are any preferred ways of doing it!

A: 

You should subclass or create a model that has a one to one relationship with the AnonymousUser class.

Olivier
subclassing would be ideal, but is more about the practicalities of doing it, as the AnonymousUser class is imported directly in a number of places.
Ross
A: 

I'm starting to think a middleware is probably the easiest solution that checks the request.user class and if is AnonymousUser then replaces it with a subclassed AnonymousUser that has the extra properties.

That sound reasonable?

Ross
+2  A: 

Your middleware suggestion got me thinking, and I now think the best idea is to overwrite the standard AuthenticationMiddleware. That class assigns a LazyUser object to the request, which is resolved to the correct user, when accessed, by calling contrib.auth.get_user. This is probably the right place to override things, so that it calls your customised get_user function which returns your subclassed AnonymousUser.

Daniel Roseman
Works a treat cheers Daniel! Heres a copy for prosperity: [custom auth backend](http://gist.github.com/397817)
Ross