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.

791 lines
25 KiB

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