Last fix
[auf_django_auth_token.git] / auf / django / auth_token / models.py
1 from django.conf import settings
2 from django.db import models
3 from django.utils.crypto import get_random_string
4 from django.contrib.auth import models as auth
5 from django.template import RequestContext
6 from django.template.loader import render_to_string
7 from django.core.mail.message import EmailMultiAlternatives
8
9
10 AUTH_TOKEN_PARAM = getattr(settings, 'AUTH_TOKEN_PARAM', 'auth_token')
11 ALLOW_UNSECURED_TOKEN_AUTH = getattr(
12 settings, 'AUTH_ALLOW_UNSECURED_TOKEN_AUTH', False)
13
14 EMAIL_SUBJECT = getattr(
15 settings, 'AUTH_TOKEN_EMAIL_SUBJECT', (
16 'Your new token.'))
17 EMAIL_FROM = getattr(
18 settings, 'AUTH_TOKEN_EMAIL_FROM', None)
19 EMAIL_TEMPLATE = getattr(
20 settings, 'AUTH_TOKEN_EMAIL_TEMPLATE', (
21 'token_auth/new_token_email.html'))
22 EMAIL_ALTERNATIVE_TEMPLATE = getattr(
23 settings, 'AUTH_TOKEN_EMAIL_TEMPLATE', (
24 'token_auth/new_token_email.txt'))
25 LOGIN_URL_TEMPLATE = getattr(
26 settings, 'AUTH_TOKEN_EMAIL_TEMPLATE', (
27 '%(protocol)s://%(host)s/?%(token_param)s=%(token)s'))
28
29
30 class Token(models.Model):
31 value = models.CharField(
32 max_length=48,
33 default=lambda: get_random_string(48),
34 )
35 user = models.OneToOneField(
36 auth.User,
37 related_name='auf_auth_token')
38
39 sent_by_email = models.BooleanField()
40
41 def send_token_by_email(self, request, recipients=[]):
42
43 url = LOGIN_URL_TEMPLATE % {
44 'protocol': ('https' if (
45 request.is_secure() or not
46 ALLOW_UNSECURED_TOKEN_AUTH) else 'http'),
47 'host': request.get_host(),
48 'token_param': AUTH_TOKEN_PARAM,
49 'token': self.value,
50 }
51
52 tpl_data = {
53 'token': self,
54 'url': url,
55 }
56
57 sender = EMAIL_FROM
58 if not sender:
59 sender = 'noreply@%s' % request.get_host()
60
61 html_response = render_to_string(
62 EMAIL_TEMPLATE,
63 tpl_data,
64 context_instance=RequestContext(request, {}),
65 )
66
67 text_response = render_to_string(
68 EMAIL_ALTERNATIVE_TEMPLATE,
69 tpl_data,
70 context_instance=RequestContext(request, {}),
71 )
72
73 if not recipients:
74 recipients = [self.user.email]
75
76 if not self.sent_by_email:
77 msg = EmailMultiAlternatives(
78 EMAIL_SUBJECT,
79 text_response,
80 sender,
81 recipients,
82 )
83 msg.attach_alternative(html_response, "text/html")
84 msg.send()
85
86
87 def reset_token(self, save=True):
88 self.value = get_random_string(48)
89 self.email_sent = False
90 if save:
91 self.save()
92
93 def __unicode__(self):
94 return self.value
95