create and authenticate an anonymous user

 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 3 years, 8 months ago
  2. New view decorator to only cache pages for anonymous users by vaughnkoch 3 years, 6 months ago
  3. User post_save signal to auto create 'admin' profile by marinho 6 years, 4 months ago
  4. Adding buttons to submit line in a Admin page by marinho 5 years, 11 months ago
  5. Custom mod_python AuthenHandler by aeby 6 years, 8 months ago

Comments

Archatas (on September 12, 2009):

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

#

(Forgotten your password?)