def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, the key will have been
reset to the string constant ``ACTIVATED``. Re-activating
is not permitted, and so this method returns ``True`` in
this case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
return self.activation_key == RegistrationProfile.ACTIVATED or \
(self.user.date_joined + expiration_date <= datetime.datetime.now())
python类ACCOUNT_ACTIVATION_DAYS的实例源码
def send_info_email(self, user):
profile = RegistrationProfile.objects.get(user=user)
site = Site.objects.get_current()
ctx_dict = {'activation_key': profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'install_main_url' : settings.INSTALL_MAIN_URL,
'conference_name' : settings.CONFERENCE_NAME,
'site': site,
'project' : self.object,
'user' : user}
subject = render_to_string('registration/activation_email_autocreate_subject.txt', ctx_dict)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('registration/activation_email_autocreate.txt', ctx_dict)
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
def test_expired_activation(self):
"""
Attempting to activate outside the permitted window does not
activate the account.
"""
new_user = RegistrationProfile.objects.create_inactive_user(
site=Site.objects.get_current(), **self.user_info)
new_user.date_joined -= datetime.timedelta(
days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
new_user.save()
profile = RegistrationProfile.objects.get(user=new_user)
activated = (RegistrationProfile.objects
.activate_user(profile.activation_key))
self.failIf(isinstance(activated, UserModel()))
self.failIf(activated)
new_user = UserModel().objects.get(username='alice')
self.failIf(new_user.is_active)
profile = RegistrationProfile.objects.get(user=new_user)
self.assertFalse(profile.activated)
def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, ``self.activated`` will
be ``True``. Re-activating is not permitted, and so this
method returns ``True`` in this case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = datetime.timedelta(
days=settings.ACCOUNT_ACTIVATION_DAYS)
return (self.activated or
(self.user.date_joined + expiration_date <= datetime_now()))
def validate_key(self, activation_key):
try:
username = signing.loads(
activation_key,
salt=settings.REGISTRATION_SALT,
max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400
)
return username
# SignatureExpired is a subclass of BadSignature, so this will
# catch either one.
except signing.SignatureExpired:
self.template_name = "accounts/activation_error.html"
self.error_reason = "Your code has expired"
return None
except signing.BadSignature:
self.template_name = "accounts/activation_error.html"
self.error_reason = "Bad activation key"
return None
def test_expired_activation(self):
"""
Attempting to activate outside the permitted window does not
activate the account.
"""
new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
**self.user_info)
new_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
new_user.save()
profile = RegistrationProfile.objects.get(user=new_user)
activated = RegistrationProfile.objects.activate_user(profile.activation_key)
self.failIf(isinstance(activated, User))
self.failIf(activated)
new_user = User.objects.get(username='alice')
self.failIf(new_user.is_active)
profile = RegistrationProfile.objects.get(user=new_user)
self.assertNotEqual(profile.activation_key, RegistrationProfile.ACTIVATED)
def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, the key will have been
reset to the string constant ``ACTIVATED``. Re-activating
is not permitted, and so this method returns ``True`` in
this case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
return self.activation_key == self.ACTIVATED or \
(self.user.date_joined + expiration_date <= datetime.datetime.now())
def validate_key(self, activation_key):
"""
Verify that the activation key is valid and within the
permitted activation time window, returning the username if
valid or ``None`` if not.
"""
try:
username = signing.loads(
activation_key,
salt=REGISTRATION_SALT,
max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400
)
return username
# SignatureExpired is a subclass of BadSignature, so this will
# catch either one.
except signing.BadSignature:
return None
def test_expired_account(self):
"""
RegistrationProfile.activation_key_expired() is True outside
the activation window.
"""
new_user = RegistrationProfile.objects.create_inactive_user(
self.get_form(),
site=self.get_site()
)
new_user.date_joined -= datetime.timedelta(
days=settings.ACCOUNT_ACTIVATION_DAYS + 1
)
new_user.save()
profile = RegistrationProfile.objects.get(user=new_user)
self.assertTrue(profile.activation_key_expired())
def expired(self):
"""
Query for all profiles which are expired and correspond to
non-active users.
"""
if settings.USE_TZ:
now = timezone.now()
else:
now = datetime.datetime.now()
return self.exclude(
user__is_active=True
).filter(
models.Q(activation_key=self.model.ACTIVATED) |
models.Q(
user__date_joined__lt=now - datetime.timedelta(
settings.ACCOUNT_ACTIVATION_DAYS
)
)
)
def send_activation_email(self, site):
"""
Send an activation email to the user associated with this
``RegistrationProfile``.
"""
ctx_dict = {'activation_key': self.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'user': self.user,
'site': site}
subject = render_to_string('registration/activation_email_subject.txt',
ctx_dict)
# Force subject to a single line to avoid header-injection
# issues.
subject = ''.join(subject.splitlines())
message = render_to_string('registration/activation_email.txt',
ctx_dict)
self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
def activation_key_expired( self ):
"""
Determine whether this :class:`GroupInvitation`'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, the key will have been
reset to the string ``ALREADY_ACTIVATED``. Re-activating is
not permitted, and so this method returns ``True`` in this
case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = \
datetime.timedelta( days = settings.ACCOUNT_ACTIVATION_DAYS )
return self.activation_key == self.ACTIVATED or \
( self.issue_date + expiration_date <= datetime.date.today() )
# TODO: find out and explain here what this means:
def setUp(self):
"""
Create an instance of the default backend for use in testing,
and set ``ACCOUNT_ACTIVATION_DAYS`` if it's not set already.
"""
self.old_activation = getattr(settings,
'ACCOUNT_ACTIVATION_DAYS', None)
if self.old_activation is None:
settings.ACCOUNT_ACTIVATION_DAYS = 7 # pragma: no cover
def tearDown(self):
"""
Yank ``ACCOUNT_ACTIVATION_DAYS`` back out if it wasn't
originally set.
"""
if self.old_activation is None:
# pragma: no cover
settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation
def tearDown(self):
settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation
settings.REGISTRATION_DEFAULT_FROM_EMAIL = self.old_reg_email
settings.REGISTRATION_EMAIL_HTML = self.old_email_html
settings.DEFAULT_FROM_EMAIL = self.old_django_email
def tearDown(self):
settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation
settings.REGISTRATION_DEFAULT_FROM_EMAIL = self.old_reg_email
settings.REGISTRATION_EMAIL_HTML = self.old_email_html
settings.DEFAULT_FROM_EMAIL = self.old_django_email
def test_expired_account(self):
"""
``RegistrationProfile.activation_key_expired()`` is ``True``
outside the activation window.
"""
new_user = RegistrationProfile.objects.create_inactive_user(
site=Site.objects.get_current(), **self.user_info)
new_user.date_joined -= datetime.timedelta(
days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
new_user.save()
profile = RegistrationProfile.objects.get(user=new_user)
self.failUnless(profile.activation_key_expired())
def setUp(self):
"""
Create an instance of the default backend for use in testing,
and set ``ACCOUNT_ACTIVATION_DAYS`` if it's not set already.
"""
self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
if self.old_activation is None:
settings.ACCOUNT_ACTIVATION_DAYS = 7 # pragma: no cover
def tearDown(self):
"""
Yank out ``ACCOUNT_ACTIVATION_DAYS`` back out if it wasn't
originally set.
"""
if self.old_activation is None:
settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation # pragma: no cover
def setUp(self):
"""
These tests use the default backend, since we know it's
available; that needs to have ``ACCOUNT_ACTIVATION_DAYS`` set.
"""
self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
if self.old_activation is None:
settings.ACCOUNT_ACTIVATION_DAYS = 7 # pragma: no cover
def setUp(self):
self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
settings.ACCOUNT_ACTIVATION_DAYS = 7
def tearDown(self):
settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation
def test_expired_account(self):
"""
``RegistrationProfile.activation_key_expired()`` is ``True``
outside the activation window.
"""
new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
**self.user_info)
new_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
new_user.save()
profile = RegistrationProfile.objects.get(user=new_user)
self.failUnless(profile.activation_key_expired())
def get_email_context(self, activation_key):
"""
Build the template context used for the activation email.
"""
return {
'activation_key': activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': get_current_site(self.request)
}
def test_expired_activation(self):
"""
Attempting to activate outside the permitted window doesn't
activate the account.
"""
new_user = RegistrationProfile.objects.create_inactive_user(
form=self.get_form(),
site=self.get_site()
)
new_user.date_joined -= datetime.timedelta(
days=settings.ACCOUNT_ACTIVATION_DAYS + 1
)
new_user.save()
profile = RegistrationProfile.objects.get(user=new_user)
activated = RegistrationProfile.objects.activate_user(
profile.activation_key
)
self.assertFalse(isinstance(activated, User))
self.assertFalse(activated)
new_user = User.objects.get(**self.user_lookup_kwargs)
self.assertFalse(new_user.is_active)
profile = RegistrationProfile.objects.get(user=new_user)
self.assertNotEqual(
profile.activation_key,
RegistrationProfile.ACTIVATED
)
def test_activation_expired(self):
"""
An expired account can't be activated.
"""
resp = self.client.post(
reverse('registration_register'),
data=self.valid_data
)
profile = RegistrationProfile.objects.get(
user__username=self.valid_data['username']
)
user = profile.user
user.date_joined -= datetime.timedelta(
days=settings.ACCOUNT_ACTIVATION_DAYS + 1
)
user.save()
resp = self.client.get(
reverse(
'registration_activate',
args=(),
kwargs={'activation_key': profile.activation_key}
)
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'registration/activate.html')
def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired, ``False`` otherwise.
"""
expiration_date = datetime.timedelta(
days=settings.ACCOUNT_ACTIVATION_DAYS
)
return self.activation_key == self.ACTIVATED or \
(self.user.date_joined + expiration_date <= timezone.now())
def activate(request, activation_key,
template_name='registration/activate.html',
extra_context=None):
"""
Activate a ``User``'s account from an activation key, if their key
is valid and hasn't expired.
By default, use the template ``registration/activate.html``; to
change this, pass the name of a template as the keyword argument
``template_name``.
**Required arguments**
``activation_key``
The activation key to validate and use for activating the
``User``.
**Optional arguments**
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``template_name``
A custom template to use.
**Context:**
``account``
The ``User`` object corresponding to the account, if the
activation was successful. ``False`` if the activation was not
successful.
``expiration_days``
The number of days for which activation keys stay valid after
registration.
Any extra variables supplied in the ``extra_context`` argument
(see above).
**Template:**
registration/activate.html or ``template_name`` keyword argument.
"""
activation_key = activation_key.lower() # Normalize before trying anything with it.
account = RegistrationProfile.objects.activate_user(activation_key)
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
context_instance=context)
def send_activation_email(self, site, name=""):
"""
Send an activation email to the user associated with this
``RegistrationProfile``.
The activation email will make use of two templates:
``registration/activation_email_subject.txt``
This template will be used for the subject line of the
email. Because it is used as the subject line of an email,
this template's output **must** be only a single line of
text; output longer than one line will be forcibly joined
into only a single line.
``registration/activation_email.txt``
This template will be used for the body of the email.
These templates will each receive the following context
variables:
``activation_key``
The activation key for the new account.
``expiration_days``
The number of days remaining during which the account may
be activated.
``site``
An object representing the site on which the user
registered; depending on whether ``django.contrib.sites``
is installed, this may be an instance of either
``django.contrib.sites.models.Site`` (if the sites
application is installed) or
``django.contrib.sites.models.RequestSite`` (if
not). Consult the documentation for the Django sites
framework for details regarding these objects' interfaces.
"""
ctx_dict = {'activation_key': self.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': site,
'name': name}
subject = render_to_string('registration/activation_email_subject.txt',
ctx_dict)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
html_content = render_to_string('registration/activation_email.html',
ctx_dict)
text_content = render_to_string('registration/activation_email.txt',
ctx_dict) # so people will have the text as well.
# create the email, and attach the HTML version as well.
try:
msg = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL, [self.user.email])
msg.attach_alternative(html_content, "text/html")
msg.send()
except smtplib.SMTPException:
self.user.email_user(subject, text_content, settings.DEFAULT_FROM_EMAIL)
def test_activation_expired(self):
"""
An expired account can't be activated.
"""
self.client.post(
reverse('registration_register'),
data=self.valid_data
)
# We need to create an activation key valid for the username,
# but with a timestamp > ACCOUNT_ACTIVATION_DAYS days in the
# past. This requires monkeypatching time.time() to return
# that timestamp, since TimestampSigner uses time.time().
#
# On Python 3.3+ this is much easier because of the
# timestamp() method of datetime objects, but since
# django-registration has to run on Python 2.7, we manually
# calculate it using a timedelta between the signup date and
# the UNIX epoch, and patch time.time() temporarily to return
# a date (ACCOUNT_ACTIVATION_DAYS + 1) days in the past.
user = self.user_model.objects.get(**self.user_lookup_kwargs)
joined_timestamp = (
user.date_joined - datetime.datetime.fromtimestamp(0)
).total_seconds()
expired_timestamp = (
joined_timestamp - (settings.ACCOUNT_ACTIVATION_DAYS + 1) * 86400
)
_old_time = time.time
time.time = lambda: expired_timestamp
try:
activation_key = signing.dumps(
obj=self.valid_data['username'],
salt=REGISTRATION_SALT
)
finally:
time.time = _old_time
resp = self.client.get(
reverse(
'registration_activate',
args=(),
kwargs={'activation_key': activation_key}
)
)
self.assertEqual(200, resp.status_code)
self.assertTemplateUsed(resp, 'registration/activate.html')