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.

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