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.

493 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-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 = Profile.objects.for_user(user)
  71. profile.current_project = project
  72. profile.save()
  73. return user
  74. def _redirect_after_login(request):
  75. """ Redirect to the URL indicated in ?next= query parameter. """
  76. redirect_url = request.GET.get("next")
  77. if _is_whitelisted(redirect_url):
  78. return redirect(redirect_url)
  79. if request.user.project_set.count() == 1:
  80. project = request.user.project_set.first()
  81. return redirect("hc-checks", project.code)
  82. return redirect("hc-index")
  83. def login(request):
  84. form = PasswordLoginForm()
  85. magic_form = EmailLoginForm()
  86. if request.method == "POST":
  87. if request.POST.get("action") == "login":
  88. form = PasswordLoginForm(request.POST)
  89. if form.is_valid():
  90. auth_login(request, form.user)
  91. return _redirect_after_login(request)
  92. else:
  93. magic_form = EmailLoginForm(request.POST)
  94. if magic_form.is_valid():
  95. redirect_url = request.GET.get("next")
  96. if not _is_whitelisted(redirect_url):
  97. redirect_url = None
  98. profile = Profile.objects.for_user(magic_form.user)
  99. profile.send_instant_login_link(redirect_url=redirect_url)
  100. response = redirect("hc-login-link-sent")
  101. # check_token_submit looks for this cookie to decide if
  102. # it needs to do the extra POST step.
  103. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  104. return response
  105. bad_link = request.session.pop("bad_link", None)
  106. ctx = {
  107. "page": "login",
  108. "form": form,
  109. "magic_form": magic_form,
  110. "bad_link": bad_link,
  111. "registration_open": settings.REGISTRATION_OPEN,
  112. }
  113. return render(request, "accounts/login.html", ctx)
  114. def logout(request):
  115. auth_logout(request)
  116. return redirect("hc-index")
  117. @require_POST
  118. @csrf_exempt
  119. def signup(request):
  120. if not settings.REGISTRATION_OPEN:
  121. return HttpResponseForbidden()
  122. ctx = {}
  123. form = AvailableEmailForm(request.POST)
  124. if form.is_valid():
  125. email = form.cleaned_data["identity"]
  126. user = _make_user(email)
  127. profile = Profile.objects.for_user(user)
  128. profile.send_instant_login_link()
  129. ctx["created"] = True
  130. else:
  131. ctx = {"form": form}
  132. response = render(request, "accounts/signup_result.html", ctx)
  133. if ctx.get("created"):
  134. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  135. return response
  136. def login_link_sent(request):
  137. return render(request, "accounts/login_link_sent.html")
  138. def link_sent(request):
  139. return render(request, "accounts/link_sent.html")
  140. def check_token(request, username, token):
  141. if request.user.is_authenticated and request.user.username == username:
  142. # User is already logged in
  143. return _redirect_after_login(request)
  144. # Some email servers open links in emails to check for malicious content.
  145. # To work around this, we sign user in if the method is POST
  146. # *or* if the browser presents a cookie we had set when sending the login link.
  147. #
  148. # If the method is GET, we instead serve a HTML form and a piece
  149. # of Javascript to automatically submit it.
  150. if request.method == "POST" or "auto-login" in request.COOKIES:
  151. user = authenticate(username=username, token=token)
  152. if user is not None and user.is_active:
  153. user.profile.token = ""
  154. user.profile.save()
  155. auth_login(request, user)
  156. return _redirect_after_login(request)
  157. request.session["bad_link"] = True
  158. return redirect("hc-login")
  159. return render(request, "accounts/check_token_submit.html")
  160. @login_required
  161. def profile(request):
  162. profile = request.profile
  163. ctx = {"page": "profile", "profile": profile, "my_projects_status": "default"}
  164. if request.method == "POST":
  165. if "change_email" in request.POST:
  166. profile.send_change_email_link()
  167. return redirect("hc-link-sent")
  168. elif "set_password" in request.POST:
  169. profile.send_set_password_link()
  170. return redirect("hc-link-sent")
  171. elif "leave_project" in request.POST:
  172. code = request.POST["code"]
  173. try:
  174. project = Project.objects.get(code=code, member__user=request.user)
  175. except Project.DoesNotExist:
  176. return HttpResponseBadRequest()
  177. if profile.current_project == project:
  178. profile.current_project = None
  179. profile.save()
  180. Member.objects.filter(project=project, user=request.user).delete()
  181. ctx["left_project"] = project
  182. ctx["my_projects_status"] = "info"
  183. # Retrieve projects right before rendering the template--
  184. # The list of the projects might have *just* changed
  185. ctx["projects"] = list(profile.projects())
  186. return render(request, "accounts/profile.html", ctx)
  187. @login_required
  188. @require_POST
  189. def add_project(request):
  190. form = ProjectNameForm(request.POST)
  191. if not form.is_valid():
  192. return HttpResponseBadRequest()
  193. project = Project(owner=request.user)
  194. project.code = project.badge_key = str(uuid.uuid4())
  195. project.name = form.cleaned_data["name"]
  196. project.save()
  197. return redirect("hc-checks", project.code)
  198. @login_required
  199. def project(request, code):
  200. if request.user.is_superuser:
  201. q = Project.objects
  202. else:
  203. q = request.profile.projects()
  204. try:
  205. project = q.get(code=code)
  206. except Project.DoesNotExist:
  207. return HttpResponseNotFound()
  208. is_owner = project.owner_id == request.user.id
  209. ctx = {
  210. "page": "project",
  211. "project": project,
  212. "is_owner": is_owner,
  213. "show_api_keys": "show_api_keys" in request.GET,
  214. "project_name_status": "default",
  215. "api_status": "default",
  216. "team_status": "default",
  217. }
  218. if request.method == "POST":
  219. if "create_api_keys" in request.POST:
  220. project.set_api_keys()
  221. project.save()
  222. ctx["show_api_keys"] = True
  223. ctx["api_keys_created"] = True
  224. ctx["api_status"] = "success"
  225. elif "revoke_api_keys" in request.POST:
  226. project.api_key = ""
  227. project.api_key_readonly = ""
  228. project.save()
  229. ctx["api_keys_revoked"] = True
  230. ctx["api_status"] = "info"
  231. elif "show_api_keys" in request.POST:
  232. ctx["show_api_keys"] = True
  233. elif "invite_team_member" in request.POST:
  234. if not is_owner or not project.can_invite():
  235. return HttpResponseForbidden()
  236. form = InviteTeamMemberForm(request.POST)
  237. if form.is_valid():
  238. if not TokenBucket.authorize_invite(request.user):
  239. return render(request, "try_later.html")
  240. email = form.cleaned_data["email"]
  241. try:
  242. user = User.objects.get(email=email)
  243. except User.DoesNotExist:
  244. user = _make_user(email, with_project=False)
  245. project.invite(user)
  246. ctx["team_member_invited"] = email
  247. ctx["team_status"] = "success"
  248. elif "remove_team_member" in request.POST:
  249. if not is_owner:
  250. return HttpResponseForbidden()
  251. form = RemoveTeamMemberForm(request.POST)
  252. if form.is_valid():
  253. q = User.objects
  254. q = q.filter(email=form.cleaned_data["email"])
  255. q = q.filter(memberships__project=project)
  256. farewell_user = q.first()
  257. if farewell_user is None:
  258. return HttpResponseBadRequest()
  259. farewell_user.profile.current_project = None
  260. farewell_user.profile.save()
  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. if request.profile.current_project == project:
  270. request.profile.current_project.name = project.name
  271. ctx["project_name_updated"] = True
  272. ctx["project_name_status"] = "success"
  273. # Count members right before rendering the template, in case
  274. # we just invited or removed someone
  275. ctx["num_members"] = project.member_set.count()
  276. return render(request, "accounts/project.html", ctx)
  277. @login_required
  278. def notifications(request):
  279. profile = request.profile
  280. ctx = {"status": "default", "page": "profile", "profile": profile}
  281. if request.method == "POST":
  282. form = ReportSettingsForm(request.POST)
  283. if form.is_valid():
  284. if profile.reports_allowed != form.cleaned_data["reports_allowed"]:
  285. profile.reports_allowed = form.cleaned_data["reports_allowed"]
  286. if profile.reports_allowed:
  287. profile.next_report_date = choose_next_report_date()
  288. else:
  289. profile.next_report_date = None
  290. if profile.nag_period != form.cleaned_data["nag_period"]:
  291. # Set the new nag period
  292. profile.nag_period = form.cleaned_data["nag_period"]
  293. # and schedule next_nag_date:
  294. if profile.nag_period:
  295. profile.next_nag_date = now() + profile.nag_period
  296. else:
  297. profile.next_nag_date = None
  298. profile.save()
  299. ctx["status"] = "info"
  300. return render(request, "accounts/notifications.html", ctx)
  301. @login_required
  302. def set_password(request, token):
  303. if not request.profile.check_token(token, "set-password"):
  304. return HttpResponseBadRequest()
  305. if request.method == "POST":
  306. form = SetPasswordForm(request.POST)
  307. if form.is_valid():
  308. password = form.cleaned_data["password"]
  309. request.user.set_password(password)
  310. request.user.save()
  311. request.profile.token = ""
  312. request.profile.save()
  313. # Setting a password logs the user out, so here we
  314. # log them back in.
  315. u = authenticate(username=request.user.email, password=password)
  316. auth_login(request, u)
  317. messages.success(request, "Your password has been set!")
  318. return redirect("hc-profile")
  319. return render(request, "accounts/set_password.html", {})
  320. @login_required
  321. def change_email(request, token):
  322. if not request.profile.check_token(token, "change-email"):
  323. return HttpResponseBadRequest()
  324. if request.method == "POST":
  325. form = ChangeEmailForm(request.POST)
  326. if form.is_valid():
  327. request.user.email = form.cleaned_data["email"]
  328. request.user.set_unusable_password()
  329. request.user.save()
  330. request.profile.token = ""
  331. request.profile.save()
  332. return redirect("hc-change-email-done")
  333. else:
  334. form = ChangeEmailForm()
  335. return render(request, "accounts/change_email.html", {"form": form})
  336. def change_email_done(request):
  337. return render(request, "accounts/change_email_done.html")
  338. @csrf_exempt
  339. def unsubscribe_reports(request, signed_username):
  340. # Some email servers open links in emails to check for malicious content.
  341. # To work around this, for GET requests we serve a confirmation form.
  342. # If the signature is more than 5 minutes old, we also include JS code to
  343. # auto-submit the form.
  344. ctx = {}
  345. signer = signing.TimestampSigner(salt="reports")
  346. # First, check the signature without looking at the timestamp:
  347. try:
  348. username = signer.unsign(signed_username)
  349. except signing.BadSignature:
  350. return render(request, "bad_link.html")
  351. # Check if timestamp is older than 5 minutes:
  352. try:
  353. username = signer.unsign(signed_username, max_age=300)
  354. except signing.SignatureExpired:
  355. ctx["autosubmit"] = True
  356. if request.method != "POST":
  357. return render(request, "accounts/unsubscribe_submit.html", ctx)
  358. user = User.objects.get(username=username)
  359. profile = Profile.objects.for_user(user)
  360. profile.reports_allowed = False
  361. profile.next_report_date = None
  362. profile.nag_period = td()
  363. profile.next_nag_date = None
  364. profile.save()
  365. return render(request, "accounts/unsubscribed.html")
  366. @require_POST
  367. @login_required
  368. def close(request):
  369. user = request.user
  370. # Subscription needs to be canceled before it is deleted:
  371. sub = Subscription.objects.filter(user=user).first()
  372. if sub:
  373. sub.cancel(delete_customer=True)
  374. user.delete()
  375. # Deleting user also deletes its profile, checks, channels etc.
  376. request.session.flush()
  377. return redirect("hc-index")
  378. @require_POST
  379. @login_required
  380. def remove_project(request, code):
  381. project = get_object_or_404(Project, code=code, owner=request.user)
  382. project.delete()
  383. return redirect("hc-index")