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.

297 lines
9.3 KiB

10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 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
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
  1. import uuid
  2. import re
  3. from django.contrib import messages
  4. from django.contrib.auth import login as auth_login
  5. from django.contrib.auth import logout as auth_logout
  6. from django.contrib.auth import authenticate
  7. from django.contrib.auth.decorators import login_required
  8. from django.contrib.auth.hashers import check_password
  9. from django.contrib.auth.models import User
  10. from django.core import signing
  11. from django.http import HttpResponseForbidden, HttpResponseBadRequest
  12. from django.shortcuts import redirect, render
  13. from hc.accounts.forms import (EmailPasswordForm, InviteTeamMemberForm,
  14. RemoveTeamMemberForm, ReportSettingsForm,
  15. SetPasswordForm, TeamNameForm)
  16. from hc.accounts.models import Profile, Member
  17. from hc.api.models import Channel, Check
  18. from hc.lib.badges import get_badge_url
  19. def _make_user(email):
  20. username = str(uuid.uuid4())[:30]
  21. user = User(username=username, email=email)
  22. user.set_unusable_password()
  23. user.save()
  24. profile = Profile(user=user)
  25. profile.save()
  26. channel = Channel()
  27. channel.user = user
  28. channel.kind = "email"
  29. channel.value = email
  30. channel.email_verified = True
  31. channel.save()
  32. return user
  33. def _associate_demo_check(request, user):
  34. if "welcome_code" not in request.session:
  35. return
  36. try:
  37. check = Check.objects.get(code=request.session["welcome_code"])
  38. except Check.DoesNotExist:
  39. return
  40. # Only associate demo check if it doesn't have an owner already.
  41. if check.user:
  42. return
  43. check.user = user
  44. check.save()
  45. check.assign_all_channels()
  46. del request.session["welcome_code"]
  47. def login(request):
  48. bad_credentials = False
  49. if request.method == 'POST':
  50. form = EmailPasswordForm(request.POST)
  51. if form.is_valid():
  52. email = form.cleaned_data["email"]
  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. else:
  61. try:
  62. user = User.objects.get(email=email)
  63. except User.DoesNotExist:
  64. user = _make_user(email)
  65. _associate_demo_check(request, user)
  66. user.profile.send_instant_login_link()
  67. return redirect("hc-login-link-sent")
  68. else:
  69. form = EmailPasswordForm()
  70. bad_link = request.session.pop("bad_link", None)
  71. ctx = {
  72. "form": form,
  73. "bad_credentials": bad_credentials,
  74. "bad_link": bad_link
  75. }
  76. return render(request, "accounts/login.html", ctx)
  77. def logout(request):
  78. auth_logout(request)
  79. return redirect("hc-index")
  80. def login_link_sent(request):
  81. return render(request, "accounts/login_link_sent.html")
  82. def set_password_link_sent(request):
  83. return render(request, "accounts/set_password_link_sent.html")
  84. def check_token(request, username, token):
  85. if request.user.is_authenticated and request.user.username == username:
  86. # User is already logged in
  87. return redirect("hc-checks")
  88. # Some email servers open links in emails to check for malicious content.
  89. # To work around this, we sign user in if the method is POST.
  90. #
  91. # If the method is GET, we instead serve a HTML form and a piece
  92. # of Javascript to automatically submit it.
  93. if request.method == "POST":
  94. user = authenticate(username=username, token=token)
  95. if user is not None and user.is_active:
  96. # This should get rid of "welcome_code" in session
  97. request.session.flush()
  98. user.profile.token = ""
  99. user.profile.save()
  100. auth_login(request, user)
  101. return redirect("hc-checks")
  102. request.session["bad_link"] = True
  103. return redirect("hc-login")
  104. return render(request, "accounts/check_token_submit.html")
  105. @login_required
  106. def profile(request):
  107. profile = request.user.profile
  108. # Switch user back to its default team
  109. if profile.current_team_id != profile.id:
  110. request.team = profile
  111. profile.current_team_id = profile.id
  112. profile.save()
  113. show_api_key = False
  114. if request.method == "POST":
  115. if "set_password" in request.POST:
  116. profile.send_set_password_link()
  117. return redirect("hc-set-password-link-sent")
  118. elif "create_api_key" in request.POST:
  119. profile.set_api_key()
  120. show_api_key = True
  121. messages.success(request, "The API key has been created!")
  122. elif "revoke_api_key" in request.POST:
  123. profile.api_key = ""
  124. profile.save()
  125. messages.info(request, "The API key has been revoked!")
  126. elif "show_api_key" in request.POST:
  127. show_api_key = True
  128. elif "update_reports_allowed" in request.POST:
  129. form = ReportSettingsForm(request.POST)
  130. if form.is_valid():
  131. profile.reports_allowed = form.cleaned_data["reports_allowed"]
  132. profile.save()
  133. messages.success(request, "Your settings have been updated!")
  134. elif "invite_team_member" in request.POST:
  135. if not profile.team_access_allowed:
  136. return HttpResponseForbidden()
  137. form = InviteTeamMemberForm(request.POST)
  138. if form.is_valid():
  139. email = form.cleaned_data["email"]
  140. try:
  141. user = User.objects.get(email=email)
  142. except User.DoesNotExist:
  143. user = _make_user(email)
  144. profile.invite(user)
  145. messages.success(request, "Invitation to %s sent!" % email)
  146. elif "remove_team_member" in request.POST:
  147. form = RemoveTeamMemberForm(request.POST)
  148. if form.is_valid():
  149. email = form.cleaned_data["email"]
  150. farewell_user = User.objects.get(email=email)
  151. farewell_user.profile.current_team = None
  152. farewell_user.profile.save()
  153. Member.objects.filter(team=profile,
  154. user=farewell_user).delete()
  155. messages.info(request, "%s removed from team!" % email)
  156. elif "set_team_name" in request.POST:
  157. if not profile.team_access_allowed:
  158. return HttpResponseForbidden()
  159. form = TeamNameForm(request.POST)
  160. if form.is_valid():
  161. profile.team_name = form.cleaned_data["team_name"]
  162. profile.save()
  163. messages.success(request, "Team Name updated!")
  164. tags = set()
  165. for check in Check.objects.filter(user=request.team.user):
  166. tags.update(check.tags_list())
  167. username = request.team.user.username
  168. badge_urls = []
  169. for tag in sorted(tags, key=lambda s: s.lower()):
  170. if not re.match("^[\w-]+$", tag):
  171. continue
  172. badge_urls.append(get_badge_url(username, tag))
  173. ctx = {
  174. "page": "profile",
  175. "badge_urls": badge_urls,
  176. "profile": profile,
  177. "show_api_key": show_api_key
  178. }
  179. return render(request, "accounts/profile.html", ctx)
  180. @login_required
  181. def set_password(request, token):
  182. profile = request.user.profile
  183. if not check_password(token, profile.token):
  184. return HttpResponseBadRequest()
  185. if request.method == "POST":
  186. form = SetPasswordForm(request.POST)
  187. if form.is_valid():
  188. password = form.cleaned_data["password"]
  189. request.user.set_password(password)
  190. request.user.save()
  191. profile.token = ""
  192. profile.save()
  193. # Setting a password logs the user out, so here we
  194. # log them back in.
  195. u = authenticate(username=request.user.email, password=password)
  196. auth_login(request, u)
  197. messages.success(request, "Your password has been set!")
  198. return redirect("hc-profile")
  199. return render(request, "accounts/set_password.html", {})
  200. def unsubscribe_reports(request, username):
  201. try:
  202. signing.Signer().unsign(request.GET.get("token"))
  203. except signing.BadSignature:
  204. return HttpResponseBadRequest()
  205. user = User.objects.get(username=username)
  206. user.profile.reports_allowed = False
  207. user.profile.save()
  208. return render(request, "accounts/unsubscribed.html")
  209. @login_required
  210. def switch_team(request, target_username):
  211. try:
  212. other_user = User.objects.get(username=target_username)
  213. except User.DoesNotExist:
  214. return HttpResponseForbidden()
  215. # The rules:
  216. # Superuser can switch to any team.
  217. access_ok = request.user.is_superuser
  218. # Users can switch to teams they are members of.
  219. if not access_ok and other_user.id == request.user.id:
  220. access_ok = True
  221. # Users can switch to their own teams.
  222. if not access_ok:
  223. for membership in request.user.member_set.all():
  224. if membership.team.user.id == other_user.id:
  225. access_ok = True
  226. break
  227. if not access_ok:
  228. return HttpResponseForbidden()
  229. request.user.profile.current_team = other_user.profile
  230. request.user.profile.save()
  231. return redirect("hc-checks")