Permalink
Browse files

COOKIE-based user authentication added

  • Loading branch information...
kottenator committed Dec 12, 2010
1 parent 3c31fac commit b75c34145d12e062d6b5ed6da6016cb9c02ba55e
View
@@ -2,7 +2,7 @@
from models import Vote, Score
class VoteAdmin(admin.ModelAdmin):
- list_display = ('content_object', 'user', 'ip_address', 'score', 'date_changed')
+ list_display = ('content_object', 'user', 'ip_address', 'cookie', 'score', 'date_changed')
list_filter = ('score', 'content_type', 'date_changed')
search_fields = ('ip_address',)
raw_id_fields = ('user',)
View
@@ -3,6 +3,7 @@
import forms
import itertools
+from datetime import datetime
from models import Vote, Score
from default_settings import RATINGS_VOTES_PER_IP
@@ -81,8 +82,8 @@ def get_real_rating(self):
return 0
return float(self.score)/self.votes
- def get_rating_for_user(self, user, ip_address=None):
- """get_rating_for_user(user, ip_address=None)
+ def get_rating_for_user(self, user, ip_address=None, cookies={}):
+ """get_rating_for_user(user, ip_address=None, cookie=None)
Returns the rating for a user or anonymous IP."""
kwargs = dict(
@@ -98,14 +99,26 @@ def get_rating_for_user(self, user, ip_address=None):
kwargs['ip_address'] = ip_address
else:
kwargs['user'] = user
+
+ use_cookies = self.field.allow_anonymous and self.field.use_cookies
+ if use_cookies:
+ cookie_name = 'vote-%d.%d.%s' % (kwargs['content_type'].pk, kwargs['object_id'], kwargs['key'][:6],) # -> md5_hexdigest?
+ cookie = cookies.get(cookie_name)
+ if cookie:
+ kwargs['cookie'] = cookie
+ else:
+ kwargs['cookie__isnull'] = True
+
try:
rating = Vote.objects.get(**kwargs)
return rating.score
+ except Vote.MultipleObjectsReturned:
+ pass
except Vote.DoesNotExist:
pass
return
- def add(self, score, user, ip_address, commit=True):
+ def add(self, score, user, ip_address, cookies={}, commit=True):
"""add(score, user, ip_address)
Used to add a rating to an object."""
@@ -123,7 +136,7 @@ def add(self, score, user, ip_address, commit=True):
if is_anonymous:
user = None
-
+
defaults = dict(
score = score,
ip_address = ip_address,
@@ -137,6 +150,14 @@ def add(self, score, user, ip_address, commit=True):
)
if not user:
kwargs['ip_address'] = ip_address
+
+ use_cookies = self.field.allow_anonymous and self.field.use_cookies
+ if use_cookies:
+ cookie_name = 'vote-%d.%d.%s' % (kwargs['content_type'].pk, kwargs['object_id'], kwargs['key'][:6],) # -> md5_hexdigest?
+ cookie = cookies.get(cookie_name)
+ if not cookie:
+ cookie = datetime.now().strftime('%Y%m%d%H%M%S%f') # -> md5_hexdigest?
+ kwargs['cookie'] = cookie
try:
rating, created = Vote.objects.get(**kwargs), False
@@ -191,6 +212,12 @@ def add(self, score, user, ip_address, commit=True):
if not created:
score.__dict__.update(defaults)
score.save()
+
+ adds = {}
+ if use_cookies:
+ adds['cookie_name'] = cookie_name
+ adds['cookie'] = cookie
+ return adds
def _get_votes(self, default=None):
return getattr(self.instance, self.votes_field_name, default)
@@ -271,6 +298,7 @@ def __init__(self, *args, **kwargs):
self.weight = kwargs.pop('weight', 0)
self.range = kwargs.pop('range', 2)
self.allow_anonymous = kwargs.pop('allow_anonymous', False)
+ self.use_cookies = kwargs.pop('use_cookies', False)
kwargs['editable'] = False
kwargs['default'] = 0
kwargs['blank'] = True
@@ -0,0 +1,110 @@
+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+
+ # Removing unique constraint on 'Vote', fields ['key', 'ip_address', 'object_id', 'content_type', 'user']
+ db.delete_unique('djangoratings_vote', ['key', 'ip_address', 'object_id', 'content_type_id', 'user_id'])
+
+ # Adding field 'Vote.cookie'
+ db.add_column('djangoratings_vote', 'cookie', self.gf('django.db.models.fields.CharField')(max_length=32, null=True, blank=True), keep_default=False)
+
+ # Adding unique constraint on 'Vote', fields ['content_type', 'object_id', 'cookie', 'user', 'key', 'ip_address']
+ db.create_unique('djangoratings_vote', ['content_type_id', 'object_id', 'cookie', 'user_id', 'key', 'ip_address'])
+
+
+ def backwards(self, orm):
+
+ # Removing unique constraint on 'Vote', fields ['content_type', 'object_id', 'cookie', 'user', 'key', 'ip_address']
+ db.delete_unique('djangoratings_vote', ['content_type_id', 'object_id', 'cookie', 'user_id', 'key', 'ip_address'])
+
+ # Deleting field 'Vote.cookie'
+ db.delete_column('djangoratings_vote', 'cookie')
+
+ # Adding unique constraint on 'Vote', fields ['key', 'ip_address', 'object_id', 'content_type', 'user']
+ db.create_unique('djangoratings_vote', ['key', 'ip_address', 'object_id', 'content_type_id', 'user_id'])
+
+
+ models = {
+ 'auth.group': {
+ 'Meta': {'object_name': 'Group'},
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+ 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+ },
+ 'auth.permission': {
+ 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+ 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+ },
+ 'auth.user': {
+ 'Meta': {'object_name': 'User'},
+ 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+ 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+ 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+ 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+ 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
+ },
+ 'contenttypes.contenttype': {
+ 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+ 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+ },
+ 'djangoratings.ignoredobject': {
+ 'Meta': {'unique_together': "(('content_type', 'object_id'),)", 'object_name': 'IgnoredObject'},
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
+ },
+ 'djangoratings.score': {
+ 'Meta': {'unique_together': "(('content_type', 'object_id', 'key'),)", 'object_name': 'Score'},
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
+ 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
+ 'score': ('django.db.models.fields.IntegerField', [], {}),
+ 'votes': ('django.db.models.fields.PositiveIntegerField', [], {})
+ },
+ 'djangoratings.similaruser': {
+ 'Meta': {'unique_together': "(('from_user', 'to_user'),)", 'object_name': 'SimilarUser'},
+ 'agrees': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
+ 'disagrees': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
+ 'exclude': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'from_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'similar_users'", 'to': "orm['auth.User']"}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'to_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'similar_users_from'", 'to': "orm['auth.User']"})
+ },
+ 'djangoratings.vote': {
+ 'Meta': {'unique_together': "(('content_type', 'object_id', 'key', 'user', 'ip_address', 'cookie'),)", 'object_name': 'Vote'},
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'votes'", 'to': "orm['contenttypes.ContentType']"}),
+ 'cookie': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+ 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'date_changed': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'ip_address': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
+ 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
+ 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
+ 'score': ('django.db.models.fields.IntegerField', [], {}),
+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'votes'", 'null': 'True', 'to': "orm['auth.User']"})
+ }
+ }
+
+ complete_apps = ['djangoratings']
View
@@ -14,6 +14,7 @@ class Vote(models.Model):
score = models.IntegerField()
user = models.ForeignKey(User, blank=True, null=True, related_name="votes")
ip_address = models.IPAddressField()
+ cookie = models.CharField(max_length=32, blank=True, null=True)
date_added = models.DateTimeField(default=datetime.datetime.now, editable=False)
date_changed = models.DateTimeField(default=datetime.datetime.now, editable=False)
@@ -22,7 +23,7 @@ class Vote(models.Model):
content_object = generic.GenericForeignKey()
class Meta:
- unique_together = (('content_type', 'object_id', 'key', 'user', 'ip_address'))
+ unique_together = (('content_type', 'object_id', 'key', 'user', 'ip_address', 'cookie'))
def __unicode__(self):
return u"%s voted %s on %s" % (self.user_display, self.score, self.content_object)
@@ -25,7 +25,7 @@ def render(self, context):
except (template.VariableDoesNotExist, AttributeError):
return ''
try:
- vote = field.get_rating_for_user(request.user, request.META['REMOTE_ADDR'])
+ vote = field.get_rating_for_user(request.user, request.META['REMOTE_ADDR'], request.COOKIES)
context[self.context_var] = vote
except ObjectDoesNotExist:
context[self.context_var] = 0
View
@@ -30,12 +30,12 @@ def __call__(self, request, content_type_id, object_id, field_name, score):
'score': score,
})
- had_voted = bool(field.get_rating_for_user(request.user, request.META['REMOTE_ADDR']))
+ had_voted = bool(field.get_rating_for_user(request.user, request.META['REMOTE_ADDR'], request.COOKIES))
context['had_voted'] = had_voted
try:
- field.add(score, request.user, request.META.get('REMOTE_ADDR'))
+ adds = field.add(score, request.user, request.META.get('REMOTE_ADDR'), request.COOKIES)
except IPLimitReached:
return self.too_many_votes_from_ip_response(request, context)
except AuthRequired:
@@ -45,8 +45,8 @@ def __call__(self, request, content_type_id, object_id, field_name, score):
except CannotChangeVote:
return self.cannot_change_vote_response(request, context)
if had_voted:
- return self.rating_changed_response(request, context)
- return self.rating_added_response(request, context)
+ return self.rating_changed_response(request, context, adds)
+ return self.rating_added_response(request, context, adds)
def get_context(self, request, context={}):
return context
@@ -58,12 +58,16 @@ def too_many_votes_from_ip_response(self, request, context):
response = HttpResponse('Too many votes from this IP address for this object.')
return response
- def rating_changed_response(self, request, context):
+ def rating_changed_response(self, request, context, adds={}):
response = HttpResponse('Vote changed.')
+ if 'cookie' in adds:
+ response.set_cookie(adds['cookie_name'], adds['cookie'], 31536000)
return response
- def rating_added_response(self, request, context):
+ def rating_added_response(self, request, context, adds={}):
response = HttpResponse('Vote recorded.')
+ if 'cookie' in adds:
+ response.set_cookie(adds['cookie_name'], adds['cookie'], 31536000)
return response
def authentication_required_response(self, request, context):

0 comments on commit b75c341

Please sign in to comment.