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.

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