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.

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