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.

417 lines
13 KiB

10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
8 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
8 years ago
8 years ago
8 years ago
8 years ago
  1. from datetime import timedelta as td
  2. import uuid
  3. import re
  4. from django.conf import settings
  5. from django.contrib import messages
  6. from django.contrib.auth import login as auth_login
  7. from django.contrib.auth import logout as auth_logout
  8. from django.contrib.auth import authenticate
  9. from django.contrib.auth.decorators import login_required
  10. from django.contrib.auth.models import User
  11. from django.core import signing
  12. from django.http import HttpResponseForbidden, HttpResponseBadRequest
  13. from django.shortcuts import redirect, render
  14. from django.utils.timezone import now
  15. from django.views.decorators.csrf import csrf_exempt
  16. from django.views.decorators.http import require_POST
  17. from hc.accounts.forms import (ChangeEmailForm, EmailPasswordForm,
  18. InviteTeamMemberForm, RemoveTeamMemberForm,
  19. ReportSettingsForm, SetPasswordForm,
  20. TeamNameForm, AvailableEmailForm,
  21. ExistingEmailForm)
  22. from hc.accounts.models import Profile, Member
  23. from hc.api.models import Channel, Check
  24. from hc.lib.badges import get_badge_url
  25. from hc.payments.models import Subscription
  26. def _make_user(email):
  27. username = str(uuid.uuid4())[:30]
  28. user = User(username=username, email=email)
  29. user.set_unusable_password()
  30. user.save()
  31. # Ensure a profile gets created
  32. Profile.objects.for_user(user)
  33. check = Check(user=user)
  34. check.name = "My First Check"
  35. check.save()
  36. channel = Channel(user=user)
  37. channel.kind = "email"
  38. channel.value = email
  39. channel.email_verified = True
  40. channel.save()
  41. channel.checks.add(check)
  42. return user
  43. def _ensure_own_team(request):
  44. """ Make sure user is switched to their own team. """
  45. if request.team != request.profile:
  46. request.team = request.profile
  47. request.profile.current_team = request.profile
  48. request.profile.save()
  49. def login(request):
  50. form = EmailPasswordForm()
  51. magic_form = ExistingEmailForm()
  52. if request.method == 'POST':
  53. if request.POST.get("action") == "login":
  54. form = EmailPasswordForm(request.POST)
  55. if form.is_valid():
  56. auth_login(request, form.user)
  57. return redirect("hc-checks")
  58. else:
  59. magic_form = ExistingEmailForm(request.POST)
  60. if magic_form.is_valid():
  61. profile = Profile.objects.for_user(magic_form.user)
  62. profile.send_instant_login_link()
  63. return redirect("hc-login-link-sent")
  64. bad_link = request.session.pop("bad_link", None)
  65. ctx = {
  66. "page": "login",
  67. "form": form,
  68. "magic_form": magic_form,
  69. "bad_link": bad_link
  70. }
  71. return render(request, "accounts/login.html", ctx)
  72. def logout(request):
  73. auth_logout(request)
  74. return redirect("hc-index")
  75. @require_POST
  76. def signup(request):
  77. if not settings.REGISTRATION_OPEN:
  78. return HttpResponseForbidden()
  79. ctx = {}
  80. form = AvailableEmailForm(request.POST)
  81. if form.is_valid():
  82. email = form.cleaned_data["identity"]
  83. user = _make_user(email)
  84. profile = Profile.objects.for_user(user)
  85. profile.send_instant_login_link()
  86. ctx["created"] = True
  87. else:
  88. ctx = {"form": form}
  89. return render(request, "accounts/signup_result.html", ctx)
  90. def login_link_sent(request):
  91. return render(request, "accounts/login_link_sent.html")
  92. def link_sent(request):
  93. return render(request, "accounts/link_sent.html")
  94. def check_token(request, username, token):
  95. if request.user.is_authenticated and request.user.username == username:
  96. # User is already logged in
  97. return redirect("hc-checks")
  98. # Some email servers open links in emails to check for malicious content.
  99. # To work around this, we sign user in if the method is POST.
  100. #
  101. # If the method is GET, we instead serve a HTML form and a piece
  102. # of Javascript to automatically submit it.
  103. if request.method == "POST":
  104. user = authenticate(username=username, token=token)
  105. if user is not None and user.is_active:
  106. user.profile.token = ""
  107. user.profile.save()
  108. auth_login(request, user)
  109. return redirect("hc-checks")
  110. request.session["bad_link"] = True
  111. return redirect("hc-login")
  112. return render(request, "accounts/check_token_submit.html")
  113. @login_required
  114. def profile(request):
  115. _ensure_own_team(request)
  116. profile = request.profile
  117. ctx = {
  118. "page": "profile",
  119. "profile": profile,
  120. "show_api_keys": False,
  121. "api_status": "default",
  122. "team_status": "default"
  123. }
  124. if request.method == "POST":
  125. if "change_email" in request.POST:
  126. profile.send_change_email_link()
  127. return redirect("hc-link-sent")
  128. elif "set_password" in request.POST:
  129. profile.send_set_password_link()
  130. return redirect("hc-link-sent")
  131. elif "create_api_keys" in request.POST:
  132. profile.set_api_keys()
  133. ctx["show_api_keys"] = True
  134. ctx["api_keys_created"] = True
  135. ctx["api_status"] = "success"
  136. elif "revoke_api_keys" in request.POST:
  137. profile.api_key_id = ""
  138. profile.api_key = ""
  139. profile.api_key_readonly = ""
  140. profile.save()
  141. ctx["api_keys_revoked"] = True
  142. ctx["api_status"] = "info"
  143. elif "show_api_keys" in request.POST:
  144. ctx["show_api_keys"] = True
  145. elif "invite_team_member" in request.POST:
  146. if not profile.can_invite():
  147. return HttpResponseForbidden()
  148. form = InviteTeamMemberForm(request.POST)
  149. if form.is_valid():
  150. email = form.cleaned_data["email"]
  151. try:
  152. user = User.objects.get(email=email)
  153. except User.DoesNotExist:
  154. user = _make_user(email)
  155. profile.invite(user)
  156. ctx["team_member_invited"] = email
  157. ctx["team_status"] = "success"
  158. elif "remove_team_member" in request.POST:
  159. form = RemoveTeamMemberForm(request.POST)
  160. if form.is_valid():
  161. email = form.cleaned_data["email"]
  162. farewell_user = User.objects.get(email=email)
  163. farewell_user.profile.current_team = None
  164. farewell_user.profile.save()
  165. Member.objects.filter(team=profile,
  166. user=farewell_user).delete()
  167. ctx["team_member_removed"] = email
  168. ctx["team_status"] = "info"
  169. elif "set_team_name" in request.POST:
  170. form = TeamNameForm(request.POST)
  171. if form.is_valid():
  172. profile.team_name = form.cleaned_data["team_name"]
  173. profile.save()
  174. ctx["team_name_updated"] = True
  175. ctx["team_status"] = "success"
  176. return render(request, "accounts/profile.html", ctx)
  177. @login_required
  178. def notifications(request):
  179. _ensure_own_team(request)
  180. profile = request.profile
  181. ctx = {
  182. "status": "default",
  183. "page": "profile",
  184. "profile": profile
  185. }
  186. if request.method == "POST":
  187. form = ReportSettingsForm(request.POST)
  188. if form.is_valid():
  189. if profile.reports_allowed != form.cleaned_data["reports_allowed"]:
  190. profile.reports_allowed = form.cleaned_data["reports_allowed"]
  191. if profile.reports_allowed:
  192. profile.next_report_date = now() + td(days=30)
  193. else:
  194. profile.next_report_date = None
  195. if profile.nag_period != form.cleaned_data["nag_period"]:
  196. # Set the new nag period
  197. profile.nag_period = form.cleaned_data["nag_period"]
  198. # and schedule next_nag_date:
  199. if profile.nag_period:
  200. profile.next_nag_date = now() + profile.nag_period
  201. else:
  202. profile.next_nag_date = None
  203. profile.save()
  204. ctx["status"] = "info"
  205. return render(request, "accounts/notifications.html", ctx)
  206. @login_required
  207. def badges(request):
  208. _ensure_own_team(request)
  209. teams = [request.profile]
  210. for membership in request.user.memberships.all():
  211. teams.append(membership.team)
  212. badge_sets = []
  213. for team in teams:
  214. tags = set()
  215. for check in Check.objects.filter(user=team.user):
  216. tags.update(check.tags_list())
  217. sorted_tags = sorted(tags, key=lambda s: s.lower())
  218. sorted_tags.append("*") # For the "overall status" badge
  219. urls = []
  220. username = team.user.username
  221. for tag in sorted_tags:
  222. if not re.match("^[\w-]+$", tag) and tag != "*":
  223. continue
  224. urls.append({
  225. "svg": get_badge_url(username, tag),
  226. "json": get_badge_url(username, tag, format="json"),
  227. })
  228. badge_sets.append({"team": team, "urls": urls})
  229. ctx = {
  230. "page": "profile",
  231. "badges": badge_sets
  232. }
  233. return render(request, "accounts/badges.html", ctx)
  234. @login_required
  235. def set_password(request, token):
  236. if not request.profile.check_token(token, "set-password"):
  237. return HttpResponseBadRequest()
  238. if request.method == "POST":
  239. form = SetPasswordForm(request.POST)
  240. if form.is_valid():
  241. password = form.cleaned_data["password"]
  242. request.user.set_password(password)
  243. request.user.save()
  244. request.profile.token = ""
  245. request.profile.save()
  246. # Setting a password logs the user out, so here we
  247. # log them back in.
  248. u = authenticate(username=request.user.email, password=password)
  249. auth_login(request, u)
  250. messages.success(request, "Your password has been set!")
  251. return redirect("hc-profile")
  252. return render(request, "accounts/set_password.html", {})
  253. @login_required
  254. def change_email(request, token):
  255. if not request.profile.check_token(token, "change-email"):
  256. return HttpResponseBadRequest()
  257. if request.method == "POST":
  258. form = ChangeEmailForm(request.POST)
  259. if form.is_valid():
  260. request.user.email = form.cleaned_data["email"]
  261. request.user.set_unusable_password()
  262. request.user.save()
  263. request.profile.token = ""
  264. request.profile.save()
  265. return redirect("hc-change-email-done")
  266. else:
  267. form = ChangeEmailForm()
  268. return render(request, "accounts/change_email.html", {"form": form})
  269. def change_email_done(request):
  270. return render(request, "accounts/change_email_done.html")
  271. @csrf_exempt
  272. def unsubscribe_reports(request, username):
  273. signer = signing.TimestampSigner(salt="reports")
  274. try:
  275. username = signer.unsign(username)
  276. except signing.BadSignature:
  277. return render(request, "bad_link.html")
  278. # Some email servers open links in emails to check for malicious content.
  279. # To work around this, we serve a form that auto-submits with JS.
  280. if "ask" in request.GET and request.method != "POST":
  281. return render(request, "accounts/unsubscribe_submit.html")
  282. user = User.objects.get(username=username)
  283. profile = Profile.objects.for_user(user)
  284. profile.reports_allowed = False
  285. profile.next_report_date = None
  286. profile.nag_period = td()
  287. profile.next_nag_date = None
  288. profile.save()
  289. return render(request, "accounts/unsubscribed.html")
  290. @login_required
  291. def switch_team(request, target_username):
  292. try:
  293. target_team = Profile.objects.get(user__username=target_username)
  294. except Profile.DoesNotExist:
  295. return HttpResponseForbidden()
  296. # The rules:
  297. # Superuser can switch to any team.
  298. access_ok = request.user.is_superuser
  299. # Users can switch to their own teams.
  300. if not access_ok and target_team == request.profile:
  301. access_ok = True
  302. # Users can switch to teams they are members of.
  303. if not access_ok:
  304. access_ok = request.user.memberships.filter(team=target_team).exists()
  305. if not access_ok:
  306. return HttpResponseForbidden()
  307. request.profile.current_team = target_team
  308. request.profile.save()
  309. return redirect("hc-checks")
  310. @require_POST
  311. @login_required
  312. def close(request):
  313. user = request.user
  314. # Subscription needs to be canceled before it is deleted:
  315. sub = Subscription.objects.filter(user=user).first()
  316. if sub:
  317. sub.cancel()
  318. user.delete()
  319. # Deleting user also deletes its profile, checks, channels etc.
  320. request.session.flush()
  321. return redirect("hc-index")