- September 12, 2009
- authentication anonymous
- 3 (after 5 ratings)
If you want anonymous visitors to your site, or parts of your site to be authenticated as real users so that you can treat them as such in your views and models, use this snippet. Add the above AuthenticationBackendAnonymous middleware into AUTHENTICATION_BACKENDS in your settings.py and use the snippet anonymous_or_real(request) in your views, which returns a user. Comment out the bit where it creates a profile if you are not using profiles.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
def anonymous_or_real(request): # do we have an existing user? if request.user.is_authenticated(): return request.user else: # if not, create an anonymous user and log them in username = IntToLetters(randint(0, maxint)) u = User(username=username, first_name='Anonymous', last_name='User') u.set_unusable_password() u.save() u.username = u.id u.save() # comment out the next two lines if you aren't using profiles p = UserProfile(user=u, anonymous=True) p.save() authenticate(user=u) login(request, u) return u ######## Anonymous authentication backend middleware ######### from django.contrib.auth.models import User from myapp.models import UserProfile class AuthenticationBackendAnonymous: ''' This is for automatically signing in the user after signup etc. ''' def authenticate(self, user=None): # make sure they have a profile and that they are anonymous # if you're not using profiles you can just return user if not user.get_profile() or not user.get_profile().anonymous: user = None return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None