Login

create and authenticate an anonymous user

Author:
chr15m
Posted:
September 12, 2009
Language:
Python
Version:
1.1
Score:
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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Archatas (on September 12, 2009):

Interesting. This or similar solution might be useful, if you rely on permission checking in templates.

#

Please login first before commenting.