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.

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