You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.2 KiB

10 years ago
10 years ago
  1. import base64
  2. import os
  3. import uuid
  4. from datetime import timedelta
  5. from django.conf import settings
  6. from django.contrib.auth.hashers import make_password
  7. from django.contrib.auth.models import User
  8. from django.core import signing
  9. from django.core.urlresolvers import reverse
  10. from django.db import models
  11. from django.utils import timezone
  12. from hc.lib import emails
  13. class ProfileManager(models.Manager):
  14. def for_user(self, user):
  15. profile, created = Profile.objects.get_or_create(user_id=user.id)
  16. return profile
  17. class Profile(models.Model):
  18. user = models.OneToOneField(User, blank=True, null=True)
  19. next_report_date = models.DateTimeField(null=True, blank=True)
  20. reports_allowed = models.BooleanField(default=True)
  21. ping_log_limit = models.IntegerField(default=100)
  22. token = models.CharField(max_length=128, blank=True)
  23. api_key = models.CharField(max_length=128, blank=True)
  24. objects = ProfileManager()
  25. def send_instant_login_link(self):
  26. token = str(uuid.uuid4())
  27. self.token = make_password(token)
  28. self.save()
  29. path = reverse("hc-check-token", args=[self.user.username, token])
  30. ctx = {"login_link": settings.SITE_ROOT + path}
  31. emails.login(self.user.email, ctx)
  32. def send_set_password_link(self):
  33. token = str(uuid.uuid4())
  34. self.token = make_password(token)
  35. self.save()
  36. path = reverse("hc-set-password", args=[token])
  37. ctx = {"set_password_link": settings.SITE_ROOT + path}
  38. emails.set_password(self.user.email, ctx)
  39. def set_api_key(self):
  40. self.api_key = base64.urlsafe_b64encode(os.urandom(24))
  41. self.save()
  42. def send_report(self):
  43. # reset next report date first:
  44. now = timezone.now()
  45. self.next_report_date = now + timedelta(days=30)
  46. self.save()
  47. token = signing.Signer().sign(uuid.uuid4())
  48. path = reverse("hc-unsubscribe-reports", args=[self.user.username])
  49. unsub_link = "%s%s?token=%s" % (settings.SITE_ROOT, path, token)
  50. ctx = {
  51. "checks": self.user.check_set.order_by("created"),
  52. "now": now,
  53. "unsub_link": unsub_link
  54. }
  55. emails.report(self.user.email, ctx)