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.

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