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.

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