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.

216 lines
7.1 KiB

10 years ago
8 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 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 check_password, make_password
  7. from django.contrib.auth.models import User
  8. from django.core.signing import TimestampSigner
  9. from django.db import models
  10. from django.urls import reverse
  11. from django.utils import timezone
  12. from hc.lib import emails
  13. NO_NAG = timedelta()
  14. NAG_PERIODS = ((NO_NAG, "Disabled"),
  15. (timedelta(hours=1), "Hourly"),
  16. (timedelta(days=1), "Daily"))
  17. def month(dt):
  18. """ For a given datetime, return the matching first-day-of-month date. """
  19. return dt.date().replace(day=1)
  20. class ProfileManager(models.Manager):
  21. def for_user(self, user):
  22. try:
  23. return user.profile
  24. except Profile.DoesNotExist:
  25. profile = Profile(user=user)
  26. if not settings.USE_PAYMENTS:
  27. # If not using payments, set high limits
  28. profile.check_limit = 500
  29. profile.sms_limit = 500
  30. profile.team_limit = 500
  31. profile.save()
  32. return profile
  33. class Profile(models.Model):
  34. # Owner:
  35. user = models.OneToOneField(User, models.CASCADE, blank=True, null=True)
  36. team_name = models.CharField(max_length=200, blank=True)
  37. next_report_date = models.DateTimeField(null=True, blank=True)
  38. reports_allowed = models.BooleanField(default=True)
  39. nag_period = models.DurationField(default=NO_NAG, choices=NAG_PERIODS)
  40. next_nag_date = models.DateTimeField(null=True, blank=True)
  41. ping_log_limit = models.IntegerField(default=100)
  42. check_limit = models.IntegerField(default=20)
  43. token = models.CharField(max_length=128, blank=True)
  44. api_key = models.CharField(max_length=128, blank=True)
  45. current_team = models.ForeignKey("self", models.SET_NULL, null=True)
  46. bill_to = models.TextField(blank=True)
  47. last_sms_date = models.DateTimeField(null=True, blank=True)
  48. sms_limit = models.IntegerField(default=0)
  49. sms_sent = models.IntegerField(default=0)
  50. team_limit = models.IntegerField(default=2)
  51. sort = models.CharField(max_length=20, default="created")
  52. objects = ProfileManager()
  53. def __str__(self):
  54. return self.team_name or self.user.email
  55. def notifications_url(self):
  56. return settings.SITE_ROOT + reverse("hc-notifications")
  57. def reports_unsub_url(self):
  58. signer = TimestampSigner(salt="reports")
  59. signed_username = signer.sign(self.user.username)
  60. path = reverse("hc-unsubscribe-reports", args=[signed_username])
  61. return settings.SITE_ROOT + path
  62. def team(self):
  63. # compare ids to avoid SQL queries
  64. if self.current_team_id and self.current_team_id != self.id:
  65. return self.current_team
  66. return self
  67. def prepare_token(self, salt):
  68. token = str(uuid.uuid4())
  69. self.token = make_password(token, salt)
  70. self.save()
  71. return token
  72. def check_token(self, token, salt):
  73. return salt in self.token and check_password(token, self.token)
  74. def send_instant_login_link(self, inviting_profile=None):
  75. token = self.prepare_token("login")
  76. path = reverse("hc-check-token", args=[self.user.username, token])
  77. ctx = {
  78. "button_text": "Log In",
  79. "button_url": settings.SITE_ROOT + path,
  80. "inviting_profile": inviting_profile
  81. }
  82. emails.login(self.user.email, ctx)
  83. def send_set_password_link(self):
  84. token = self.prepare_token("set-password")
  85. path = reverse("hc-set-password", args=[token])
  86. ctx = {
  87. "button_text": "Set Password",
  88. "button_url": settings.SITE_ROOT + path
  89. }
  90. emails.set_password(self.user.email, ctx)
  91. def send_change_email_link(self):
  92. token = self.prepare_token("change-email")
  93. path = reverse("hc-change-email", args=[token])
  94. ctx = {
  95. "button_text": "Change Email",
  96. "button_url": settings.SITE_ROOT + path
  97. }
  98. emails.change_email(self.user.email, ctx)
  99. def set_api_key(self):
  100. self.api_key = base64.urlsafe_b64encode(os.urandom(24))
  101. self.save()
  102. def checks_from_all_teams(self):
  103. """ Return a queryset of checks from all teams we have access for. """
  104. team_ids = set(self.user.memberships.values_list("team_id", flat=True))
  105. team_ids.add(self.id)
  106. from hc.api.models import Check
  107. return Check.objects.filter(user__profile__id__in=team_ids)
  108. def send_report(self, nag=False):
  109. checks = self.checks_from_all_teams()
  110. # Is there at least one check that has received a ping?
  111. if not checks.filter(last_ping__isnull=False).exists():
  112. return False
  113. # Is there at least one check that is down?
  114. num_down = checks.filter(status="down").count()
  115. if nag and num_down == 0:
  116. return False
  117. # Sort checks by owner. Need this because will group by owner in
  118. # template.
  119. checks = checks.order_by("user_id")
  120. ctx = {
  121. "checks": checks,
  122. "sort": self.sort,
  123. "now": timezone.now(),
  124. "unsub_link": self.reports_unsub_url(),
  125. "notifications_url": self.notifications_url(),
  126. "nag": nag,
  127. "nag_period": self.nag_period.total_seconds(),
  128. "num_down": num_down
  129. }
  130. emails.report(self.user.email, ctx)
  131. return True
  132. def can_invite(self):
  133. return self.member_set.count() < self.team_limit
  134. def invite(self, user):
  135. member = Member(team=self, user=user)
  136. member.save()
  137. # Switch the invited user over to the new team so they
  138. # notice the new team on next visit:
  139. user.profile.current_team = self
  140. user.profile.save()
  141. user.profile.send_instant_login_link(self)
  142. def sms_sent_this_month(self):
  143. # IF last_sms_date was never set, we have not sent any messages yet.
  144. if not self.last_sms_date:
  145. return 0
  146. # If last sent date is not from this month, we've sent 0 this month.
  147. if month(timezone.now()) > month(self.last_sms_date):
  148. return 0
  149. return self.sms_sent
  150. def authorize_sms(self):
  151. """ If monthly limit not exceeded, increase counter and return True """
  152. sent_this_month = self.sms_sent_this_month()
  153. if sent_this_month >= self.sms_limit:
  154. return False
  155. self.sms_sent = sent_this_month + 1
  156. self.last_sms_date = timezone.now()
  157. self.save()
  158. return True
  159. def set_next_nag_date(self):
  160. """ Set next_nag_date for all members of this team. """
  161. is_owner = models.Q(id=self.id)
  162. is_member = models.Q(user__memberships__team=self)
  163. q = Profile.objects.filter(is_owner | is_member)
  164. q = q.exclude(nag_period=NO_NAG)
  165. # Exclude profiles with next_nag_date already set
  166. q = q.filter(next_nag_date__isnull=True)
  167. q.update(next_nag_date=timezone.now() + models.F("nag_period"))
  168. class Member(models.Model):
  169. team = models.ForeignKey(Profile, models.CASCADE)
  170. user = models.ForeignKey(User, models.CASCADE, related_name="memberships")