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.

251 lines
8.5 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
  1. from base64 import urlsafe_b64encode
  2. from datetime import timedelta
  3. import os
  4. import uuid
  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. user = models.OneToOneField(User, models.CASCADE, blank=True, null=True)
  35. next_report_date = models.DateTimeField(null=True, blank=True)
  36. reports_allowed = models.BooleanField(default=True)
  37. nag_period = models.DurationField(default=NO_NAG, choices=NAG_PERIODS)
  38. next_nag_date = models.DateTimeField(null=True, blank=True)
  39. ping_log_limit = models.IntegerField(default=100)
  40. check_limit = models.IntegerField(default=20)
  41. token = models.CharField(max_length=128, blank=True)
  42. current_project = models.ForeignKey("Project", models.SET_NULL, null=True)
  43. last_sms_date = models.DateTimeField(null=True, blank=True)
  44. sms_limit = models.IntegerField(default=0)
  45. sms_sent = models.IntegerField(default=0)
  46. team_limit = models.IntegerField(default=2)
  47. sort = models.CharField(max_length=20, default="created")
  48. objects = ProfileManager()
  49. def __str__(self):
  50. return "Profile for %s" % self.user.email
  51. def notifications_url(self):
  52. return settings.SITE_ROOT + reverse("hc-notifications")
  53. def reports_unsub_url(self):
  54. signer = TimestampSigner(salt="reports")
  55. signed_username = signer.sign(self.user.username)
  56. path = reverse("hc-unsubscribe-reports", args=[signed_username])
  57. return settings.SITE_ROOT + path
  58. def prepare_token(self, salt):
  59. token = urlsafe_b64encode(os.urandom(24)).decode()
  60. self.token = make_password(token, salt)
  61. self.save()
  62. return token
  63. def check_token(self, token, salt):
  64. return salt in self.token and check_password(token, self.token)
  65. def send_instant_login_link(self, inviting_project=None, redirect_url=None):
  66. token = self.prepare_token("login")
  67. path = reverse("hc-check-token", args=[self.user.username, token])
  68. if redirect_url:
  69. path += "?next=%s" % redirect_url
  70. ctx = {
  71. "button_text": "Sign In",
  72. "button_url": settings.SITE_ROOT + path,
  73. "inviting_project": inviting_project
  74. }
  75. emails.login(self.user.email, ctx)
  76. def send_set_password_link(self):
  77. token = self.prepare_token("set-password")
  78. path = reverse("hc-set-password", args=[token])
  79. ctx = {
  80. "button_text": "Set Password",
  81. "button_url": settings.SITE_ROOT + path
  82. }
  83. emails.set_password(self.user.email, ctx)
  84. def send_change_email_link(self):
  85. token = self.prepare_token("change-email")
  86. path = reverse("hc-change-email", args=[token])
  87. ctx = {
  88. "button_text": "Change Email",
  89. "button_url": settings.SITE_ROOT + path
  90. }
  91. emails.change_email(self.user.email, ctx)
  92. def projects(self):
  93. """ Return a queryset of all projects we have access to. """
  94. is_owner = models.Q(owner=self.user)
  95. is_member = models.Q(member__user=self.user)
  96. q = Project.objects.filter(is_owner | is_member)
  97. return q.distinct().order_by("name")
  98. def checks_from_all_projects(self):
  99. """ Return a queryset of checks from projects we have access to. """
  100. project_ids = self.projects().values("id")
  101. from hc.api.models import Check
  102. return Check.objects.filter(project_id__in=project_ids)
  103. def send_report(self, nag=False):
  104. checks = self.checks_from_all_projects()
  105. # Has there been a ping in last 6 months?
  106. result = checks.aggregate(models.Max("last_ping"))
  107. last_ping = result["last_ping__max"]
  108. six_months_ago = timezone.now() - timedelta(days=180)
  109. if last_ping is None or last_ping < six_months_ago:
  110. return False
  111. # Is there at least one check that is down?
  112. num_down = checks.filter(status="down").count()
  113. if nag and num_down == 0:
  114. return False
  115. # Sort checks by project. Need this because will group by project in
  116. # template.
  117. checks = checks.select_related("project")
  118. checks = checks.order_by("project_id")
  119. # list() executes the query, to avoid DB access while
  120. # rendering the template
  121. checks = list(checks)
  122. unsub_url = self.reports_unsub_url()
  123. headers = {
  124. "List-Unsubscribe": unsub_url,
  125. "X-Bounce-Url": unsub_url
  126. }
  127. ctx = {
  128. "checks": checks,
  129. "sort": self.sort,
  130. "now": timezone.now(),
  131. "unsub_link": unsub_url,
  132. "notifications_url": self.notifications_url(),
  133. "nag": nag,
  134. "nag_period": self.nag_period.total_seconds(),
  135. "num_down": num_down
  136. }
  137. emails.report(self.user.email, ctx, headers)
  138. return True
  139. def sms_sent_this_month(self):
  140. # IF last_sms_date was never set, we have not sent any messages yet.
  141. if not self.last_sms_date:
  142. return 0
  143. # If last sent date is not from this month, we've sent 0 this month.
  144. if month(timezone.now()) > month(self.last_sms_date):
  145. return 0
  146. return self.sms_sent
  147. def authorize_sms(self):
  148. """ If monthly limit not exceeded, increase counter and return True """
  149. sent_this_month = self.sms_sent_this_month()
  150. if sent_this_month >= self.sms_limit:
  151. return False
  152. self.sms_sent = sent_this_month + 1
  153. self.last_sms_date = timezone.now()
  154. self.save()
  155. return True
  156. class Project(models.Model):
  157. code = models.UUIDField(default=uuid.uuid4, unique=True)
  158. name = models.CharField(max_length=200, blank=True)
  159. owner = models.ForeignKey(User, models.CASCADE)
  160. api_key = models.CharField(max_length=128, blank=True)
  161. api_key_readonly = models.CharField(max_length=128, blank=True)
  162. badge_key = models.CharField(max_length=150, unique=True)
  163. def __str__(self):
  164. return self.name or self.owner.email
  165. @property
  166. def owner_profile(self):
  167. return Profile.objects.for_user(self.owner)
  168. def num_checks_available(self):
  169. from hc.api.models import Check
  170. num_used = Check.objects.filter(project__owner=self.owner).count()
  171. return self.owner_profile.check_limit - num_used
  172. def set_api_keys(self):
  173. self.api_key = urlsafe_b64encode(os.urandom(24)).decode()
  174. self.api_key_readonly = urlsafe_b64encode(os.urandom(24)).decode()
  175. self.save()
  176. def can_invite(self):
  177. return self.member_set.count() < self.owner_profile.team_limit
  178. def invite(self, user):
  179. Member.objects.create(user=user, project=self)
  180. # Switch the invited user over to the new team so they
  181. # notice the new team on next visit:
  182. user.profile.current_project = self
  183. user.profile.save()
  184. user.profile.send_instant_login_link(self)
  185. def set_next_nag_date(self):
  186. """ Set next_nag_date on profiles of all members of this project. """
  187. is_owner = models.Q(user=self.owner)
  188. is_member = models.Q(user__memberships__project=self)
  189. q = Profile.objects.filter(is_owner | is_member)
  190. q = q.exclude(nag_period=NO_NAG)
  191. # Exclude profiles with next_nag_date already set
  192. q = q.filter(next_nag_date__isnull=True)
  193. q.update(next_nag_date=timezone.now() + models.F("nag_period"))
  194. class Member(models.Model):
  195. user = models.ForeignKey(User, models.CASCADE, related_name="memberships")
  196. project = models.ForeignKey(Project, models.CASCADE)