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.

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