Skip to content

Commit

Permalink
low etc
Browse files Browse the repository at this point in the history
  • Loading branch information
sorl committed Dec 29, 2011
1 parent 379299c commit 5d9e241
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 30 deletions.
6 changes: 3 additions & 3 deletions profilebase/middleware.py
Expand Up @@ -5,13 +5,13 @@ class ProfileMiddleware(object):
def process_request(self, request): def process_request(self, request):
assert hasattr(request, 'session'), "Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." assert hasattr(request, 'session'), "Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
for model in _profiles: for model in _profiles:
name = model.__name__.lower() session_key = '_%s_id' % model.__namelow__
session_key = '_%s_id' % name
pk = request.session.get(session_key) pk = request.session.get(session_key)
profile = EmptyProfile() profile = EmptyProfile()
if pk is not None: if pk is not None:
try: try:
profile = model.objects.get(is_active=True, pk=pk) profile = model.objects.get(is_active=True, pk=pk)
except model.DoesNotExist: except model.DoesNotExist:
request.session.pop(session_key) request.session.pop(session_key)
setattr(request, name, profile) setattr(request, model.__namelow__, profile)

41 changes: 19 additions & 22 deletions profilebase/models.py
@@ -1,16 +1,14 @@
import datetime import datetime
import hashlib import hashlib
import random import random
from .utils import uncamel
from django.conf import settings from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.cache import cache from django.core.cache import cache
from django.core.mail import send_mail from django.core.mail import send_mail
from django.db import models from django.db import models
from django.db.models import Q
from django.db.models.base import ModelBase from django.db.models.base import ModelBase
from django.db.models.fields import Field from django.db.models.fields import Field
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.utils.encoding import smart_str from django.utils.encoding import smart_str
from django.utils.http import urlquote from django.utils.http import urlquote
Expand Down Expand Up @@ -46,6 +44,7 @@ def __new__(cls, name, bases, attrs):
if k not in attrs: if k not in attrs:
attrs[k] = cls.base_fields[k] attrs[k] = cls.base_fields[k]
model = ModelBase.__new__(cls, name, bases, attrs) model = ModelBase.__new__(cls, name, bases, attrs)
model.__namelow__ = uncamel(model.__name__)
_profiles.append(model) _profiles.append(model)
return model return model


Expand All @@ -64,7 +63,6 @@ def __getattr__(self, name):
class ProfileBase(models.Model): class ProfileBase(models.Model):
__metaclass__ = ProfileBaseMeta __metaclass__ = ProfileBaseMeta


username = StringField(_('username'), unique=True, null=True, blank=True)
email = EmailField(_('email'), unique=True) email = EmailField(_('email'), unique=True)
password = StringField(editable=False) password = StringField(editable=False)
is_active = models.BooleanField(_('active'), default=True) is_active = models.BooleanField(_('active'), default=True)
Expand All @@ -73,8 +71,11 @@ class ProfileBase(models.Model):
created = models.DateTimeField(_('created'), auto_now_add=True, editable=False) created = models.DateTimeField(_('created'), auto_now_add=True, editable=False)
updated = models.DateTimeField(_('updated'), auto_now=True, editable=False) updated = models.DateTimeField(_('updated'), auto_now=True, editable=False)


def login_url(self, next_=''):
return '/login/?next=%s' % next_

def __unicode__(self): def __unicode__(self):
return self.username or self.email return self.email


def is_authenticated(self): def is_authenticated(self):
return True return True
Expand All @@ -100,37 +101,34 @@ def login(self, request):
Persist a profile id in the request. This way a profile doesn't have to Persist a profile id in the request. This way a profile doesn't have to
reauthenticate on every request. reauthenticate on every request.
""" """
name = self.__class__.__name__.lower() session_key = '_%s_id' % self.__namelow__
session_key = '_%s_id' % name
request.session.pop(session_key, None) request.session.pop(session_key, None)
request.session.cycle_key() request.session.cycle_key()
request.session[session_key] = self.pk request.session[session_key] = self.pk
self.last_login = datetime.datetime.now() self.last_login = datetime.datetime.now()
ProfileBase.save(self) ProfileBase.save(self)
setattr(request, name, self) setattr(request, self.__namelow__, self)


@classmethod @classmethod
def logout(cls, request): def logout(cls, request):
""" """
Removes the authenticated profile's id from the request and deletes key Removes the authenticated profile's id from the request and deletes key
from their session data. from their session data.
""" """
name = cls.__name__.lower() session_key = '_%s_id' % cls.__namelow__
session_key = '_%s_id' % name
request.session.pop(session_key, None) request.session.pop(session_key, None)
setattr(request, name, EmptyProfile()) setattr(request, cls.__namelow__, EmptyProfile())


@classmethod @classmethod
def profile_required(cls, view, redirect_field_name=REDIRECT_FIELD_NAME): def profile_required(cls, view):
"""Check that a profile for this class is authenticated""" """
login_url = settings.LOGIN_URL Check that a profile for this class is authenticated
"""
def wrapped(request, *args, **kwargs): def wrapped(request, *args, **kwargs):
name = cls.__name__.lower() profile = getattr(request, cls.__namelow__, None)
profile = getattr(request, name, None) if not profile.is_authenticated():
if not(profile and profile.is_authenticated()):
path = urlquote(request.get_full_path()) path = urlquote(request.get_full_path())
redir = login_url, redirect_field_name, path return HttpResponseRedirect(cls.login_url(path))
return HttpResponseRedirect('%s?%s=%s' % redir)
return view(request, *args, **kwargs) return view(request, *args, **kwargs)
return wrapped return wrapped


Expand All @@ -144,14 +142,13 @@ def authenticate(cls, login, password):
@classmethod @classmethod
def get_profiles(cls, login): def get_profiles(cls, login):
profiles = cls._default_manager.filter( profiles = cls._default_manager.filter(
Q(is_active=True) & is_active=True, email__iexact=login
(Q(email__iexact=login) | Q(username__iexact=login))
) )
return profiles return profiles


@classmethod @classmethod
def make_password_reset_key(cls, code): def make_password_reset_key(cls, code):
return 'profilebase.reset.%s.%s' % (cls.__name__.lower(), code) return 'profilebase.reset.%s.%s' % (cls.__namelow__, code)


@classmethod @classmethod
def get_profile_by_code(cls, code): def get_profile_by_code(cls, code):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -10,7 +10,7 @@ def run(self):


setup( setup(
name='django-profilebase', name='django-profilebase',
version='0.1.1', version='0.2.0',
description='Tools for building a custom Profile class with authentication', description='Tools for building a custom Profile class with authentication',
long_description=open('README.rst').read(), long_description=open('README.rst').read(),
author='Mikko Hellsing', author='Mikko Hellsing',
Expand Down
7 changes: 3 additions & 4 deletions tests/profilebase_tests/tests.py
Expand Up @@ -7,22 +7,21 @@


class SimpleTestCase(unittest.TestCase): class SimpleTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
self.p = Profile.objects.create(username='xxx', email='xxx@xxx.com') self.p = Profile.objects.create(email='xxx@xxx.com')


def tearDown(self): def tearDown(self):
self.p.delete() self.p.delete()


def test_unicode(self): def test_unicode(self):
self.assertEqual(u'xxx', unicode(self.p)) self.assertEqual(u'xxx@xxx.com', unicode(self.p))


def test_authentication1(self): def test_authentication1(self):
self.assertEqual(Profile.authenticate('xxx', 'yyy'), None) self.assertEqual(Profile.authenticate('xxx', 'yyy'), None)


def test_authentication2(self): def test_authentication2(self):
self.p.set_password('yyy') self.p.set_password('yyy')
self.p.save() self.p.save()
self.assertEqual(Profile.authenticate('xxx', 'yyy'), self.p) self.assertEqual(Profile.authenticate('xxx@xxx.com', 'zzz'), None)
self.assertEqual(Profile.authenticate('xxx', 'zzz'), None)
self.assertEqual(Profile.authenticate('xxx@xxx.com', 'yyy'), self.p) self.assertEqual(Profile.authenticate('xxx@xxx.com', 'yyy'), self.p)


def test_login_logout(self): def test_login_logout(self):
Expand Down

0 comments on commit 5d9e241

Please sign in to comment.