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.

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