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.

84 lines
2.4 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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. import uuid
  2. from django.conf import settings
  3. from django.contrib.auth import authenticate
  4. from django.contrib.auth import login as auth_login, logout as auth_logout
  5. from django.contrib.auth.models import User
  6. from django.core.mail import send_mail
  7. from django.core.urlresolvers import reverse
  8. from django.http import HttpResponseBadRequest
  9. from django.shortcuts import redirect, render
  10. from hc.accounts.forms import EmailForm
  11. from hc.api.models import Check
  12. def _make_user(email):
  13. username = str(uuid.uuid4())[:30]
  14. user = User(username=username, email=email)
  15. user.save()
  16. return user
  17. def _associate_demo_check(request, user):
  18. if "welcome_code" in request.session:
  19. check = Check.objects.get(code=request.session["welcome_code"])
  20. check.user = user
  21. check.save()
  22. def login(request):
  23. if request.method == 'POST':
  24. form = EmailForm(request.POST)
  25. if form.is_valid():
  26. email = form.cleaned_data["email"]
  27. try:
  28. user = User.objects.get(email=email)
  29. except User.DoesNotExist:
  30. user = _make_user(email)
  31. _associate_demo_check(request, user)
  32. # We don't want to reset passwords of staff users :-)
  33. if user.is_staff:
  34. return HttpResponseBadRequest()
  35. token = str(uuid.uuid4())
  36. user.set_password(token)
  37. user.save()
  38. login_link = reverse("hc-check-token", args=[user.username, token])
  39. login_link = settings.SITE_ROOT + login_link
  40. body = "login link: %s" % login_link
  41. send_mail('Log In', body, '[email protected]', [email],
  42. fail_silently=False)
  43. return redirect("hc-login-link-sent")
  44. else:
  45. form = EmailForm()
  46. ctx = {"form": form}
  47. return render(request, "accounts/login.html", ctx)
  48. def logout(request):
  49. auth_logout(request)
  50. return redirect("hc-index")
  51. def login_link_sent(request):
  52. return render(request, "accounts/login_link_sent.html")
  53. def check_token(request, username, token):
  54. user = authenticate(username=username, password=token)
  55. if user is not None:
  56. if user.is_active:
  57. user.set_unusable_password()
  58. user.save()
  59. auth_login(request, user)
  60. return redirect("hc-checks")
  61. return render(request, "bad_link.html")