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.

815 lines
25 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. return doc["team_name"]
  433. @property
  434. def slack_channel(self):
  435. assert self.kind == "slack"
  436. if not self.value.startswith("{"):
  437. return None
  438. doc = json.loads(self.value)
  439. return doc["incoming_webhook"]["channel"]
  440. @property
  441. def slack_webhook_url(self):
  442. assert self.kind in ("slack", "mattermost")
  443. if not self.value.startswith("{"):
  444. return self.value
  445. doc = json.loads(self.value)
  446. return doc["incoming_webhook"]["url"]
  447. @property
  448. def discord_webhook_url(self):
  449. assert self.kind == "discord"
  450. doc = json.loads(self.value)
  451. return doc["webhook"]["url"]
  452. @property
  453. def discord_webhook_id(self):
  454. assert self.kind == "discord"
  455. doc = json.loads(self.value)
  456. return doc["webhook"]["id"]
  457. @property
  458. def telegram_id(self):
  459. assert self.kind == "telegram"
  460. doc = json.loads(self.value)
  461. return doc.get("id")
  462. @property
  463. def telegram_type(self):
  464. assert self.kind == "telegram"
  465. doc = json.loads(self.value)
  466. return doc.get("type")
  467. @property
  468. def telegram_name(self):
  469. assert self.kind == "telegram"
  470. doc = json.loads(self.value)
  471. return doc.get("name")
  472. @property
  473. def pd_service_key(self):
  474. assert self.kind == "pd"
  475. if not self.value.startswith("{"):
  476. return self.value
  477. doc = json.loads(self.value)
  478. return doc["service_key"]
  479. @property
  480. def pd_account(self):
  481. assert self.kind == "pd"
  482. if self.value.startswith("{"):
  483. doc = json.loads(self.value)
  484. return doc["account"]
  485. def latest_notification(self):
  486. return Notification.objects.filter(channel=self).latest()
  487. @property
  488. def sms_number(self):
  489. assert self.kind in ("sms", "whatsapp")
  490. if self.value.startswith("{"):
  491. doc = json.loads(self.value)
  492. return doc["value"]
  493. return self.value
  494. @property
  495. def trello_token(self):
  496. assert self.kind == "trello"
  497. if self.value.startswith("{"):
  498. doc = json.loads(self.value)
  499. return doc["token"]
  500. @property
  501. def trello_board_list(self):
  502. assert self.kind == "trello"
  503. if self.value.startswith("{"):
  504. doc = json.loads(self.value)
  505. return doc["board_name"], doc["list_name"]
  506. @property
  507. def trello_list_id(self):
  508. assert self.kind == "trello"
  509. if self.value.startswith("{"):
  510. doc = json.loads(self.value)
  511. return doc["list_id"]
  512. @property
  513. def email_value(self):
  514. assert self.kind == "email"
  515. if not self.value.startswith("{"):
  516. return self.value
  517. return self.json["value"]
  518. @property
  519. def email_notify_up(self):
  520. assert self.kind == "email"
  521. if not self.value.startswith("{"):
  522. return True
  523. doc = json.loads(self.value)
  524. return doc.get("up")
  525. @property
  526. def email_notify_down(self):
  527. assert self.kind == "email"
  528. if not self.value.startswith("{"):
  529. return True
  530. doc = json.loads(self.value)
  531. return doc.get("down")
  532. @property
  533. def whatsapp_notify_up(self):
  534. assert self.kind == "whatsapp"
  535. doc = json.loads(self.value)
  536. return doc["up"]
  537. @property
  538. def whatsapp_notify_down(self):
  539. assert self.kind == "whatsapp"
  540. doc = json.loads(self.value)
  541. return doc["down"]
  542. @property
  543. def opsgenie_key(self):
  544. assert self.kind == "opsgenie"
  545. if not self.value.startswith("{"):
  546. return self.value
  547. doc = json.loads(self.value)
  548. return doc["key"]
  549. @property
  550. def opsgenie_region(self):
  551. assert self.kind == "opsgenie"
  552. if not self.value.startswith("{"):
  553. return "us"
  554. doc = json.loads(self.value)
  555. return doc["region"]
  556. @property
  557. def zulip_bot_email(self):
  558. assert self.kind == "zulip"
  559. doc = json.loads(self.value)
  560. return doc["bot_email"]
  561. @property
  562. def zulip_api_key(self):
  563. assert self.kind == "zulip"
  564. doc = json.loads(self.value)
  565. return doc["api_key"]
  566. @property
  567. def zulip_type(self):
  568. assert self.kind == "zulip"
  569. doc = json.loads(self.value)
  570. return doc["mtype"]
  571. @property
  572. def zulip_to(self):
  573. assert self.kind == "zulip"
  574. doc = json.loads(self.value)
  575. return doc["to"]
  576. class Notification(models.Model):
  577. class Meta:
  578. get_latest_by = "created"
  579. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  580. owner = models.ForeignKey(Check, models.CASCADE)
  581. check_status = models.CharField(max_length=6)
  582. channel = models.ForeignKey(Channel, models.CASCADE)
  583. created = models.DateTimeField(auto_now_add=True)
  584. error = models.CharField(max_length=200, blank=True)
  585. def bounce_url(self):
  586. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])
  587. class Flip(models.Model):
  588. owner = models.ForeignKey(Check, models.CASCADE)
  589. created = models.DateTimeField()
  590. processed = models.DateTimeField(null=True, blank=True)
  591. old_status = models.CharField(max_length=8, choices=STATUSES)
  592. new_status = models.CharField(max_length=8, choices=STATUSES)
  593. class Meta:
  594. indexes = [
  595. # For quickly looking up unprocessed flips.
  596. # Used in the sendalerts management command.
  597. models.Index(
  598. fields=["processed"],
  599. name="api_flip_not_processed",
  600. condition=models.Q(processed=None),
  601. )
  602. ]
  603. def send_alerts(self):
  604. if self.new_status == "up" and self.old_status in ("new", "paused"):
  605. # Don't send alerts on new->up and paused->up transitions
  606. return []
  607. if self.new_status not in ("up", "down"):
  608. raise NotImplementedError("Unexpected status: %s" % self.status)
  609. errors = []
  610. for channel in self.owner.channel_set.all():
  611. error = channel.notify(self.owner)
  612. if error not in ("", "no-op"):
  613. errors.append((channel, error))
  614. return errors
  615. class TokenBucket(models.Model):
  616. value = models.CharField(max_length=80, unique=True)
  617. tokens = models.FloatField(default=1.0)
  618. updated = models.DateTimeField(default=timezone.now)
  619. @staticmethod
  620. def authorize(value, capacity, refill_time_secs):
  621. now = timezone.now()
  622. obj, created = TokenBucket.objects.get_or_create(value=value)
  623. if not created:
  624. # Top up the bucket:
  625. delta_secs = (now - obj.updated).total_seconds()
  626. obj.tokens = min(1.0, obj.tokens + delta_secs / refill_time_secs)
  627. obj.tokens -= 1.0 / capacity
  628. if obj.tokens < 0:
  629. # Not enough tokens
  630. return False
  631. # Race condition: two concurrent authorize calls can overwrite each
  632. # other's changes. It's OK to be a little inexact here for the sake
  633. # of simplicity.
  634. obj.updated = now
  635. obj.save()
  636. return True
  637. @staticmethod
  638. def authorize_login_email(email):
  639. # remove dots and alias:
  640. mailbox, domain = email.split("@")
  641. mailbox = mailbox.replace(".", "")
  642. mailbox = mailbox.split("+")[0]
  643. email = mailbox + "@" + domain
  644. salted_encoded = (email + settings.SECRET_KEY).encode()
  645. value = "em-%s" % hashlib.sha1(salted_encoded).hexdigest()
  646. # 20 login attempts for a single email per hour:
  647. return TokenBucket.authorize(value, 20, 3600)
  648. @staticmethod
  649. def authorize_invite(user):
  650. value = "invite-%d" % user.id
  651. # 20 invites per day
  652. return TokenBucket.authorize(value, 20, 3600 * 24)
  653. @staticmethod
  654. def authorize_login_password(email):
  655. salted_encoded = (email + settings.SECRET_KEY).encode()
  656. value = "pw-%s" % hashlib.sha1(salted_encoded).hexdigest()
  657. # 20 password attempts per day
  658. return TokenBucket.authorize(value, 20, 3600 * 24)