Skip to content

Commit

Permalink
password reset form
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperp committed Dec 21, 2011
1 parent d733bd6 commit 379299c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
23 changes: 23 additions & 0 deletions profilebase/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,29 @@
from django.utils.translation import ugettext_lazy as _


class PasswordResetForm(forms.Form):
email = forms.EmailField(
label=_(u'Email'),
)

def __init__(self, profile_cls, **kwargs):
self.profile_cls = profile_cls
self.profiles = None
super(PasswordResetForm, self).__init__(**kwargs)

def clean_email(self):
data = self.cleaned_data
email = data['email']
self.profiles = self.profile_cls.get_profiles(email)
if not self.profiles.exists():
raise forms.ValidationError(_(u'No account with that email'))
return data

def save(self, *kwargs):
for profile in self.profiles:
profile.send_password_reset()


class NewPasswordForm(forms.Form):
password = forms.CharField(
label=_(u'Password'),
Expand Down
19 changes: 14 additions & 5 deletions profilebase/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,18 @@ def wrapped(request, *args, **kwargs):

@classmethod
def authenticate(cls, login, password):
profiles = cls.get_profiles(login)
for profile in profiles:
if profile.check_password(password):
return profile

@classmethod
def get_profiles(cls, login):
profiles = cls._default_manager.filter(
Q(is_active=True) &
(Q(email__iexact=login) | Q(username__iexact=login))
)
for profile in profiles:
if profile.check_password(password):
return profile
return profiles

@classmethod
def make_password_reset_key(cls, code):
Expand All @@ -157,11 +162,10 @@ def get_profile_by_code(cls, code):
except cls.DoesNotExist:
return None

def send_password_reset(self):
def send_password_reset(self, timeout=3600):
import uuid
code = uuid.uuid4().hex
cache_key = self.make_password_reset_key(code)
timeout = 60 * 60 * 24 * settings.PASSWORD_RESET_TIMEOUT_DAYS
cache.set(cache_key, self.pk, timeout)
ctx = { 'code': code, 'profile': self }
text = render_to_string('profilebase/password_reset_email.txt', ctx)
Expand All @@ -173,6 +177,11 @@ def login_form(cls, **kwargs):
from .forms import LoginForm
return LoginForm(cls.authenticate, **kwargs)

@classmethod
def password_reset_form(cls, **kwargs):
from .forms import PasswordResetForm
return PasswordResetForm(cls, **kwargs)

class Meta:
abstract = True
ordering = ('created',)
Expand Down

0 comments on commit 379299c

Please sign in to comment.