Login

create and authenticate an anonymous user

Author:
chr15m
Posted:
September 12, 2009
Language:
Python
Version:
1.1
Tags:
authentication anonymous
Score:
2 (after 4 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. Use both NTLM and Anonymous authentication with IIS by ungenio41 5 years ago
  2. New view decorator to only cache pages for anonymous users by vaughnkoch 4 years, 9 months ago
  3. User post_save signal to auto create 'admin' profile by marinho 7 years, 7 months ago
  4. Adding buttons to submit line in a Admin page by marinho 7 years, 2 months ago
  5. Custom mod_python AuthenHandler by aeby 7 years, 11 months 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.