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.

393 lines
13 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 datetime import timedelta
  2. from secrets import token_urlsafe
  3. from urllib.parse import quote, urlencode
  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.db.models import Count, Q
  11. from django.urls import reverse
  12. from django.utils import timezone
  13. from fido2.ctap2 import AttestedCredentialData
  14. from hc.lib import emails
  15. from hc.lib.date import month_boundaries
  16. NO_NAG = timedelta()
  17. NAG_PERIODS = (
  18. (NO_NAG, "Disabled"),
  19. (timedelta(hours=1), "Hourly"),
  20. (timedelta(days=1), "Daily"),
  21. )
  22. def month(dt):
  23. """ For a given datetime, return the matching first-day-of-month date. """
  24. return dt.date().replace(day=1)
  25. class ProfileManager(models.Manager):
  26. def for_user(self, user):
  27. try:
  28. return user.profile
  29. except Profile.DoesNotExist:
  30. profile = Profile(user=user)
  31. if not settings.USE_PAYMENTS:
  32. # If not using payments, set high limits
  33. profile.check_limit = 500
  34. profile.sms_limit = 500
  35. profile.call_limit = 500
  36. profile.team_limit = 500
  37. profile.save()
  38. return profile
  39. class Profile(models.Model):
  40. user = models.OneToOneField(User, models.CASCADE, blank=True, null=True)
  41. next_report_date = models.DateTimeField(null=True, blank=True)
  42. reports_allowed = models.BooleanField(default=True)
  43. nag_period = models.DurationField(default=NO_NAG, choices=NAG_PERIODS)
  44. next_nag_date = models.DateTimeField(null=True, blank=True)
  45. ping_log_limit = models.IntegerField(default=100)
  46. check_limit = models.IntegerField(default=20)
  47. token = models.CharField(max_length=128, blank=True)
  48. last_sms_date = models.DateTimeField(null=True, blank=True)
  49. sms_limit = models.IntegerField(default=5)
  50. sms_sent = models.IntegerField(default=0)
  51. last_call_date = models.DateTimeField(null=True, blank=True)
  52. call_limit = models.IntegerField(default=0)
  53. calls_sent = models.IntegerField(default=0)
  54. team_limit = models.IntegerField(default=2)
  55. sort = models.CharField(max_length=20, default="created")
  56. deletion_notice_date = models.DateTimeField(null=True, blank=True)
  57. last_active_date = models.DateTimeField(null=True, blank=True)
  58. objects = ProfileManager()
  59. def __str__(self):
  60. return "Profile for %s" % self.user.email
  61. def notifications_url(self):
  62. return settings.SITE_ROOT + reverse("hc-notifications")
  63. def reports_unsub_url(self):
  64. signer = TimestampSigner(salt="reports")
  65. signed_username = signer.sign(self.user.username)
  66. path = reverse("hc-unsubscribe-reports", args=[signed_username])
  67. return settings.SITE_ROOT + path
  68. def prepare_token(self, salt):
  69. token = token_urlsafe(24)
  70. self.token = make_password(token, salt)
  71. self.save()
  72. return token
  73. def check_token(self, token, salt):
  74. return salt in self.token and check_password(token, self.token)
  75. def send_instant_login_link(self, inviting_project=None, redirect_url=None):
  76. token = self.prepare_token("login")
  77. path = reverse("hc-check-token", args=[self.user.username, token])
  78. if redirect_url:
  79. path += "?next=%s" % redirect_url
  80. ctx = {
  81. "button_text": "Sign In",
  82. "button_url": settings.SITE_ROOT + path,
  83. "inviting_project": inviting_project,
  84. }
  85. emails.login(self.user.email, ctx)
  86. def send_transfer_request(self, project):
  87. token = self.prepare_token("login")
  88. settings_path = reverse("hc-project-settings", args=[project.code])
  89. path = reverse("hc-check-token", args=[self.user.username, token])
  90. path += "?next=%s" % settings_path
  91. ctx = {
  92. "button_text": "Project Settings",
  93. "button_url": settings.SITE_ROOT + path,
  94. "project": project,
  95. }
  96. emails.transfer_request(self.user.email, ctx)
  97. def send_sms_limit_notice(self, transport):
  98. ctx = {"transport": transport, "limit": self.sms_limit}
  99. if self.sms_limit != 500 and settings.USE_PAYMENTS:
  100. ctx["url"] = settings.SITE_ROOT + reverse("hc-pricing")
  101. emails.sms_limit(self.user.email, ctx)
  102. def send_call_limit_notice(self):
  103. ctx = {"limit": self.call_limit}
  104. if self.call_limit != 500 and settings.USE_PAYMENTS:
  105. ctx["url"] = settings.SITE_ROOT + reverse("hc-pricing")
  106. emails.call_limit(self.user.email, ctx)
  107. def projects(self):
  108. """ Return a queryset of all projects we have access to. """
  109. is_owner = Q(owner=self.user)
  110. is_member = Q(member__user=self.user)
  111. q = Project.objects.filter(is_owner | is_member)
  112. return q.distinct().order_by("name")
  113. def annotated_projects(self):
  114. """ Return all projects, annotated with 'n_down'. """
  115. # Subquery for getting project ids
  116. project_ids = self.projects().values("id")
  117. # Main query with the n_down annotation.
  118. # Must use the subquery, otherwise ORM gets confused by
  119. # joins and group by's
  120. q = Project.objects.filter(id__in=project_ids)
  121. n_down = Count("check", filter=Q(check__status="down"))
  122. q = q.annotate(n_down=n_down)
  123. return q.order_by("name")
  124. def checks_from_all_projects(self):
  125. """ Return a queryset of checks from projects we have access to. """
  126. project_ids = self.projects().values("id")
  127. from hc.api.models import Check
  128. return Check.objects.filter(project_id__in=project_ids)
  129. def send_report(self, nag=False):
  130. checks = self.checks_from_all_projects()
  131. # Has there been a ping in last 6 months?
  132. result = checks.aggregate(models.Max("last_ping"))
  133. last_ping = result["last_ping__max"]
  134. six_months_ago = timezone.now() - timedelta(days=180)
  135. if last_ping is None or last_ping < six_months_ago:
  136. return False
  137. # Is there at least one check that is down?
  138. num_down = checks.filter(status="down").count()
  139. if nag and num_down == 0:
  140. return False
  141. # Sort checks by project. Need this because will group by project in
  142. # template.
  143. checks = checks.select_related("project")
  144. checks = checks.order_by("project_id")
  145. # list() executes the query, to avoid DB access while
  146. # rendering the template
  147. checks = list(checks)
  148. unsub_url = self.reports_unsub_url()
  149. headers = {
  150. "List-Unsubscribe": "<%s>" % unsub_url,
  151. "X-Bounce-Url": unsub_url,
  152. "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
  153. }
  154. ctx = {
  155. "checks": checks,
  156. "sort": self.sort,
  157. "now": timezone.now(),
  158. "unsub_link": unsub_url,
  159. "notifications_url": self.notifications_url(),
  160. "nag": nag,
  161. "nag_period": self.nag_period.total_seconds(),
  162. "num_down": num_down,
  163. "month_boundaries": month_boundaries(),
  164. }
  165. emails.report(self.user.email, ctx, headers)
  166. return True
  167. def sms_sent_this_month(self):
  168. # IF last_sms_date was never set, we have not sent any messages yet.
  169. if not self.last_sms_date:
  170. return 0
  171. # If last sent date is not from this month, we've sent 0 this month.
  172. if month(timezone.now()) > month(self.last_sms_date):
  173. return 0
  174. return self.sms_sent
  175. def authorize_sms(self):
  176. """ If monthly limit not exceeded, increase counter and return True """
  177. sent_this_month = self.sms_sent_this_month()
  178. if sent_this_month >= self.sms_limit:
  179. return False
  180. self.sms_sent = sent_this_month + 1
  181. self.last_sms_date = timezone.now()
  182. self.save()
  183. return True
  184. def calls_sent_this_month(self):
  185. # IF last_call_date was never set, we have not made any phone calls yet.
  186. if not self.last_call_date:
  187. return 0
  188. # If last sent date is not from this month, we've made 0 calls this month.
  189. if month(timezone.now()) > month(self.last_call_date):
  190. return 0
  191. return self.calls_sent
  192. def authorize_call(self):
  193. """ If monthly limit not exceeded, increase counter and return True """
  194. sent_this_month = self.calls_sent_this_month()
  195. if sent_this_month >= self.call_limit:
  196. return False
  197. self.calls_sent = sent_this_month + 1
  198. self.last_call_date = timezone.now()
  199. self.save()
  200. return True
  201. def num_checks_used(self):
  202. from hc.api.models import Check
  203. return Check.objects.filter(project__owner_id=self.user_id).count()
  204. def num_checks_available(self):
  205. return self.check_limit - self.num_checks_used()
  206. def can_accept(self, project):
  207. return project.num_checks() <= self.num_checks_available()
  208. class Project(models.Model):
  209. code = models.UUIDField(default=uuid.uuid4, unique=True)
  210. name = models.CharField(max_length=200, blank=True)
  211. owner = models.ForeignKey(User, models.CASCADE)
  212. api_key = models.CharField(max_length=128, blank=True, db_index=True)
  213. api_key_readonly = models.CharField(max_length=128, blank=True, db_index=True)
  214. badge_key = models.CharField(max_length=150, unique=True)
  215. def __str__(self):
  216. return self.name or self.owner.email
  217. @property
  218. def owner_profile(self):
  219. return Profile.objects.for_user(self.owner)
  220. def num_checks(self):
  221. return self.check_set.count()
  222. def num_checks_available(self):
  223. return self.owner_profile.num_checks_available()
  224. def set_api_keys(self):
  225. self.api_key = token_urlsafe(nbytes=24)
  226. self.api_key_readonly = token_urlsafe(nbytes=24)
  227. self.save()
  228. def team(self):
  229. return User.objects.filter(memberships__project=self).order_by("email")
  230. def invite_suggestions(self):
  231. q = User.objects.filter(memberships__project__owner_id=self.owner_id)
  232. q = q.exclude(memberships__project=self)
  233. return q.distinct().order_by("email")
  234. def can_invite_new_users(self):
  235. q = User.objects.filter(memberships__project__owner_id=self.owner_id)
  236. used = q.distinct().count()
  237. return used < self.owner_profile.team_limit
  238. def invite(self, user, rw):
  239. if Member.objects.filter(user=user, project=self).exists():
  240. return False
  241. if self.owner_id == user.id:
  242. return False
  243. Member.objects.create(user=user, project=self, rw=rw)
  244. checks_url = reverse("hc-checks", args=[self.code])
  245. user.profile.send_instant_login_link(self, redirect_url=checks_url)
  246. return True
  247. def set_next_nag_date(self):
  248. """ Set next_nag_date on profiles of all members of this project. """
  249. is_owner = Q(user=self.owner)
  250. is_member = Q(user__memberships__project=self)
  251. q = Profile.objects.filter(is_owner | is_member)
  252. q = q.exclude(nag_period=NO_NAG)
  253. # Exclude profiles with next_nag_date already set
  254. q = q.filter(next_nag_date__isnull=True)
  255. q.update(next_nag_date=timezone.now() + models.F("nag_period"))
  256. def overall_status(self):
  257. status = "up"
  258. for check in self.check_set.all():
  259. check_status = check.get_status()
  260. if status == "up" and check_status == "grace":
  261. status = "grace"
  262. if check_status == "down":
  263. status = "down"
  264. break
  265. return status
  266. def have_channel_issues(self):
  267. errors = list(self.channel_set.values_list("last_error", flat=True))
  268. # It's a problem if a project has no integrations at all
  269. if len(errors) == 0:
  270. return True
  271. # It's a problem if any integration has a logged error
  272. return True if max(errors) else False
  273. def transfer_request(self):
  274. return self.member_set.filter(transfer_request_date__isnull=False).first()
  275. def dashboard_url(self):
  276. if not self.api_key_readonly:
  277. return None
  278. frag = urlencode({self.api_key_readonly: str(self)}, quote_via=quote)
  279. return reverse("hc-dashboard") + "#" + frag
  280. class Member(models.Model):
  281. user = models.ForeignKey(User, models.CASCADE, related_name="memberships")
  282. project = models.ForeignKey(Project, models.CASCADE)
  283. transfer_request_date = models.DateTimeField(null=True, blank=True)
  284. rw = models.BooleanField(default=True)
  285. class Meta:
  286. constraints = [
  287. models.UniqueConstraint(
  288. fields=["user", "project"], name="accounts_member_no_duplicates"
  289. )
  290. ]
  291. def can_accept(self):
  292. return self.user.profile.can_accept(self.project)
  293. class Credential(models.Model):
  294. code = models.UUIDField(default=uuid.uuid4, unique=True)
  295. name = models.CharField(max_length=100)
  296. user = models.ForeignKey(User, models.CASCADE, related_name="credentials")
  297. created = models.DateTimeField(auto_now_add=True)
  298. data = models.BinaryField()
  299. def unpack(self):
  300. unpacked, remaining_data = AttestedCredentialData.unpack_from(self.data)
  301. return unpacked