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.

826 lines
26 KiB

10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
6 years ago
7 years ago
6 years ago
  1. # coding: utf-8
  2. import hashlib
  3. import json
  4. import uuid
  5. from datetime import datetime, timedelta as td
  6. from croniter import croniter
  7. from django.conf import settings
  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.accounts.models import Project
  13. from hc.api import transports
  14. from hc.lib import emails
  15. from hc.lib.date import month_boundaries
  16. import pytz
  17. STATUSES = (("up", "Up"), ("down", "Down"), ("new", "New"), ("paused", "Paused"))
  18. DEFAULT_TIMEOUT = td(days=1)
  19. DEFAULT_GRACE = td(hours=1)
  20. NEVER = datetime(3000, 1, 1, tzinfo=pytz.UTC)
  21. CHECK_KINDS = (("simple", "Simple"), ("cron", "Cron"))
  22. # max time between start and ping where we will consider both events related:
  23. MAX_DELTA = td(hours=24)
  24. CHANNEL_KINDS = (
  25. ("email", "Email"),
  26. ("webhook", "Webhook"),
  27. ("hipchat", "HipChat"),
  28. ("slack", "Slack"),
  29. ("pd", "PagerDuty"),
  30. ("pagertree", "PagerTree"),
  31. ("pagerteam", "Pager Team"),
  32. ("po", "Pushover"),
  33. ("pushbullet", "Pushbullet"),
  34. ("opsgenie", "OpsGenie"),
  35. ("victorops", "VictorOps"),
  36. ("discord", "Discord"),
  37. ("telegram", "Telegram"),
  38. ("sms", "SMS"),
  39. ("zendesk", "Zendesk"),
  40. ("trello", "Trello"),
  41. ("matrix", "Matrix"),
  42. ("whatsapp", "WhatsApp"),
  43. ("apprise", "Apprise"),
  44. ("mattermost", "Mattermost"),
  45. ("msteams", "Microsoft Teams"),
  46. ("shell", "Shell Command"),
  47. ("zulip", "Zulip"),
  48. )
  49. PO_PRIORITIES = {-2: "lowest", -1: "low", 0: "normal", 1: "high", 2: "emergency"}
  50. def isostring(dt):
  51. """Convert the datetime to ISO 8601 format with no microseconds. """
  52. if dt:
  53. return dt.replace(microsecond=0).isoformat()
  54. class Check(models.Model):
  55. name = models.CharField(max_length=100, blank=True)
  56. tags = models.CharField(max_length=500, blank=True)
  57. code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  58. desc = models.TextField(blank=True)
  59. project = models.ForeignKey(Project, models.CASCADE)
  60. created = models.DateTimeField(auto_now_add=True)
  61. kind = models.CharField(max_length=10, default="simple", choices=CHECK_KINDS)
  62. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  63. grace = models.DurationField(default=DEFAULT_GRACE)
  64. schedule = models.CharField(max_length=100, default="* * * * *")
  65. tz = models.CharField(max_length=36, default="UTC")
  66. subject = models.CharField(max_length=100, blank=True)
  67. methods = models.CharField(max_length=30, blank=True)
  68. n_pings = models.IntegerField(default=0)
  69. last_ping = models.DateTimeField(null=True, blank=True)
  70. last_start = models.DateTimeField(null=True, blank=True)
  71. last_duration = models.DurationField(null=True, blank=True)
  72. last_ping_was_fail = models.NullBooleanField(default=False)
  73. has_confirmation_link = models.BooleanField(default=False)
  74. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  75. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  76. class Meta:
  77. indexes = [
  78. # Index for the alert_after field. Excludes rows with status=down.
  79. # Used in the sendalerts management command.
  80. models.Index(
  81. fields=["alert_after"],
  82. name="api_check_aa_not_down",
  83. condition=~models.Q(status="down"),
  84. )
  85. ]
  86. def __str__(self):
  87. return "%s (%d)" % (self.name or self.code, self.id)
  88. def name_then_code(self):
  89. if self.name:
  90. return self.name
  91. return str(self.code)
  92. def url(self):
  93. return settings.PING_ENDPOINT + str(self.code)
  94. def details_url(self):
  95. return settings.SITE_ROOT + reverse("hc-details", args=[self.code])
  96. def email(self):
  97. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  98. def clamped_last_duration(self):
  99. if self.last_duration and self.last_duration < MAX_DELTA:
  100. return self.last_duration
  101. def get_grace_start(self):
  102. """ Return the datetime when the grace period starts.
  103. If the check is currently new, paused or down, return None.
  104. """
  105. # NEVER is a constant sentinel value (year 3000).
  106. # Using None instead would make the logic clunky.
  107. result = NEVER
  108. if self.kind == "simple" and self.status == "up":
  109. result = self.last_ping + self.timeout
  110. elif self.kind == "cron" and self.status == "up":
  111. # The complex case, next ping is expected based on cron schedule.
  112. # Don't convert to naive datetimes (and so avoid ambiguities around
  113. # DST transitions). Croniter will handle the timezone-aware datetimes.
  114. zone = pytz.timezone(self.tz)
  115. last_local = timezone.localtime(self.last_ping, zone)
  116. it = croniter(self.schedule, last_local)
  117. result = it.next(datetime)
  118. if self.last_start and self.status != "down":
  119. result = min(result, self.last_start)
  120. if result != NEVER:
  121. return result
  122. def going_down_after(self):
  123. """ Return the datetime when the check goes down.
  124. If the check is new or paused, and not currently running, return None.
  125. If the check is already down, also return None.
  126. """
  127. grace_start = self.get_grace_start()
  128. if grace_start is not None:
  129. return grace_start + self.grace
  130. def get_status(self, now=None, with_started=True):
  131. """ Return current status for display. """
  132. if now is None:
  133. now = timezone.now()
  134. if self.last_start:
  135. if now >= self.last_start + self.grace:
  136. return "down"
  137. elif with_started:
  138. return "started"
  139. if self.status in ("new", "paused", "down"):
  140. return self.status
  141. grace_start = self.get_grace_start()
  142. grace_end = grace_start + self.grace
  143. if now >= grace_end:
  144. return "down"
  145. if now >= grace_start:
  146. return "grace"
  147. return "up"
  148. def assign_all_channels(self):
  149. channels = Channel.objects.filter(project=self.project)
  150. self.channel_set.set(channels)
  151. def tags_list(self):
  152. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  153. def matches_tag_set(self, tag_set):
  154. return tag_set.issubset(self.tags_list())
  155. def channels_str(self):
  156. """ Return a comma-separated string of assigned channel codes. """
  157. codes = self.channel_set.order_by("code").values_list("code", flat=True)
  158. return ",".join(map(str, codes))
  159. @property
  160. def unique_key(self):
  161. code_half = self.code.hex[:16]
  162. return hashlib.sha1(code_half.encode()).hexdigest()
  163. def to_dict(self, readonly=False):
  164. result = {
  165. "name": self.name,
  166. "tags": self.tags,
  167. "desc": self.desc,
  168. "grace": int(self.grace.total_seconds()),
  169. "n_pings": self.n_pings,
  170. "status": self.get_status(),
  171. "last_ping": isostring(self.last_ping),
  172. "next_ping": isostring(self.get_grace_start()),
  173. }
  174. if self.last_duration:
  175. result["last_duration"] = int(self.last_duration.total_seconds())
  176. if readonly:
  177. result["unique_key"] = self.unique_key
  178. else:
  179. update_rel_url = reverse("hc-api-single", args=[self.code])
  180. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  181. result["ping_url"] = self.url()
  182. result["update_url"] = settings.SITE_ROOT + update_rel_url
  183. result["pause_url"] = settings.SITE_ROOT + pause_rel_url
  184. result["channels"] = self.channels_str()
  185. if self.kind == "simple":
  186. result["timeout"] = int(self.timeout.total_seconds())
  187. elif self.kind == "cron":
  188. result["schedule"] = self.schedule
  189. result["tz"] = self.tz
  190. return result
  191. def ping(self, remote_addr, scheme, method, ua, body, action):
  192. now = timezone.now()
  193. if action == "start":
  194. self.last_start = now
  195. # Don't update "last_ping" field.
  196. elif action == "ign":
  197. pass
  198. else:
  199. self.last_ping = now
  200. if self.last_start:
  201. self.last_duration = self.last_ping - self.last_start
  202. self.last_start = None
  203. else:
  204. self.last_duration = None
  205. new_status = "down" if action == "fail" else "up"
  206. if self.status != new_status:
  207. flip = Flip(owner=self)
  208. flip.created = self.last_ping
  209. flip.old_status = self.status
  210. flip.new_status = new_status
  211. flip.save()
  212. self.status = new_status
  213. self.alert_after = self.going_down_after()
  214. self.n_pings = models.F("n_pings") + 1
  215. self.has_confirmation_link = "confirm" in str(body).lower()
  216. self.save()
  217. self.refresh_from_db()
  218. ping = Ping(owner=self)
  219. ping.n = self.n_pings
  220. ping.created = now
  221. if action in ("start", "fail", "ign"):
  222. ping.kind = action
  223. ping.remote_addr = remote_addr
  224. ping.scheme = scheme
  225. ping.method = method
  226. # If User-Agent is longer than 200 characters, truncate it:
  227. ping.ua = ua[:200]
  228. ping.body = body[: settings.PING_BODY_LIMIT]
  229. ping.save()
  230. def downtimes(self, months=3):
  231. """ Calculate the number of downtimes and downtime minutes per month.
  232. Returns a list of (datetime, downtime_in_secs, number_of_outages) tuples.
  233. """
  234. def monthkey(dt):
  235. return dt.year, dt.month
  236. # Datetimes of the first days of months we're interested in. Ascending order.
  237. boundaries = month_boundaries(months=months)
  238. # Will accumulate totals here.
  239. # (year, month) -> [datetime, total_downtime, number_of_outages]
  240. totals = {monthkey(b): [b, td(), 0] for b in boundaries}
  241. # A list of flips and month boundaries
  242. events = [(b, "---") for b in boundaries]
  243. q = self.flip_set.filter(created__gt=min(boundaries))
  244. for pair in q.values_list("created", "old_status"):
  245. events.append(pair)
  246. # Iterate through flips and month boundaries in reverse order,
  247. # and for each "down" event increase the counters in `totals`.
  248. dt, status = timezone.now(), self.status
  249. for prev_dt, prev_status in sorted(events, reverse=True):
  250. if status == "down":
  251. delta = dt - prev_dt
  252. totals[monthkey(prev_dt)][1] += delta
  253. totals[monthkey(prev_dt)][2] += 1
  254. dt = prev_dt
  255. if prev_status != "---":
  256. status = prev_status
  257. return sorted(totals.values())
  258. class Ping(models.Model):
  259. id = models.BigAutoField(primary_key=True)
  260. n = models.IntegerField(null=True)
  261. owner = models.ForeignKey(Check, models.CASCADE)
  262. created = models.DateTimeField(default=timezone.now)
  263. kind = models.CharField(max_length=6, blank=True, null=True)
  264. scheme = models.CharField(max_length=10, default="http")
  265. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  266. method = models.CharField(max_length=10, blank=True)
  267. ua = models.CharField(max_length=200, blank=True)
  268. body = models.TextField(blank=True, null=True)
  269. class Channel(models.Model):
  270. name = models.CharField(max_length=100, blank=True)
  271. code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  272. project = models.ForeignKey(Project, models.CASCADE)
  273. created = models.DateTimeField(auto_now_add=True)
  274. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  275. value = models.TextField(blank=True)
  276. email_verified = models.BooleanField(default=False)
  277. last_error = models.CharField(max_length=200, blank=True)
  278. checks = models.ManyToManyField(Check)
  279. def __str__(self):
  280. if self.name:
  281. return self.name
  282. if self.kind == "email":
  283. return "Email to %s" % self.email_value
  284. elif self.kind == "sms":
  285. return "SMS to %s" % self.sms_number
  286. elif self.kind == "slack":
  287. return "Slack %s" % self.slack_channel
  288. elif self.kind == "telegram":
  289. return "Telegram %s" % self.telegram_name
  290. elif self.kind == "zulip":
  291. if self.zulip_type == "stream":
  292. return "Zulip stream %s" % self.zulip_to
  293. if self.zulip_type == "private":
  294. return "Zulip user %s" % self.zulip_to
  295. return self.get_kind_display()
  296. def to_dict(self):
  297. return {"id": str(self.code), "name": self.name, "kind": self.kind}
  298. def assign_all_checks(self):
  299. checks = Check.objects.filter(project=self.project)
  300. self.checks.add(*checks)
  301. def make_token(self):
  302. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  303. seed = seed.encode()
  304. return hashlib.sha1(seed).hexdigest()
  305. def send_verify_link(self):
  306. args = [self.code, self.make_token()]
  307. verify_link = reverse("hc-verify-email", args=args)
  308. verify_link = settings.SITE_ROOT + verify_link
  309. emails.verify_email(self.email_value, {"verify_link": verify_link})
  310. def get_unsub_link(self):
  311. signer = TimestampSigner(salt="alerts")
  312. signed_token = signer.sign(self.make_token())
  313. args = [self.code, signed_token]
  314. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  315. return settings.SITE_ROOT + verify_link
  316. @property
  317. def transport(self):
  318. if self.kind == "email":
  319. return transports.Email(self)
  320. elif self.kind == "webhook":
  321. return transports.Webhook(self)
  322. elif self.kind in ("slack", "mattermost"):
  323. return transports.Slack(self)
  324. elif self.kind == "hipchat":
  325. return transports.HipChat(self)
  326. elif self.kind == "pd":
  327. return transports.PagerDuty(self)
  328. elif self.kind == "pagertree":
  329. return transports.PagerTree(self)
  330. elif self.kind == "pagerteam":
  331. return transports.PagerTeam(self)
  332. elif self.kind == "victorops":
  333. return transports.VictorOps(self)
  334. elif self.kind == "pushbullet":
  335. return transports.Pushbullet(self)
  336. elif self.kind == "po":
  337. return transports.Pushover(self)
  338. elif self.kind == "opsgenie":
  339. return transports.OpsGenie(self)
  340. elif self.kind == "discord":
  341. return transports.Discord(self)
  342. elif self.kind == "telegram":
  343. return transports.Telegram(self)
  344. elif self.kind == "sms":
  345. return transports.Sms(self)
  346. elif self.kind == "trello":
  347. return transports.Trello(self)
  348. elif self.kind == "matrix":
  349. return transports.Matrix(self)
  350. elif self.kind == "whatsapp":
  351. return transports.WhatsApp(self)
  352. elif self.kind == "apprise":
  353. return transports.Apprise(self)
  354. elif self.kind == "msteams":
  355. return transports.MsTeams(self)
  356. elif self.kind == "shell":
  357. return transports.Shell(self)
  358. elif self.kind == "zulip":
  359. return transports.Zulip(self)
  360. else:
  361. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  362. def notify(self, check):
  363. if self.transport.is_noop(check):
  364. return "no-op"
  365. n = Notification(owner=check, channel=self)
  366. n.check_status = check.status
  367. n.error = "Sending"
  368. n.save()
  369. if self.kind == "email":
  370. error = self.transport.notify(check, n.bounce_url()) or ""
  371. else:
  372. error = self.transport.notify(check) or ""
  373. n.error = error
  374. n.save()
  375. self.last_error = error
  376. self.save()
  377. return error
  378. def icon_path(self):
  379. return "img/integrations/%s.png" % self.kind
  380. @property
  381. def json(self):
  382. return json.loads(self.value)
  383. @property
  384. def po_priority(self):
  385. assert self.kind == "po"
  386. parts = self.value.split("|")
  387. prio = int(parts[1])
  388. return PO_PRIORITIES[prio]
  389. def webhook_spec(self, status):
  390. assert self.kind == "webhook"
  391. doc = json.loads(self.value)
  392. if status == "down" and "method_down" in doc:
  393. return {
  394. "method": doc["method_down"],
  395. "url": doc["url_down"],
  396. "body": doc["body_down"],
  397. "headers": doc["headers_down"],
  398. }
  399. elif status == "up" and "method_up" in doc:
  400. return {
  401. "method": doc["method_up"],
  402. "url": doc["url_up"],
  403. "body": doc["body_up"],
  404. "headers": doc["headers_up"],
  405. }
  406. @property
  407. def down_webhook_spec(self):
  408. return self.webhook_spec("down")
  409. @property
  410. def up_webhook_spec(self):
  411. return self.webhook_spec("up")
  412. @property
  413. def url_down(self):
  414. return self.down_webhook_spec["url"]
  415. @property
  416. def url_up(self):
  417. return self.up_webhook_spec["url"]
  418. @property
  419. def cmd_down(self):
  420. assert self.kind == "shell"
  421. return self.json["cmd_down"]
  422. @property
  423. def cmd_up(self):
  424. assert self.kind == "shell"
  425. return self.json["cmd_up"]
  426. @property
  427. def slack_team(self):
  428. assert self.kind == "slack"
  429. if not self.value.startswith("{"):
  430. return None
  431. doc = json.loads(self.value)
  432. if "team_name" in doc:
  433. return doc["team_name"]
  434. if "team" in doc:
  435. return doc["team"]["name"]
  436. @property
  437. def slack_channel(self):
  438. assert self.kind == "slack"
  439. if not self.value.startswith("{"):
  440. return None
  441. doc = json.loads(self.value)
  442. return doc["incoming_webhook"]["channel"]
  443. @property
  444. def slack_webhook_url(self):
  445. assert self.kind in ("slack", "mattermost")
  446. if not self.value.startswith("{"):
  447. return self.value
  448. doc = json.loads(self.value)
  449. return doc["incoming_webhook"]["url"]
  450. @property
  451. def discord_webhook_url(self):
  452. assert self.kind == "discord"
  453. doc = json.loads(self.value)
  454. return doc["webhook"]["url"]
  455. @property
  456. def discord_webhook_id(self):
  457. assert self.kind == "discord"
  458. doc = json.loads(self.value)
  459. return doc["webhook"]["id"]
  460. @property
  461. def telegram_id(self):
  462. assert self.kind == "telegram"
  463. doc = json.loads(self.value)
  464. return doc.get("id")
  465. @property
  466. def telegram_type(self):
  467. assert self.kind == "telegram"
  468. doc = json.loads(self.value)
  469. return doc.get("type")
  470. @property
  471. def telegram_name(self):
  472. assert self.kind == "telegram"
  473. doc = json.loads(self.value)
  474. return doc.get("name")
  475. @property
  476. def pd_service_key(self):
  477. assert self.kind == "pd"
  478. if not self.value.startswith("{"):
  479. return self.value
  480. doc = json.loads(self.value)
  481. return doc["service_key"]
  482. @property
  483. def pd_account(self):
  484. assert self.kind == "pd"
  485. if self.value.startswith("{"):
  486. doc = json.loads(self.value)
  487. return doc["account"]
  488. def latest_notification(self):
  489. return Notification.objects.filter(channel=self).latest()
  490. @property
  491. def sms_number(self):
  492. assert self.kind in ("sms", "whatsapp")
  493. if self.value.startswith("{"):
  494. doc = json.loads(self.value)
  495. return doc["value"]
  496. return self.value
  497. @property
  498. def trello_token(self):
  499. assert self.kind == "trello"
  500. if self.value.startswith("{"):
  501. doc = json.loads(self.value)
  502. return doc["token"]
  503. @property
  504. def trello_board_list(self):
  505. assert self.kind == "trello"
  506. if self.value.startswith("{"):
  507. doc = json.loads(self.value)
  508. return doc["board_name"], doc["list_name"]
  509. @property
  510. def trello_list_id(self):
  511. assert self.kind == "trello"
  512. if self.value.startswith("{"):
  513. doc = json.loads(self.value)
  514. return doc["list_id"]
  515. @property
  516. def email_value(self):
  517. assert self.kind == "email"
  518. if not self.value.startswith("{"):
  519. return self.value
  520. return self.json["value"]
  521. @property
  522. def email_notify_up(self):
  523. assert self.kind == "email"
  524. if not self.value.startswith("{"):
  525. return True
  526. doc = json.loads(self.value)
  527. return doc.get("up")
  528. @property
  529. def email_notify_down(self):
  530. assert self.kind == "email"
  531. if not self.value.startswith("{"):
  532. return True
  533. doc = json.loads(self.value)
  534. return doc.get("down")
  535. @property
  536. def whatsapp_notify_up(self):
  537. assert self.kind == "whatsapp"
  538. doc = json.loads(self.value)
  539. return doc["up"]
  540. @property
  541. def whatsapp_notify_down(self):
  542. assert self.kind == "whatsapp"
  543. doc = json.loads(self.value)
  544. return doc["down"]
  545. @property
  546. def opsgenie_key(self):
  547. assert self.kind == "opsgenie"
  548. if not self.value.startswith("{"):
  549. return self.value
  550. doc = json.loads(self.value)
  551. return doc["key"]
  552. @property
  553. def opsgenie_region(self):
  554. assert self.kind == "opsgenie"
  555. if not self.value.startswith("{"):
  556. return "us"
  557. doc = json.loads(self.value)
  558. return doc["region"]
  559. @property
  560. def zulip_bot_email(self):
  561. assert self.kind == "zulip"
  562. doc = json.loads(self.value)
  563. return doc["bot_email"]
  564. @property
  565. def zulip_api_key(self):
  566. assert self.kind == "zulip"
  567. doc = json.loads(self.value)
  568. return doc["api_key"]
  569. @property
  570. def zulip_type(self):
  571. assert self.kind == "zulip"
  572. doc = json.loads(self.value)
  573. return doc["mtype"]
  574. @property
  575. def zulip_to(self):
  576. assert self.kind == "zulip"
  577. doc = json.loads(self.value)
  578. return doc["to"]
  579. class Notification(models.Model):
  580. class Meta:
  581. get_latest_by = "created"
  582. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  583. owner = models.ForeignKey(Check, models.CASCADE)
  584. check_status = models.CharField(max_length=6)
  585. channel = models.ForeignKey(Channel, models.CASCADE)
  586. created = models.DateTimeField(auto_now_add=True)
  587. error = models.CharField(max_length=200, blank=True)
  588. def bounce_url(self):
  589. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])
  590. class Flip(models.Model):
  591. owner = models.ForeignKey(Check, models.CASCADE)
  592. created = models.DateTimeField()
  593. processed = models.DateTimeField(null=True, blank=True)
  594. old_status = models.CharField(max_length=8, choices=STATUSES)
  595. new_status = models.CharField(max_length=8, choices=STATUSES)
  596. class Meta:
  597. indexes = [
  598. # For quickly looking up unprocessed flips.
  599. # Used in the sendalerts management command.
  600. models.Index(
  601. fields=["processed"],
  602. name="api_flip_not_processed",
  603. condition=models.Q(processed=None),
  604. )
  605. ]
  606. def send_alerts(self):
  607. if self.new_status == "up" and self.old_status in ("new", "paused"):
  608. # Don't send alerts on new->up and paused->up transitions
  609. return []
  610. if self.new_status not in ("up", "down"):
  611. raise NotImplementedError("Unexpected status: %s" % self.status)
  612. errors = []
  613. for channel in self.owner.channel_set.all():
  614. error = channel.notify(self.owner)
  615. if error not in ("", "no-op"):
  616. errors.append((channel, error))
  617. return errors
  618. class TokenBucket(models.Model):
  619. value = models.CharField(max_length=80, unique=True)
  620. tokens = models.FloatField(default=1.0)
  621. updated = models.DateTimeField(default=timezone.now)
  622. @staticmethod
  623. def authorize(value, capacity, refill_time_secs):
  624. now = timezone.now()
  625. obj, created = TokenBucket.objects.get_or_create(value=value)
  626. if not created:
  627. # Top up the bucket:
  628. delta_secs = (now - obj.updated).total_seconds()
  629. obj.tokens = min(1.0, obj.tokens + delta_secs / refill_time_secs)
  630. obj.tokens -= 1.0 / capacity
  631. if obj.tokens < 0:
  632. # Not enough tokens
  633. return False
  634. # Race condition: two concurrent authorize calls can overwrite each
  635. # other's changes. It's OK to be a little inexact here for the sake
  636. # of simplicity.
  637. obj.updated = now
  638. obj.save()
  639. return True
  640. @staticmethod
  641. def authorize_login_email(email):
  642. # remove dots and alias:
  643. mailbox, domain = email.split("@")
  644. mailbox = mailbox.replace(".", "")
  645. mailbox = mailbox.split("+")[0]
  646. email = mailbox + "@" + domain
  647. salted_encoded = (email + settings.SECRET_KEY).encode()
  648. value = "em-%s" % hashlib.sha1(salted_encoded).hexdigest()
  649. # 20 login attempts for a single email per hour:
  650. return TokenBucket.authorize(value, 20, 3600)
  651. @staticmethod
  652. def authorize_invite(user):
  653. value = "invite-%d" % user.id
  654. # 20 invites per day
  655. return TokenBucket.authorize(value, 20, 3600 * 24)
  656. @staticmethod
  657. def authorize_login_password(email):
  658. salted_encoded = (email + settings.SECRET_KEY).encode()
  659. value = "pw-%s" % hashlib.sha1(salted_encoded).hexdigest()
  660. # 20 password attempts per day
  661. return TokenBucket.authorize(value, 20, 3600 * 24)
  662. @staticmethod
  663. def authorize_telegram(telegram_id):
  664. value = "tg-%s" % telegram_id
  665. # 10 messages for a single chat per minute:
  666. return TokenBucket.authorize(value, 10, 60)