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.

545 lines
17 KiB

10 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
9 years ago
9 years ago
9 years ago
9 years ago
  1. from datetime import timedelta as td
  2. from urllib.parse import urlparse
  3. import uuid
  4. from django.db import transaction
  5. from django.conf import settings
  6. from django.contrib import messages
  7. from django.contrib.auth import login as auth_login
  8. from django.contrib.auth import logout as auth_logout
  9. from django.contrib.auth import authenticate
  10. from django.contrib.auth.decorators import login_required
  11. from django.contrib.auth.models import User
  12. from django.core import signing
  13. from django.http import (
  14. HttpResponseForbidden,
  15. HttpResponseBadRequest,
  16. HttpResponseNotFound,
  17. )
  18. from django.shortcuts import get_object_or_404, redirect, render
  19. from django.utils.timezone import now
  20. from django.urls import resolve, Resolver404
  21. from django.views.decorators.csrf import csrf_exempt
  22. from django.views.decorators.http import require_POST
  23. from hc.accounts import forms
  24. from hc.accounts.models import Profile, Project, Member
  25. from hc.api.models import Channel, Check, TokenBucket
  26. from hc.lib.date import choose_next_report_date
  27. from hc.payments.models import Subscription
  28. NEXT_WHITELIST = (
  29. "hc-checks",
  30. "hc-details",
  31. "hc-log",
  32. "hc-p-channels",
  33. "hc-add-slack",
  34. "hc-add-pushover",
  35. "hc-add-telegram",
  36. "hc-project-settings",
  37. )
  38. def _is_whitelisted(redirect_url):
  39. if not redirect_url:
  40. return False
  41. parsed = urlparse(redirect_url)
  42. try:
  43. match = resolve(parsed.path)
  44. except Resolver404:
  45. return False
  46. return match.url_name in NEXT_WHITELIST
  47. def _make_user(email, with_project=True):
  48. username = str(uuid.uuid4())[:30]
  49. user = User(username=username, email=email)
  50. user.set_unusable_password()
  51. user.save()
  52. project = None
  53. if with_project:
  54. project = Project(owner=user)
  55. project.badge_key = user.username
  56. project.save()
  57. check = Check(project=project)
  58. check.name = "My First Check"
  59. check.save()
  60. channel = Channel(project=project)
  61. channel.kind = "email"
  62. channel.value = email
  63. channel.email_verified = True
  64. channel.save()
  65. channel.checks.add(check)
  66. # Ensure a profile gets created
  67. Profile.objects.for_user(user)
  68. return user
  69. def _redirect_after_login(request):
  70. """ Redirect to the URL indicated in ?next= query parameter. """
  71. redirect_url = request.GET.get("next")
  72. if _is_whitelisted(redirect_url):
  73. return redirect(redirect_url)
  74. if request.user.project_set.count() == 1:
  75. project = request.user.project_set.first()
  76. return redirect("hc-checks", project.code)
  77. return redirect("hc-index")
  78. def login(request):
  79. form = forms.PasswordLoginForm()
  80. magic_form = forms.EmailLoginForm()
  81. if request.method == "POST":
  82. if request.POST.get("action") == "login":
  83. form = forms.PasswordLoginForm(request.POST)
  84. if form.is_valid():
  85. auth_login(request, form.user)
  86. return _redirect_after_login(request)
  87. else:
  88. magic_form = forms.EmailLoginForm(request.POST)
  89. if magic_form.is_valid():
  90. redirect_url = request.GET.get("next")
  91. if not _is_whitelisted(redirect_url):
  92. redirect_url = None
  93. profile = Profile.objects.for_user(magic_form.user)
  94. profile.send_instant_login_link(redirect_url=redirect_url)
  95. response = redirect("hc-login-link-sent")
  96. # check_token_submit looks for this cookie to decide if
  97. # it needs to do the extra POST step.
  98. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  99. return response
  100. bad_link = request.session.pop("bad_link", None)
  101. ctx = {
  102. "page": "login",
  103. "form": form,
  104. "magic_form": magic_form,
  105. "bad_link": bad_link,
  106. "registration_open": settings.REGISTRATION_OPEN,
  107. }
  108. return render(request, "accounts/login.html", ctx)
  109. def logout(request):
  110. auth_logout(request)
  111. return redirect("hc-index")
  112. @require_POST
  113. @csrf_exempt
  114. def signup(request):
  115. if not settings.REGISTRATION_OPEN:
  116. return HttpResponseForbidden()
  117. ctx = {}
  118. form = forms.AvailableEmailForm(request.POST)
  119. if form.is_valid():
  120. email = form.cleaned_data["identity"]
  121. user = _make_user(email)
  122. profile = Profile.objects.for_user(user)
  123. profile.send_instant_login_link()
  124. ctx["created"] = True
  125. else:
  126. ctx = {"form": form}
  127. response = render(request, "accounts/signup_result.html", ctx)
  128. if ctx.get("created"):
  129. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  130. return response
  131. def login_link_sent(request):
  132. return render(request, "accounts/login_link_sent.html")
  133. def link_sent(request):
  134. return render(request, "accounts/link_sent.html")
  135. def check_token(request, username, token):
  136. if request.user.is_authenticated and request.user.username == username:
  137. # User is already logged in
  138. return _redirect_after_login(request)
  139. # Some email servers open links in emails to check for malicious content.
  140. # To work around this, we sign user in if the method is POST
  141. # *or* if the browser presents a cookie we had set when sending the login link.
  142. #
  143. # If the method is GET, we instead serve a HTML form and a piece
  144. # of Javascript to automatically submit it.
  145. if request.method == "POST" or "auto-login" in request.COOKIES:
  146. user = authenticate(username=username, token=token)
  147. if user is not None and user.is_active:
  148. user.profile.token = ""
  149. user.profile.save()
  150. auth_login(request, user)
  151. return _redirect_after_login(request)
  152. request.session["bad_link"] = True
  153. return redirect("hc-login")
  154. return render(request, "accounts/check_token_submit.html")
  155. @login_required
  156. def profile(request):
  157. profile = request.profile
  158. ctx = {"page": "profile", "profile": profile, "my_projects_status": "default"}
  159. if request.method == "POST":
  160. if "change_email" in request.POST:
  161. profile.send_change_email_link()
  162. return redirect("hc-link-sent")
  163. elif "set_password" in request.POST:
  164. profile.send_set_password_link()
  165. return redirect("hc-link-sent")
  166. elif "leave_project" in request.POST:
  167. code = request.POST["code"]
  168. try:
  169. project = Project.objects.get(code=code, member__user=request.user)
  170. except Project.DoesNotExist:
  171. return HttpResponseBadRequest()
  172. Member.objects.filter(project=project, user=request.user).delete()
  173. ctx["left_project"] = project
  174. ctx["my_projects_status"] = "info"
  175. # Retrieve projects right before rendering the template--
  176. # The list of the projects might have *just* changed
  177. ctx["projects"] = list(profile.projects())
  178. return render(request, "accounts/profile.html", ctx)
  179. @login_required
  180. @require_POST
  181. def add_project(request):
  182. form = forms.ProjectNameForm(request.POST)
  183. if not form.is_valid():
  184. return HttpResponseBadRequest()
  185. project = Project(owner=request.user)
  186. project.code = project.badge_key = str(uuid.uuid4())
  187. project.name = form.cleaned_data["name"]
  188. project.save()
  189. return redirect("hc-checks", project.code)
  190. @login_required
  191. def project(request, code):
  192. if request.user.is_superuser:
  193. q = Project.objects
  194. else:
  195. q = request.profile.projects()
  196. try:
  197. project = q.get(code=code)
  198. except Project.DoesNotExist:
  199. return HttpResponseNotFound()
  200. is_owner = project.owner_id == request.user.id
  201. ctx = {
  202. "page": "project",
  203. "project": project,
  204. "is_owner": is_owner,
  205. "show_api_keys": "show_api_keys" in request.GET,
  206. }
  207. if request.method == "POST":
  208. if "create_api_keys" in request.POST:
  209. project.set_api_keys()
  210. project.save()
  211. ctx["show_api_keys"] = True
  212. ctx["api_keys_created"] = True
  213. ctx["api_status"] = "success"
  214. elif "revoke_api_keys" in request.POST:
  215. project.api_key = ""
  216. project.api_key_readonly = ""
  217. project.save()
  218. ctx["api_keys_revoked"] = True
  219. ctx["api_status"] = "info"
  220. elif "show_api_keys" in request.POST:
  221. ctx["show_api_keys"] = True
  222. elif "invite_team_member" in request.POST:
  223. if not is_owner:
  224. return HttpResponseForbidden()
  225. form = forms.InviteTeamMemberForm(request.POST)
  226. if form.is_valid():
  227. email = form.cleaned_data["email"]
  228. invite_suggestions = project.invite_suggestions()
  229. if not invite_suggestions.filter(email=email).exists():
  230. # We're inviting a new user. Are we within team size limit?
  231. if not project.can_invite_new_users():
  232. return HttpResponseForbidden()
  233. # And are we not hitting a rate limit?
  234. if not TokenBucket.authorize_invite(request.user):
  235. return render(request, "try_later.html")
  236. try:
  237. user = User.objects.get(email=email)
  238. except User.DoesNotExist:
  239. user = _make_user(email, with_project=False)
  240. project.invite(user)
  241. ctx["team_member_invited"] = email
  242. ctx["team_status"] = "success"
  243. elif "remove_team_member" in request.POST:
  244. if not is_owner:
  245. return HttpResponseForbidden()
  246. form = forms.RemoveTeamMemberForm(request.POST)
  247. if form.is_valid():
  248. q = User.objects
  249. q = q.filter(email=form.cleaned_data["email"])
  250. q = q.filter(memberships__project=project)
  251. farewell_user = q.first()
  252. if farewell_user is None:
  253. return HttpResponseBadRequest()
  254. Member.objects.filter(project=project, user=farewell_user).delete()
  255. ctx["team_member_removed"] = form.cleaned_data["email"]
  256. ctx["team_status"] = "info"
  257. elif "set_project_name" in request.POST:
  258. form = forms.ProjectNameForm(request.POST)
  259. if form.is_valid():
  260. project.name = form.cleaned_data["name"]
  261. project.save()
  262. ctx["project_name_updated"] = True
  263. ctx["project_name_status"] = "success"
  264. elif "transfer_project" in request.POST:
  265. if not is_owner:
  266. return HttpResponseForbidden()
  267. form = forms.TransferForm(request.POST)
  268. if form.is_valid():
  269. # Look up the proposed new owner
  270. email = form.cleaned_data["email"]
  271. try:
  272. membership = project.member_set.filter(user__email=email).get()
  273. except Member.DoesNotExist:
  274. return HttpResponseBadRequest()
  275. # Revoke any previous transfer requests
  276. project.member_set.update(transfer_request_date=None)
  277. # Initiate the new request
  278. membership.transfer_request_date = now()
  279. membership.save()
  280. # Send an email notification
  281. profile = Profile.objects.for_user(membership.user)
  282. profile.send_transfer_request(project)
  283. ctx["transfer_initiated"] = True
  284. ctx["transfer_status"] = "success"
  285. elif "cancel_transfer" in request.POST:
  286. if not is_owner:
  287. return HttpResponseForbidden()
  288. project.member_set.update(transfer_request_date=None)
  289. ctx["transfer_cancelled"] = True
  290. ctx["transfer_status"] = "success"
  291. elif "accept_transfer" in request.POST:
  292. tr = project.transfer_request()
  293. if not tr or tr.user != request.user:
  294. return HttpResponseForbidden()
  295. if not tr.can_accept():
  296. return HttpResponseBadRequest()
  297. with transaction.atomic():
  298. # 1. Reuse the existing membership, and change its user
  299. tr.user = project.owner
  300. tr.transfer_request_date = None
  301. tr.save()
  302. # 2. Change project's owner
  303. project.owner = request.user
  304. project.save()
  305. ctx["is_owner"] = True
  306. messages.success(request, "You are now the owner of this project!")
  307. elif "reject_transfer" in request.POST:
  308. tr = project.transfer_request()
  309. if not tr or tr.user != request.user:
  310. return HttpResponseForbidden()
  311. tr.transfer_request_date = None
  312. tr.save()
  313. return render(request, "accounts/project.html", ctx)
  314. @login_required
  315. def notifications(request):
  316. profile = request.profile
  317. ctx = {"status": "default", "page": "profile", "profile": profile}
  318. if request.method == "POST":
  319. form = forms.ReportSettingsForm(request.POST)
  320. if form.is_valid():
  321. if profile.reports_allowed != form.cleaned_data["reports_allowed"]:
  322. profile.reports_allowed = form.cleaned_data["reports_allowed"]
  323. if profile.reports_allowed:
  324. profile.next_report_date = choose_next_report_date()
  325. else:
  326. profile.next_report_date = None
  327. if profile.nag_period != form.cleaned_data["nag_period"]:
  328. # Set the new nag period
  329. profile.nag_period = form.cleaned_data["nag_period"]
  330. # and schedule next_nag_date:
  331. if profile.nag_period:
  332. profile.next_nag_date = now() + profile.nag_period
  333. else:
  334. profile.next_nag_date = None
  335. profile.save()
  336. ctx["status"] = "info"
  337. return render(request, "accounts/notifications.html", ctx)
  338. @login_required
  339. def set_password(request, token):
  340. if not request.profile.check_token(token, "set-password"):
  341. return HttpResponseBadRequest()
  342. if request.method == "POST":
  343. form = forms.SetPasswordForm(request.POST)
  344. if form.is_valid():
  345. password = form.cleaned_data["password"]
  346. request.user.set_password(password)
  347. request.user.save()
  348. request.profile.token = ""
  349. request.profile.save()
  350. # Setting a password logs the user out, so here we
  351. # log them back in.
  352. u = authenticate(username=request.user.email, password=password)
  353. auth_login(request, u)
  354. messages.success(request, "Your password has been set!")
  355. return redirect("hc-profile")
  356. return render(request, "accounts/set_password.html", {})
  357. @login_required
  358. def change_email(request, token):
  359. if not request.profile.check_token(token, "change-email"):
  360. return HttpResponseBadRequest()
  361. if request.method == "POST":
  362. form = forms.ChangeEmailForm(request.POST)
  363. if form.is_valid():
  364. request.user.email = form.cleaned_data["email"]
  365. request.user.set_unusable_password()
  366. request.user.save()
  367. request.profile.token = ""
  368. request.profile.save()
  369. return redirect("hc-change-email-done")
  370. else:
  371. form = forms.ChangeEmailForm()
  372. return render(request, "accounts/change_email.html", {"form": form})
  373. def change_email_done(request):
  374. return render(request, "accounts/change_email_done.html")
  375. @csrf_exempt
  376. def unsubscribe_reports(request, signed_username):
  377. # Some email servers open links in emails to check for malicious content.
  378. # To work around this, for GET requests we serve a confirmation form.
  379. # If the signature is more than 5 minutes old, we also include JS code to
  380. # auto-submit the form.
  381. ctx = {}
  382. signer = signing.TimestampSigner(salt="reports")
  383. # First, check the signature without looking at the timestamp:
  384. try:
  385. username = signer.unsign(signed_username)
  386. except signing.BadSignature:
  387. return render(request, "bad_link.html")
  388. # Check if timestamp is older than 5 minutes:
  389. try:
  390. username = signer.unsign(signed_username, max_age=300)
  391. except signing.SignatureExpired:
  392. ctx["autosubmit"] = True
  393. if request.method != "POST":
  394. return render(request, "accounts/unsubscribe_submit.html", ctx)
  395. user = User.objects.get(username=username)
  396. profile = Profile.objects.for_user(user)
  397. profile.reports_allowed = False
  398. profile.next_report_date = None
  399. profile.nag_period = td()
  400. profile.next_nag_date = None
  401. profile.save()
  402. return render(request, "accounts/unsubscribed.html")
  403. @require_POST
  404. @login_required
  405. def close(request):
  406. user = request.user
  407. # Cancel their subscription:
  408. sub = Subscription.objects.filter(user=user).first()
  409. if sub:
  410. sub.cancel()
  411. user.delete()
  412. # Deleting user also deletes its profile, checks, channels etc.
  413. request.session.flush()
  414. return redirect("hc-index")
  415. @require_POST
  416. @login_required
  417. def remove_project(request, code):
  418. project = get_object_or_404(Project, code=code, owner=request.user)
  419. project.delete()
  420. return redirect("hc-index")