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.

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