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.

470 lines
14 KiB

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