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.

450 lines
14 KiB

10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. from datetime import timedelta as td
  2. import uuid
  3. import re
  4. from django.conf import settings
  5. from django.contrib import messages
  6. from django.contrib.auth import login as auth_login
  7. from django.contrib.auth import logout as auth_logout
  8. from django.contrib.auth import authenticate
  9. from django.contrib.auth.decorators import login_required
  10. from django.contrib.auth.models import User
  11. from django.core import signing
  12. from django.http import HttpResponseForbidden, HttpResponseBadRequest
  13. from django.shortcuts import redirect, render
  14. from django.utils.timezone import now
  15. from django.urls import resolve, Resolver404
  16. from django.views.decorators.csrf import csrf_exempt
  17. from django.views.decorators.http import require_POST
  18. from hc.accounts.forms import (ChangeEmailForm, EmailPasswordForm,
  19. InviteTeamMemberForm, RemoveTeamMemberForm,
  20. ReportSettingsForm, SetPasswordForm,
  21. TeamNameForm, AvailableEmailForm,
  22. ExistingEmailForm)
  23. from hc.accounts.models import Profile, Member
  24. from hc.api.models import Channel, Check
  25. from hc.lib.badges import get_badge_url
  26. from hc.payments.models import Subscription
  27. NEXT_WHITELIST = ("hc-checks",
  28. "hc-details",
  29. "hc-log",
  30. "hc-channels",
  31. "hc-add-slack",
  32. "hc-add-pushover")
  33. def _is_whitelisted(path):
  34. try:
  35. match = resolve(path)
  36. except Resolver404:
  37. return False
  38. return match.url_name in NEXT_WHITELIST
  39. def _make_user(email):
  40. username = str(uuid.uuid4())[:30]
  41. user = User(username=username, email=email)
  42. user.set_unusable_password()
  43. user.save()
  44. # Ensure a profile gets created
  45. Profile.objects.for_user(user)
  46. check = Check(user=user)
  47. check.name = "My First Check"
  48. check.save()
  49. channel = Channel(user=user)
  50. channel.kind = "email"
  51. channel.value = email
  52. channel.email_verified = True
  53. channel.save()
  54. channel.checks.add(check)
  55. return user
  56. def _ensure_own_team(request):
  57. """ Make sure user is switched to their own team. """
  58. if request.team != request.profile:
  59. request.team = request.profile
  60. request.profile.current_team = request.profile
  61. request.profile.save()
  62. def _redirect_after_login(request):
  63. """ Redirect to the URL indicated in ?next= query parameter. """
  64. redirect_url = request.GET.get("next")
  65. if _is_whitelisted(redirect_url):
  66. return redirect(redirect_url)
  67. return redirect("hc-checks")
  68. def login(request):
  69. form = EmailPasswordForm()
  70. magic_form = ExistingEmailForm()
  71. if request.method == 'POST':
  72. if request.POST.get("action") == "login":
  73. form = EmailPasswordForm(request.POST)
  74. if form.is_valid():
  75. auth_login(request, form.user)
  76. return _redirect_after_login(request)
  77. else:
  78. magic_form = ExistingEmailForm(request.POST)
  79. if magic_form.is_valid():
  80. profile = Profile.objects.for_user(magic_form.user)
  81. redirect_url = request.GET.get("next")
  82. if _is_whitelisted(redirect_url):
  83. profile.send_instant_login_link(redirect_url=redirect_url)
  84. else:
  85. profile.send_instant_login_link()
  86. return redirect("hc-login-link-sent")
  87. bad_link = request.session.pop("bad_link", None)
  88. ctx = {
  89. "page": "login",
  90. "form": form,
  91. "magic_form": magic_form,
  92. "bad_link": bad_link
  93. }
  94. return render(request, "accounts/login.html", ctx)
  95. def logout(request):
  96. auth_logout(request)
  97. return redirect("hc-index")
  98. @require_POST
  99. def signup(request):
  100. if not settings.REGISTRATION_OPEN:
  101. return HttpResponseForbidden()
  102. ctx = {}
  103. form = AvailableEmailForm(request.POST)
  104. if form.is_valid():
  105. email = form.cleaned_data["identity"]
  106. user = _make_user(email)
  107. profile = Profile.objects.for_user(user)
  108. profile.send_instant_login_link()
  109. ctx["created"] = True
  110. else:
  111. ctx = {"form": form}
  112. return render(request, "accounts/signup_result.html", ctx)
  113. def login_link_sent(request):
  114. return render(request, "accounts/login_link_sent.html")
  115. def link_sent(request):
  116. return render(request, "accounts/link_sent.html")
  117. def check_token(request, username, token):
  118. if request.user.is_authenticated and request.user.username == username:
  119. # User is already logged in
  120. return _redirect_after_login(request)
  121. # Some email servers open links in emails to check for malicious content.
  122. # To work around this, we sign user in if the method is POST.
  123. #
  124. # If the method is GET, we instead serve a HTML form and a piece
  125. # of Javascript to automatically submit it.
  126. if request.method == "POST":
  127. user = authenticate(username=username, token=token)
  128. if user is not None and user.is_active:
  129. user.profile.token = ""
  130. user.profile.save()
  131. auth_login(request, user)
  132. return _redirect_after_login(request)
  133. request.session["bad_link"] = True
  134. return redirect("hc-login")
  135. return render(request, "accounts/check_token_submit.html")
  136. @login_required
  137. def profile(request):
  138. _ensure_own_team(request)
  139. profile = request.profile
  140. ctx = {
  141. "page": "profile",
  142. "profile": profile,
  143. "show_api_keys": False,
  144. "api_status": "default",
  145. "team_status": "default"
  146. }
  147. if request.method == "POST":
  148. if "change_email" in request.POST:
  149. profile.send_change_email_link()
  150. return redirect("hc-link-sent")
  151. elif "set_password" in request.POST:
  152. profile.send_set_password_link()
  153. return redirect("hc-link-sent")
  154. elif "create_api_keys" in request.POST:
  155. profile.set_api_keys()
  156. ctx["show_api_keys"] = True
  157. ctx["api_keys_created"] = True
  158. ctx["api_status"] = "success"
  159. elif "revoke_api_keys" in request.POST:
  160. profile.api_key_id = ""
  161. profile.api_key = ""
  162. profile.api_key_readonly = ""
  163. profile.save()
  164. ctx["api_keys_revoked"] = True
  165. ctx["api_status"] = "info"
  166. elif "show_api_keys" in request.POST:
  167. ctx["show_api_keys"] = True
  168. elif "invite_team_member" in request.POST:
  169. if not profile.can_invite():
  170. return HttpResponseForbidden()
  171. form = InviteTeamMemberForm(request.POST)
  172. if form.is_valid():
  173. email = form.cleaned_data["email"]
  174. try:
  175. user = User.objects.get(email=email)
  176. except User.DoesNotExist:
  177. user = _make_user(email)
  178. profile.invite(user)
  179. ctx["team_member_invited"] = email
  180. ctx["team_status"] = "success"
  181. elif "remove_team_member" in request.POST:
  182. form = RemoveTeamMemberForm(request.POST)
  183. if form.is_valid():
  184. email = form.cleaned_data["email"]
  185. farewell_user = User.objects.get(email=email)
  186. farewell_user.profile.current_team = None
  187. farewell_user.profile.save()
  188. Member.objects.filter(team=profile,
  189. user=farewell_user).delete()
  190. ctx["team_member_removed"] = email
  191. ctx["team_status"] = "info"
  192. elif "set_team_name" in request.POST:
  193. form = TeamNameForm(request.POST)
  194. if form.is_valid():
  195. profile.team_name = form.cleaned_data["team_name"]
  196. profile.save()
  197. ctx["team_name_updated"] = True
  198. ctx["team_status"] = "success"
  199. return render(request, "accounts/profile.html", ctx)
  200. @login_required
  201. def notifications(request):
  202. _ensure_own_team(request)
  203. profile = request.profile
  204. ctx = {
  205. "status": "default",
  206. "page": "profile",
  207. "profile": profile
  208. }
  209. if request.method == "POST":
  210. form = ReportSettingsForm(request.POST)
  211. if form.is_valid():
  212. if profile.reports_allowed != form.cleaned_data["reports_allowed"]:
  213. profile.reports_allowed = form.cleaned_data["reports_allowed"]
  214. if profile.reports_allowed:
  215. profile.next_report_date = now() + td(days=30)
  216. else:
  217. profile.next_report_date = None
  218. if profile.nag_period != form.cleaned_data["nag_period"]:
  219. # Set the new nag period
  220. profile.nag_period = form.cleaned_data["nag_period"]
  221. # and schedule next_nag_date:
  222. if profile.nag_period:
  223. profile.next_nag_date = now() + profile.nag_period
  224. else:
  225. profile.next_nag_date = None
  226. profile.save()
  227. ctx["status"] = "info"
  228. return render(request, "accounts/notifications.html", ctx)
  229. @login_required
  230. def badges(request):
  231. _ensure_own_team(request)
  232. teams = [request.profile]
  233. for membership in request.user.memberships.all():
  234. teams.append(membership.team)
  235. badge_sets = []
  236. for team in teams:
  237. tags = set()
  238. for check in Check.objects.filter(user=team.user):
  239. tags.update(check.tags_list())
  240. sorted_tags = sorted(tags, key=lambda s: s.lower())
  241. sorted_tags.append("*") # For the "overall status" badge
  242. urls = []
  243. username = team.user.username
  244. for tag in sorted_tags:
  245. if not re.match("^[\w-]+$", tag) and tag != "*":
  246. continue
  247. urls.append({
  248. "svg": get_badge_url(username, tag),
  249. "json": get_badge_url(username, tag, format="json"),
  250. })
  251. badge_sets.append({"team": team, "urls": urls})
  252. ctx = {
  253. "page": "profile",
  254. "badges": badge_sets
  255. }
  256. return render(request, "accounts/badges.html", ctx)
  257. @login_required
  258. def set_password(request, token):
  259. if not request.profile.check_token(token, "set-password"):
  260. return HttpResponseBadRequest()
  261. if request.method == "POST":
  262. form = SetPasswordForm(request.POST)
  263. if form.is_valid():
  264. password = form.cleaned_data["password"]
  265. request.user.set_password(password)
  266. request.user.save()
  267. request.profile.token = ""
  268. request.profile.save()
  269. # Setting a password logs the user out, so here we
  270. # log them back in.
  271. u = authenticate(username=request.user.email, password=password)
  272. auth_login(request, u)
  273. messages.success(request, "Your password has been set!")
  274. return redirect("hc-profile")
  275. return render(request, "accounts/set_password.html", {})
  276. @login_required
  277. def change_email(request, token):
  278. if not request.profile.check_token(token, "change-email"):
  279. return HttpResponseBadRequest()
  280. if request.method == "POST":
  281. form = ChangeEmailForm(request.POST)
  282. if form.is_valid():
  283. request.user.email = form.cleaned_data["email"]
  284. request.user.set_unusable_password()
  285. request.user.save()
  286. request.profile.token = ""
  287. request.profile.save()
  288. return redirect("hc-change-email-done")
  289. else:
  290. form = ChangeEmailForm()
  291. return render(request, "accounts/change_email.html", {"form": form})
  292. def change_email_done(request):
  293. return render(request, "accounts/change_email_done.html")
  294. @csrf_exempt
  295. def unsubscribe_reports(request, username):
  296. signer = signing.TimestampSigner(salt="reports")
  297. try:
  298. username = signer.unsign(username)
  299. except signing.BadSignature:
  300. return render(request, "bad_link.html")
  301. # Some email servers open links in emails to check for malicious content.
  302. # To work around this, we serve a form that auto-submits with JS.
  303. if "ask" in request.GET and request.method != "POST":
  304. return render(request, "accounts/unsubscribe_submit.html")
  305. user = User.objects.get(username=username)
  306. profile = Profile.objects.for_user(user)
  307. profile.reports_allowed = False
  308. profile.next_report_date = None
  309. profile.nag_period = td()
  310. profile.next_nag_date = None
  311. profile.save()
  312. return render(request, "accounts/unsubscribed.html")
  313. @login_required
  314. def switch_team(request, target_username):
  315. try:
  316. target_team = Profile.objects.get(user__username=target_username)
  317. except Profile.DoesNotExist:
  318. return HttpResponseForbidden()
  319. # The rules:
  320. # Superuser can switch to any team.
  321. access_ok = request.user.is_superuser
  322. # Users can switch to their own teams.
  323. if not access_ok and target_team == request.profile:
  324. access_ok = True
  325. # Users can switch to teams they are members of.
  326. if not access_ok:
  327. access_ok = request.user.memberships.filter(team=target_team).exists()
  328. if not access_ok:
  329. return HttpResponseForbidden()
  330. request.profile.current_team = target_team
  331. request.profile.save()
  332. return redirect("hc-checks")
  333. @require_POST
  334. @login_required
  335. def close(request):
  336. user = request.user
  337. # Subscription needs to be canceled before it is deleted:
  338. sub = Subscription.objects.filter(user=user).first()
  339. if sub:
  340. sub.cancel()
  341. user.delete()
  342. # Deleting user also deletes its profile, checks, channels etc.
  343. request.session.flush()
  344. return redirect("hc-index")