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.

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