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.

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