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.

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