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.

730 lines
21 KiB

9 years ago
8 years ago
9 years ago
8 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
  1. from collections import Counter
  2. from croniter import croniter
  3. from datetime import datetime, timedelta as td
  4. from itertools import tee
  5. import requests
  6. from django.conf import settings
  7. from django.contrib import messages
  8. from django.contrib.auth.decorators import login_required
  9. from django.db.models import Count
  10. from django.http import Http404, HttpResponseBadRequest, HttpResponseForbidden
  11. from django.shortcuts import get_object_or_404, redirect, render
  12. from django.urls import reverse
  13. from django.utils import timezone
  14. from django.utils.crypto import get_random_string
  15. from django.views.decorators.csrf import csrf_exempt
  16. from django.views.decorators.http import require_POST
  17. from django.utils.six.moves.urllib.parse import urlencode
  18. from hc.api.decorators import uuid_or_400
  19. from hc.api.models import (DEFAULT_GRACE, DEFAULT_TIMEOUT, Channel, Check,
  20. Ping, Notification)
  21. from hc.front.forms import (AddWebhookForm, NameTagsForm,
  22. TimeoutForm, AddUrlForm, AddPdForm, AddEmailForm,
  23. AddOpsGenieForm, CronForm)
  24. from pytz import all_timezones
  25. from pytz.exceptions import UnknownTimeZoneError
  26. # from itertools recipes:
  27. def pairwise(iterable):
  28. "s -> (s0,s1), (s1,s2), (s2, s3), ..."
  29. a, b = tee(iterable)
  30. next(b, None)
  31. return zip(a, b)
  32. @login_required
  33. def my_checks(request):
  34. q = Check.objects.filter(user=request.team.user).order_by("created")
  35. checks = list(q)
  36. counter = Counter()
  37. down_tags, grace_tags = set(), set()
  38. for check in checks:
  39. status = check.get_status()
  40. for tag in check.tags_list():
  41. if tag == "":
  42. continue
  43. counter[tag] += 1
  44. if status == "down":
  45. down_tags.add(tag)
  46. elif check.in_grace_period():
  47. grace_tags.add(tag)
  48. ctx = {
  49. "page": "checks",
  50. "checks": checks,
  51. "now": timezone.now(),
  52. "tags": counter.most_common(),
  53. "down_tags": down_tags,
  54. "grace_tags": grace_tags,
  55. "ping_endpoint": settings.PING_ENDPOINT,
  56. "timezones": all_timezones
  57. }
  58. return render(request, "front/my_checks.html", ctx)
  59. def _welcome_check(request):
  60. check = None
  61. if "welcome_code" in request.session:
  62. code = request.session["welcome_code"]
  63. check = Check.objects.filter(code=code).first()
  64. if check is None:
  65. check = Check()
  66. check.save()
  67. request.session["welcome_code"] = str(check.code)
  68. return check
  69. def index(request):
  70. if request.user.is_authenticated:
  71. return redirect("hc-checks")
  72. check = _welcome_check(request)
  73. ctx = {
  74. "page": "welcome",
  75. "check": check,
  76. "ping_url": check.url(),
  77. "enable_pushbullet": settings.PUSHBULLET_CLIENT_ID is not None,
  78. "enable_pushover": settings.PUSHOVER_API_TOKEN is not None,
  79. "enable_discord": settings.DISCORD_CLIENT_ID is not None,
  80. "registration_open": settings.REGISTRATION_OPEN
  81. }
  82. return render(request, "front/welcome.html", ctx)
  83. def docs(request):
  84. check = _welcome_check(request)
  85. ctx = {
  86. "page": "docs",
  87. "section": "home",
  88. "ping_endpoint": settings.PING_ENDPOINT,
  89. "check": check,
  90. "ping_url": check.url()
  91. }
  92. return render(request, "front/docs.html", ctx)
  93. def docs_api(request):
  94. ctx = {
  95. "page": "docs",
  96. "section": "api",
  97. "SITE_ROOT": settings.SITE_ROOT,
  98. "PING_ENDPOINT": settings.PING_ENDPOINT,
  99. "default_timeout": int(DEFAULT_TIMEOUT.total_seconds()),
  100. "default_grace": int(DEFAULT_GRACE.total_seconds())
  101. }
  102. return render(request, "front/docs_api.html", ctx)
  103. def about(request):
  104. return render(request, "front/about.html", {"page": "about"})
  105. @require_POST
  106. @login_required
  107. def add_check(request):
  108. check = Check(user=request.team.user)
  109. check.save()
  110. check.assign_all_channels()
  111. return redirect("hc-checks")
  112. @require_POST
  113. @login_required
  114. @uuid_or_400
  115. def update_name(request, code):
  116. check = get_object_or_404(Check, code=code)
  117. if check.user_id != request.team.user.id:
  118. return HttpResponseForbidden()
  119. form = NameTagsForm(request.POST)
  120. if form.is_valid():
  121. check.name = form.cleaned_data["name"]
  122. check.tags = form.cleaned_data["tags"]
  123. check.save()
  124. return redirect("hc-checks")
  125. @require_POST
  126. @login_required
  127. @uuid_or_400
  128. def update_timeout(request, code):
  129. check = get_object_or_404(Check, code=code)
  130. if check.user != request.team.user:
  131. return HttpResponseForbidden()
  132. kind = request.POST.get("kind")
  133. if kind == "simple":
  134. form = TimeoutForm(request.POST)
  135. if not form.is_valid():
  136. return HttpResponseBadRequest()
  137. check.kind = "simple"
  138. check.timeout = td(seconds=form.cleaned_data["timeout"])
  139. check.grace = td(seconds=form.cleaned_data["grace"])
  140. elif kind == "cron":
  141. form = CronForm(request.POST)
  142. if not form.is_valid():
  143. return HttpResponseBadRequest()
  144. check.kind = "cron"
  145. check.schedule = form.cleaned_data["schedule"]
  146. check.tz = form.cleaned_data["tz"]
  147. check.grace = td(minutes=form.cleaned_data["grace"])
  148. if check.last_ping:
  149. check.alert_after = check.get_alert_after()
  150. check.save()
  151. return redirect("hc-checks")
  152. @csrf_exempt
  153. @require_POST
  154. def cron_preview(request):
  155. schedule = request.POST.get("schedule")
  156. tz = request.POST.get("tz")
  157. ctx = {"tz": tz, "dates": []}
  158. try:
  159. with timezone.override(tz):
  160. now_naive = timezone.make_naive(timezone.now())
  161. it = croniter(schedule, now_naive)
  162. for i in range(0, 6):
  163. naive = it.get_next(datetime)
  164. aware = timezone.make_aware(naive)
  165. ctx["dates"].append((naive, aware))
  166. except UnknownTimeZoneError:
  167. ctx["bad_tz"] = True
  168. except:
  169. ctx["bad_schedule"] = True
  170. return render(request, "front/cron_preview.html", ctx)
  171. @require_POST
  172. @login_required
  173. @uuid_or_400
  174. def pause(request, code):
  175. check = get_object_or_404(Check, code=code)
  176. if check.user_id != request.team.user.id:
  177. return HttpResponseForbidden()
  178. check.status = "paused"
  179. check.save()
  180. return redirect("hc-checks")
  181. @require_POST
  182. @login_required
  183. @uuid_or_400
  184. def remove_check(request, code):
  185. check = get_object_or_404(Check, code=code)
  186. if check.user != request.team.user:
  187. return HttpResponseForbidden()
  188. check.delete()
  189. return redirect("hc-checks")
  190. @login_required
  191. @uuid_or_400
  192. def log(request, code):
  193. check = get_object_or_404(Check, code=code)
  194. if check.user != request.team.user:
  195. return HttpResponseForbidden()
  196. limit = request.team.ping_log_limit
  197. pings = Ping.objects.filter(owner=check).order_by("-id")[:limit + 1]
  198. pings = list(pings)
  199. num_pings = len(pings)
  200. pings = pings[:limit]
  201. alerts = []
  202. if len(pings):
  203. cutoff = pings[-1].created
  204. alerts = Notification.objects \
  205. .select_related("channel") \
  206. .filter(owner=check, check_status="down", created__gt=cutoff)
  207. events = pings + list(alerts)
  208. events.sort(key=lambda el: el.created, reverse=True)
  209. ctx = {
  210. "check": check,
  211. "events": events,
  212. "num_pings": min(num_pings, limit),
  213. "limit": limit,
  214. "show_limit_notice": num_pings > limit and settings.USE_PAYMENTS
  215. }
  216. return render(request, "front/log.html", ctx)
  217. @login_required
  218. def channels(request):
  219. if request.method == "POST":
  220. code = request.POST["channel"]
  221. try:
  222. channel = Channel.objects.get(code=code)
  223. except Channel.DoesNotExist:
  224. return HttpResponseBadRequest()
  225. if channel.user_id != request.team.user.id:
  226. return HttpResponseForbidden()
  227. new_checks = []
  228. for key in request.POST:
  229. if key.startswith("check-"):
  230. code = key[6:]
  231. try:
  232. check = Check.objects.get(code=code)
  233. except Check.DoesNotExist:
  234. return HttpResponseBadRequest()
  235. if check.user_id != request.team.user.id:
  236. return HttpResponseForbidden()
  237. new_checks.append(check)
  238. channel.checks = new_checks
  239. return redirect("hc-channels")
  240. channels = Channel.objects.filter(user=request.team.user)
  241. channels = channels.order_by("created")
  242. channels = channels.annotate(n_checks=Count("checks"))
  243. num_checks = Check.objects.filter(user=request.team.user).count()
  244. ctx = {
  245. "page": "channels",
  246. "channels": channels,
  247. "num_checks": num_checks,
  248. "enable_pushbullet": settings.PUSHBULLET_CLIENT_ID is not None,
  249. "enable_pushover": settings.PUSHOVER_API_TOKEN is not None,
  250. "enable_discord": settings.DISCORD_CLIENT_ID is not None
  251. }
  252. return render(request, "front/channels.html", ctx)
  253. @login_required
  254. @uuid_or_400
  255. def channel_checks(request, code):
  256. channel = get_object_or_404(Channel, code=code)
  257. if channel.user_id != request.team.user.id:
  258. return HttpResponseForbidden()
  259. assigned = set(channel.checks.values_list('code', flat=True).distinct())
  260. checks = Check.objects.filter(user=request.team.user).order_by("created")
  261. ctx = {
  262. "checks": checks,
  263. "assigned": assigned,
  264. "channel": channel
  265. }
  266. return render(request, "front/channel_checks.html", ctx)
  267. @uuid_or_400
  268. def verify_email(request, code, token):
  269. channel = get_object_or_404(Channel, code=code)
  270. if channel.make_token() == token:
  271. channel.email_verified = True
  272. channel.save()
  273. return render(request, "front/verify_email_success.html")
  274. return render(request, "bad_link.html")
  275. @uuid_or_400
  276. def unsubscribe_email(request, code, token):
  277. channel = get_object_or_404(Channel, code=code)
  278. if channel.make_token() != token:
  279. return render(request, "bad_link.html")
  280. if channel.kind != "email":
  281. return HttpResponseBadRequest()
  282. channel.delete()
  283. return render(request, "front/unsubscribe_success.html")
  284. @require_POST
  285. @login_required
  286. @uuid_or_400
  287. def remove_channel(request, code):
  288. # user may refresh the page during POST and cause two deletion attempts
  289. channel = Channel.objects.filter(code=code).first()
  290. if channel:
  291. if channel.user != request.team.user:
  292. return HttpResponseForbidden()
  293. channel.delete()
  294. return redirect("hc-channels")
  295. @login_required
  296. def add_email(request):
  297. if request.method == "POST":
  298. form = AddEmailForm(request.POST)
  299. if form.is_valid():
  300. channel = Channel(user=request.team.user, kind="email")
  301. channel.value = form.cleaned_data["value"]
  302. channel.save()
  303. channel.assign_all_checks()
  304. channel.send_verify_link()
  305. return redirect("hc-channels")
  306. else:
  307. form = AddEmailForm()
  308. ctx = {"page": "channels", "form": form}
  309. return render(request, "integrations/add_email.html", ctx)
  310. @login_required
  311. def add_webhook(request):
  312. if request.method == "POST":
  313. form = AddWebhookForm(request.POST)
  314. if form.is_valid():
  315. channel = Channel(user=request.team.user, kind="webhook")
  316. channel.value = form.get_value()
  317. channel.save()
  318. channel.assign_all_checks()
  319. return redirect("hc-channels")
  320. else:
  321. form = AddWebhookForm()
  322. ctx = {
  323. "page": "channels",
  324. "form": form,
  325. "now": timezone.now().replace(microsecond=0).isoformat()
  326. }
  327. return render(request, "integrations/add_webhook.html", ctx)
  328. @login_required
  329. def add_pd(request):
  330. if request.method == "POST":
  331. form = AddPdForm(request.POST)
  332. if form.is_valid():
  333. channel = Channel(user=request.team.user, kind="pd")
  334. channel.value = form.cleaned_data["value"]
  335. channel.save()
  336. channel.assign_all_checks()
  337. return redirect("hc-channels")
  338. else:
  339. form = AddPdForm()
  340. ctx = {"page": "channels", "form": form}
  341. return render(request, "integrations/add_pd.html", ctx)
  342. def _prepare_state(request, session_key):
  343. state = get_random_string()
  344. request.session[session_key] = state
  345. return state
  346. def _get_validated_code(request, session_key):
  347. if session_key not in request.session:
  348. return None
  349. session_state = request.session.pop(session_key)
  350. request_state = request.GET.get("state")
  351. if session_state is None or session_state != request_state:
  352. return None
  353. return request.GET.get("code")
  354. def add_slack(request):
  355. if not settings.SLACK_CLIENT_ID and not request.user.is_authenticated:
  356. return redirect("hc-login")
  357. if request.method == "POST":
  358. form = AddUrlForm(request.POST)
  359. if form.is_valid():
  360. channel = Channel(user=request.team.user, kind="slack")
  361. channel.value = form.cleaned_data["value"]
  362. channel.save()
  363. channel.assign_all_checks()
  364. return redirect("hc-channels")
  365. else:
  366. form = AddUrlForm()
  367. ctx = {
  368. "page": "channels",
  369. "form": form,
  370. "slack_client_id": settings.SLACK_CLIENT_ID
  371. }
  372. if settings.SLACK_CLIENT_ID:
  373. ctx["state"] = _prepare_state(request, "slack")
  374. return render(request, "integrations/add_slack.html", ctx)
  375. @login_required
  376. def add_slack_btn(request):
  377. code = _get_validated_code(request, "slack")
  378. if code is None:
  379. return HttpResponseBadRequest()
  380. result = requests.post("https://slack.com/api/oauth.access", {
  381. "client_id": settings.SLACK_CLIENT_ID,
  382. "client_secret": settings.SLACK_CLIENT_SECRET,
  383. "code": code
  384. })
  385. doc = result.json()
  386. if doc.get("ok"):
  387. channel = Channel()
  388. channel.user = request.team.user
  389. channel.kind = "slack"
  390. channel.value = result.text
  391. channel.save()
  392. channel.assign_all_checks()
  393. messages.success(request, "The Slack integration has been added!")
  394. else:
  395. s = doc.get("error")
  396. messages.warning(request, "Error message from slack: %s" % s)
  397. return redirect("hc-channels")
  398. @login_required
  399. def add_hipchat(request):
  400. if request.method == "POST":
  401. form = AddUrlForm(request.POST)
  402. if form.is_valid():
  403. channel = Channel(user=request.team.user, kind="hipchat")
  404. channel.value = form.cleaned_data["value"]
  405. channel.save()
  406. channel.assign_all_checks()
  407. return redirect("hc-channels")
  408. else:
  409. form = AddUrlForm()
  410. ctx = {"page": "channels", "form": form}
  411. return render(request, "integrations/add_hipchat.html", ctx)
  412. @login_required
  413. def add_pushbullet(request):
  414. if settings.PUSHBULLET_CLIENT_ID is None:
  415. raise Http404("pushbullet integration is not available")
  416. if "code" in request.GET:
  417. code = _get_validated_code(request, "pushbullet")
  418. if code is None:
  419. return HttpResponseBadRequest()
  420. result = requests.post("https://api.pushbullet.com/oauth2/token", {
  421. "client_id": settings.PUSHBULLET_CLIENT_ID,
  422. "client_secret": settings.PUSHBULLET_CLIENT_SECRET,
  423. "code": code,
  424. "grant_type": "authorization_code"
  425. })
  426. doc = result.json()
  427. if "access_token" in doc:
  428. channel = Channel(kind="pushbullet")
  429. channel.user = request.team.user
  430. channel.value = doc["access_token"]
  431. channel.save()
  432. channel.assign_all_checks()
  433. messages.success(request,
  434. "The Pushbullet integration has been added!")
  435. else:
  436. messages.warning(request, "Something went wrong")
  437. return redirect("hc-channels")
  438. redirect_uri = settings.SITE_ROOT + reverse("hc-add-pushbullet")
  439. authorize_url = "https://www.pushbullet.com/authorize?" + urlencode({
  440. "client_id": settings.PUSHBULLET_CLIENT_ID,
  441. "redirect_uri": redirect_uri,
  442. "response_type": "code",
  443. "state": _prepare_state(request, "pushbullet")
  444. })
  445. ctx = {
  446. "page": "channels",
  447. "authorize_url": authorize_url
  448. }
  449. return render(request, "integrations/add_pushbullet.html", ctx)
  450. @login_required
  451. def add_discord(request):
  452. if settings.DISCORD_CLIENT_ID is None:
  453. raise Http404("discord integration is not available")
  454. redirect_uri = settings.SITE_ROOT + reverse("hc-add-discord")
  455. if "code" in request.GET:
  456. code = _get_validated_code(request, "discord")
  457. if code is None:
  458. return HttpResponseBadRequest()
  459. result = requests.post("https://discordapp.com/api/oauth2/token", {
  460. "client_id": settings.DISCORD_CLIENT_ID,
  461. "client_secret": settings.DISCORD_CLIENT_SECRET,
  462. "code": code,
  463. "grant_type": "authorization_code",
  464. "redirect_uri": redirect_uri
  465. })
  466. doc = result.json()
  467. if "access_token" in doc:
  468. channel = Channel(kind="discord")
  469. channel.user = request.team.user
  470. channel.value = result.text
  471. channel.save()
  472. channel.assign_all_checks()
  473. messages.success(request,
  474. "The Discord integration has been added!")
  475. else:
  476. messages.warning(request, "Something went wrong")
  477. return redirect("hc-channels")
  478. auth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode({
  479. "client_id": settings.DISCORD_CLIENT_ID,
  480. "scope": "webhook.incoming",
  481. "redirect_uri": redirect_uri,
  482. "response_type": "code",
  483. "state": _prepare_state(request, "discord")
  484. })
  485. ctx = {
  486. "page": "channels",
  487. "authorize_url": auth_url
  488. }
  489. return render(request, "integrations/add_discord.html", ctx)
  490. @login_required
  491. def add_pushover(request):
  492. if settings.PUSHOVER_API_TOKEN is None or settings.PUSHOVER_SUBSCRIPTION_URL is None:
  493. raise Http404("pushover integration is not available")
  494. if request.method == "POST":
  495. # Initiate the subscription
  496. nonce = get_random_string()
  497. request.session["po_nonce"] = nonce
  498. failure_url = settings.SITE_ROOT + reverse("hc-channels")
  499. success_url = settings.SITE_ROOT + reverse("hc-add-pushover") + "?" + urlencode({
  500. "nonce": nonce,
  501. "prio": request.POST.get("po_priority", "0"),
  502. })
  503. subscription_url = settings.PUSHOVER_SUBSCRIPTION_URL + "?" + urlencode({
  504. "success": success_url,
  505. "failure": failure_url,
  506. })
  507. return redirect(subscription_url)
  508. # Handle successful subscriptions
  509. if "pushover_user_key" in request.GET:
  510. if "nonce" not in request.GET or "prio" not in request.GET:
  511. return HttpResponseBadRequest()
  512. # Validate nonce
  513. if request.GET["nonce"] != request.session.get("po_nonce"):
  514. return HttpResponseForbidden()
  515. # Validate priority
  516. if request.GET["prio"] not in ("-2", "-1", "0", "1", "2"):
  517. return HttpResponseBadRequest()
  518. # All looks well--
  519. del request.session["po_nonce"]
  520. if request.GET.get("pushover_unsubscribed") == "1":
  521. # Unsubscription: delete all Pushover channels for this user
  522. Channel.objects.filter(user=request.user, kind="po").delete()
  523. return redirect("hc-channels")
  524. else:
  525. # Subscription
  526. user_key = request.GET["pushover_user_key"]
  527. priority = int(request.GET["prio"])
  528. channel = Channel(user=request.team.user, kind="po")
  529. channel.value = "%s|%d" % (user_key, priority)
  530. channel.save()
  531. channel.assign_all_checks()
  532. return redirect("hc-channels")
  533. # Show Integration Settings form
  534. ctx = {
  535. "page": "channels",
  536. "po_retry_delay": td(seconds=settings.PUSHOVER_EMERGENCY_RETRY_DELAY),
  537. "po_expiration": td(seconds=settings.PUSHOVER_EMERGENCY_EXPIRATION),
  538. }
  539. return render(request, "integrations/add_pushover.html", ctx)
  540. @login_required
  541. def add_opsgenie(request):
  542. if request.method == "POST":
  543. form = AddOpsGenieForm(request.POST)
  544. if form.is_valid():
  545. channel = Channel(user=request.team.user, kind="opsgenie")
  546. channel.value = form.cleaned_data["value"]
  547. channel.save()
  548. channel.assign_all_checks()
  549. return redirect("hc-channels")
  550. else:
  551. form = AddUrlForm()
  552. ctx = {"page": "channels", "form": form}
  553. return render(request, "integrations/add_opsgenie.html", ctx)
  554. @login_required
  555. def add_victorops(request):
  556. if request.method == "POST":
  557. form = AddUrlForm(request.POST)
  558. if form.is_valid():
  559. channel = Channel(user=request.team.user, kind="victorops")
  560. channel.value = form.cleaned_data["value"]
  561. channel.save()
  562. channel.assign_all_checks()
  563. return redirect("hc-channels")
  564. else:
  565. form = AddUrlForm()
  566. ctx = {"page": "channels", "form": form}
  567. return render(request, "integrations/add_victorops.html", ctx)
  568. def privacy(request):
  569. return render(request, "front/privacy.html", {})
  570. def terms(request):
  571. return render(request, "front/terms.html", {})