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.

893 lines
28 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
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. import base64
  2. from datetime import timedelta as td
  3. from secrets import token_bytes
  4. from urllib.parse import urlparse
  5. import time
  6. import uuid
  7. from django.db import transaction
  8. from django.conf import settings
  9. from django.contrib import messages
  10. from django.contrib.auth import login as auth_login
  11. from django.contrib.auth import logout as auth_logout
  12. from django.contrib.auth import authenticate, update_session_auth_hash
  13. from django.contrib.auth.decorators import login_required
  14. from django.contrib.auth.models import User
  15. from django.core import signing
  16. from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest
  17. from django.shortcuts import get_object_or_404, redirect, render
  18. from django.utils.timezone import now
  19. from django.urls import resolve, reverse, Resolver404
  20. from django.views.decorators.csrf import csrf_exempt
  21. from django.views.decorators.http import require_POST
  22. from fido2.ctap2 import AttestationObject, AuthenticatorData
  23. from fido2.client import ClientData
  24. from fido2.server import Fido2Server
  25. from fido2.webauthn import PublicKeyCredentialRpEntity
  26. from fido2 import cbor
  27. from hc.accounts import forms
  28. from hc.accounts.decorators import require_sudo_mode
  29. from hc.accounts.models import Credential, Profile, Project, Member
  30. from hc.api.models import Channel, Check, TokenBucket
  31. from hc.payments.models import Subscription
  32. import pyotp
  33. import segno
  34. POST_LOGIN_ROUTES = (
  35. "hc-checks",
  36. "hc-details",
  37. "hc-log",
  38. "hc-channels",
  39. "hc-add-slack",
  40. "hc-add-pushover",
  41. "hc-add-telegram",
  42. "hc-project-settings",
  43. "hc-uncloak",
  44. )
  45. FIDO2_SERVER = Fido2Server(PublicKeyCredentialRpEntity(settings.RP_ID, "healthchecks"))
  46. def _allow_redirect(redirect_url):
  47. if not redirect_url:
  48. return False
  49. parsed = urlparse(redirect_url)
  50. try:
  51. match = resolve(parsed.path)
  52. except Resolver404:
  53. return False
  54. return match.url_name in POST_LOGIN_ROUTES
  55. def _make_user(email, tz=None, with_project=True):
  56. username = str(uuid.uuid4())[:30]
  57. user = User(username=username, email=email)
  58. user.set_unusable_password()
  59. user.save()
  60. project = None
  61. if with_project:
  62. project = Project(owner=user)
  63. project.badge_key = user.username
  64. project.save()
  65. check = Check(project=project)
  66. check.name = "My First Check"
  67. check.save()
  68. channel = Channel(project=project)
  69. channel.kind = "email"
  70. channel.value = email
  71. channel.email_verified = True
  72. channel.save()
  73. channel.checks.add(check)
  74. # Ensure a profile gets created
  75. profile = Profile.objects.for_user(user)
  76. if tz:
  77. profile.tz = tz
  78. profile.save()
  79. return user
  80. def _redirect_after_login(request):
  81. """ Redirect to the URL indicated in ?next= query parameter. """
  82. redirect_url = request.GET.get("next")
  83. if _allow_redirect(redirect_url):
  84. return redirect(redirect_url)
  85. if request.user.project_set.count() == 1:
  86. project = request.user.project_set.first()
  87. return redirect("hc-checks", project.code)
  88. return redirect("hc-index")
  89. def _check_2fa(request, user):
  90. have_keys = user.credentials.exists()
  91. if have_keys or user.profile.totp:
  92. # We have verified user's password or token, and now must
  93. # verify their security key. We store the following in user's session:
  94. # - user.id, to look up the user in the login_webauthn view
  95. # - user.email, to make sure email was not changed between the auth steps
  96. # - timestamp, to limit the max time between the auth steps
  97. request.session["2fa_user"] = [user.id, user.email, int(time.time())]
  98. if have_keys:
  99. path = reverse("hc-login-webauthn")
  100. else:
  101. path = reverse("hc-login-totp")
  102. redirect_url = request.GET.get("next")
  103. if _allow_redirect(redirect_url):
  104. path += "?next=%s" % redirect_url
  105. return redirect(path)
  106. auth_login(request, user)
  107. return _redirect_after_login(request)
  108. def login(request):
  109. form = forms.PasswordLoginForm()
  110. magic_form = forms.EmailLoginForm()
  111. if request.method == "POST":
  112. if request.POST.get("action") == "login":
  113. form = forms.PasswordLoginForm(request.POST)
  114. if form.is_valid():
  115. return _check_2fa(request, form.user)
  116. else:
  117. magic_form = forms.EmailLoginForm(request.POST)
  118. if magic_form.is_valid():
  119. redirect_url = request.GET.get("next")
  120. if not _allow_redirect(redirect_url):
  121. redirect_url = None
  122. profile = Profile.objects.for_user(magic_form.user)
  123. profile.send_instant_login_link(redirect_url=redirect_url)
  124. response = redirect("hc-login-link-sent")
  125. # check_token_submit looks for this cookie to decide if
  126. # it needs to do the extra POST step.
  127. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  128. return response
  129. bad_link = request.session.pop("bad_link", None)
  130. ctx = {
  131. "page": "login",
  132. "form": form,
  133. "magic_form": magic_form,
  134. "bad_link": bad_link,
  135. "registration_open": settings.REGISTRATION_OPEN,
  136. "support_email": settings.SUPPORT_EMAIL,
  137. }
  138. return render(request, "accounts/login.html", ctx)
  139. def logout(request):
  140. auth_logout(request)
  141. return redirect("hc-index")
  142. @require_POST
  143. @csrf_exempt
  144. def signup(request):
  145. if not settings.REGISTRATION_OPEN:
  146. return HttpResponseForbidden()
  147. ctx = {}
  148. form = forms.SignupForm(request.POST)
  149. if form.is_valid():
  150. email = form.cleaned_data["identity"]
  151. tz = form.cleaned_data["tz"]
  152. user = _make_user(email, tz)
  153. profile = Profile.objects.for_user(user)
  154. profile.send_instant_login_link()
  155. ctx["created"] = True
  156. else:
  157. ctx = {"form": form}
  158. response = render(request, "accounts/signup_result.html", ctx)
  159. if ctx.get("created"):
  160. response.set_cookie("auto-login", "1", max_age=300, httponly=True)
  161. return response
  162. def login_link_sent(request):
  163. return render(request, "accounts/login_link_sent.html")
  164. def check_token(request, username, token):
  165. if request.user.is_authenticated and request.user.username == username:
  166. # User is already logged in
  167. return _redirect_after_login(request)
  168. # Some email servers open links in emails to check for malicious content.
  169. # To work around this, we sign user in if the method is POST
  170. # *or* if the browser presents a cookie we had set when sending the login link.
  171. #
  172. # If the method is GET and the auto-login cookie isn't present, we serve
  173. # a HTML form with a submit button.
  174. if request.method == "POST" or "auto-login" in request.COOKIES:
  175. user = authenticate(username=username, token=token)
  176. if user is not None and user.is_active:
  177. user.profile.token = ""
  178. user.profile.save()
  179. return _check_2fa(request, user)
  180. request.session["bad_link"] = True
  181. return redirect("hc-login")
  182. return render(request, "accounts/check_token_submit.html")
  183. @login_required
  184. def profile(request):
  185. profile = request.profile
  186. ctx = {
  187. "page": "profile",
  188. "profile": profile,
  189. "my_projects_status": "default",
  190. "2fa_status": "default",
  191. "added_credential_name": request.session.pop("added_credential_name", ""),
  192. "removed_credential_name": request.session.pop("removed_credential_name", ""),
  193. "enabled_totp": request.session.pop("enabled_totp", False),
  194. "disabled_totp": request.session.pop("disabled_totp", False),
  195. "credentials": list(request.user.credentials.order_by("id")),
  196. "use_webauthn": settings.RP_ID,
  197. }
  198. if ctx["added_credential_name"] or ctx["enabled_totp"]:
  199. ctx["2fa_status"] = "success"
  200. if ctx["removed_credential_name"] or ctx["disabled_totp"]:
  201. ctx["2fa_status"] = "info"
  202. if request.session.pop("changed_password", False):
  203. ctx["changed_password"] = True
  204. ctx["email_password_status"] = "success"
  205. if request.method == "POST" and "leave_project" in request.POST:
  206. code = request.POST["code"]
  207. try:
  208. project = Project.objects.get(code=code, member__user=request.user)
  209. except Project.DoesNotExist:
  210. return HttpResponseBadRequest()
  211. Member.objects.filter(project=project, user=request.user).delete()
  212. ctx["left_project"] = project
  213. ctx["my_projects_status"] = "info"
  214. return render(request, "accounts/profile.html", ctx)
  215. @login_required
  216. @require_POST
  217. def add_project(request):
  218. form = forms.ProjectNameForm(request.POST)
  219. if not form.is_valid():
  220. return HttpResponseBadRequest()
  221. project = Project(owner=request.user)
  222. project.code = project.badge_key = str(uuid.uuid4())
  223. project.name = form.cleaned_data["name"]
  224. project.save()
  225. return redirect("hc-checks", project.code)
  226. @login_required
  227. def project(request, code):
  228. project = get_object_or_404(Project, code=code)
  229. is_owner = project.owner_id == request.user.id
  230. if request.user.is_superuser or is_owner:
  231. is_manager = True
  232. rw = True
  233. else:
  234. membership = get_object_or_404(Member, project=project, user=request.user)
  235. is_manager = membership.role == Member.Role.MANAGER
  236. rw = membership.is_rw
  237. ctx = {
  238. "page": "project",
  239. "rw": rw,
  240. "project": project,
  241. "is_owner": is_owner,
  242. "is_manager": is_manager,
  243. "show_api_keys": "show_api_keys" in request.GET,
  244. "enable_prometheus": settings.PROMETHEUS_ENABLED is True,
  245. }
  246. if request.method == "POST":
  247. if "create_api_keys" in request.POST:
  248. if not rw:
  249. return HttpResponseForbidden()
  250. project.set_api_keys()
  251. project.save()
  252. ctx["show_api_keys"] = True
  253. ctx["api_keys_created"] = True
  254. ctx["api_status"] = "success"
  255. elif "revoke_api_keys" in request.POST:
  256. if not rw:
  257. return HttpResponseForbidden()
  258. project.api_key = ""
  259. project.api_key_readonly = ""
  260. project.save()
  261. ctx["api_keys_revoked"] = True
  262. ctx["api_status"] = "info"
  263. elif "show_api_keys" in request.POST:
  264. if not rw:
  265. return HttpResponseForbidden()
  266. ctx["show_api_keys"] = True
  267. elif "invite_team_member" in request.POST:
  268. if not is_manager:
  269. return HttpResponseForbidden()
  270. form = forms.InviteTeamMemberForm(request.POST)
  271. if form.is_valid():
  272. email = form.cleaned_data["email"]
  273. invite_suggestions = project.invite_suggestions()
  274. if not invite_suggestions.filter(email=email).exists():
  275. # We're inviting a new user. Are we within team size limit?
  276. if not project.can_invite_new_users():
  277. return HttpResponseForbidden()
  278. # And are we not hitting a rate limit?
  279. if not TokenBucket.authorize_invite(request.user):
  280. return render(request, "try_later.html")
  281. try:
  282. user = User.objects.get(email=email)
  283. except User.DoesNotExist:
  284. user = _make_user(email, with_project=False)
  285. if project.invite(user, role=form.cleaned_data["role"]):
  286. ctx["team_member_invited"] = email
  287. ctx["team_status"] = "success"
  288. else:
  289. ctx["team_member_duplicate"] = email
  290. ctx["team_status"] = "info"
  291. elif "remove_team_member" in request.POST:
  292. if not is_manager:
  293. return HttpResponseForbidden()
  294. form = forms.RemoveTeamMemberForm(request.POST)
  295. if form.is_valid():
  296. q = User.objects
  297. q = q.filter(email=form.cleaned_data["email"])
  298. q = q.filter(memberships__project=project)
  299. farewell_user = q.first()
  300. if farewell_user is None:
  301. return HttpResponseBadRequest()
  302. if farewell_user == request.user:
  303. return HttpResponseBadRequest()
  304. Member.objects.filter(project=project, user=farewell_user).delete()
  305. ctx["team_member_removed"] = form.cleaned_data["email"]
  306. ctx["team_status"] = "info"
  307. elif "set_project_name" in request.POST:
  308. if not rw:
  309. return HttpResponseForbidden()
  310. form = forms.ProjectNameForm(request.POST)
  311. if form.is_valid():
  312. project.name = form.cleaned_data["name"]
  313. project.save()
  314. ctx["project_name_updated"] = True
  315. ctx["project_name_status"] = "success"
  316. elif "transfer_project" in request.POST:
  317. if not is_owner:
  318. return HttpResponseForbidden()
  319. form = forms.TransferForm(request.POST)
  320. if form.is_valid():
  321. # Look up the proposed new owner
  322. email = form.cleaned_data["email"]
  323. try:
  324. membership = project.member_set.filter(user__email=email).get()
  325. except Member.DoesNotExist:
  326. return HttpResponseBadRequest()
  327. # Revoke any previous transfer requests
  328. project.member_set.update(transfer_request_date=None)
  329. # Initiate the new request
  330. membership.transfer_request_date = now()
  331. membership.save()
  332. # Send an email notification
  333. profile = Profile.objects.for_user(membership.user)
  334. profile.send_transfer_request(project)
  335. ctx["transfer_initiated"] = True
  336. ctx["transfer_status"] = "success"
  337. elif "cancel_transfer" in request.POST:
  338. if not is_owner:
  339. return HttpResponseForbidden()
  340. project.member_set.update(transfer_request_date=None)
  341. ctx["transfer_cancelled"] = True
  342. ctx["transfer_status"] = "success"
  343. elif "accept_transfer" in request.POST:
  344. tr = project.transfer_request()
  345. if not tr or tr.user != request.user:
  346. return HttpResponseForbidden()
  347. if not tr.can_accept():
  348. return HttpResponseBadRequest()
  349. with transaction.atomic():
  350. # 1. Reuse the existing membership, and change its user
  351. tr.user = project.owner
  352. tr.transfer_request_date = None
  353. # The previous owner becomes a regular member
  354. # (not readonly, not manager):
  355. tr.role = Member.Role.REGULAR
  356. tr.save()
  357. # 2. Change project's owner
  358. project.owner = request.user
  359. project.save()
  360. ctx["is_owner"] = True
  361. ctx["is_manager"] = True
  362. messages.success(request, "You are now the owner of this project!")
  363. elif "reject_transfer" in request.POST:
  364. tr = project.transfer_request()
  365. if not tr or tr.user != request.user:
  366. return HttpResponseForbidden()
  367. tr.transfer_request_date = None
  368. tr.save()
  369. q = project.member_set.select_related("user").order_by("user__email")
  370. ctx["memberships"] = list(q)
  371. return render(request, "accounts/project.html", ctx)
  372. @login_required
  373. def notifications(request):
  374. profile = request.profile
  375. ctx = {"status": "default", "page": "profile", "profile": profile}
  376. if request.method == "POST":
  377. form = forms.ReportSettingsForm(request.POST)
  378. if form.is_valid():
  379. if form.cleaned_data["tz"]:
  380. profile.tz = form.cleaned_data["tz"]
  381. profile.reports = form.cleaned_data["reports"]
  382. profile.next_report_date = profile.choose_next_report_date()
  383. if profile.nag_period != form.cleaned_data["nag_period"]:
  384. # Set the new nag period
  385. profile.nag_period = form.cleaned_data["nag_period"]
  386. # and update next_nag_date:
  387. if profile.nag_period:
  388. profile.update_next_nag_date()
  389. else:
  390. profile.next_nag_date = None
  391. profile.save()
  392. ctx["status"] = "info"
  393. return render(request, "accounts/notifications.html", ctx)
  394. @login_required
  395. @require_sudo_mode
  396. def set_password(request):
  397. if request.method == "POST":
  398. form = forms.SetPasswordForm(request.POST)
  399. if form.is_valid():
  400. password = form.cleaned_data["password"]
  401. request.user.set_password(password)
  402. request.user.save()
  403. request.profile.token = ""
  404. request.profile.save()
  405. # update the session with the new password hash so that
  406. # the user doesn't get logged out
  407. update_session_auth_hash(request, request.user)
  408. request.session["changed_password"] = True
  409. return redirect("hc-profile")
  410. return render(request, "accounts/set_password.html", {})
  411. @login_required
  412. @require_sudo_mode
  413. def change_email(request):
  414. if request.method == "POST":
  415. form = forms.ChangeEmailForm(request.POST)
  416. if form.is_valid():
  417. request.user.email = form.cleaned_data["email"]
  418. request.user.set_unusable_password()
  419. request.user.save()
  420. request.profile.token = ""
  421. request.profile.save()
  422. return redirect("hc-change-email-done")
  423. else:
  424. form = forms.ChangeEmailForm()
  425. return render(request, "accounts/change_email.html", {"form": form})
  426. def change_email_done(request):
  427. return render(request, "accounts/change_email_done.html")
  428. @csrf_exempt
  429. def unsubscribe_reports(request, signed_username):
  430. # Some email servers open links in emails to check for malicious content.
  431. # To work around this, for GET requests we serve a confirmation form.
  432. # If the signature is more than 5 minutes old, we also include JS code to
  433. # auto-submit the form.
  434. signer = signing.TimestampSigner(salt="reports")
  435. # First, check the signature without looking at the timestamp:
  436. try:
  437. username = signer.unsign(signed_username)
  438. except signing.BadSignature:
  439. return render(request, "bad_link.html")
  440. try:
  441. user = User.objects.get(username=username)
  442. except User.DoesNotExist:
  443. # This is likely an old unsubscribe link, and the user account has already
  444. # been deleted. Show the "Unsubscribed!" page nevertheless.
  445. return render(request, "accounts/unsubscribed.html")
  446. if request.method != "POST":
  447. # Unsign again, now with max_age set,
  448. # to see if the timestamp is older than 5 minutes
  449. try:
  450. autosubmit = False
  451. username = signer.unsign(signed_username, max_age=300)
  452. except signing.SignatureExpired:
  453. autosubmit = True
  454. ctx = {"autosubmit": autosubmit}
  455. return render(request, "accounts/unsubscribe_submit.html", ctx)
  456. profile = Profile.objects.for_user(user)
  457. profile.reports = "off"
  458. profile.next_report_date = None
  459. profile.nag_period = td()
  460. profile.next_nag_date = None
  461. profile.save()
  462. return render(request, "accounts/unsubscribed.html")
  463. @login_required
  464. @require_sudo_mode
  465. def close(request):
  466. user = request.user
  467. if request.method == "POST":
  468. if request.POST.get("confirmation") == request.user.email:
  469. # Cancel their subscription:
  470. sub = Subscription.objects.filter(user=user).first()
  471. if sub:
  472. sub.cancel()
  473. # Deleting user also deletes its profile, checks, channels etc.
  474. user.delete()
  475. request.session.flush()
  476. return redirect("hc-index")
  477. ctx = {}
  478. if "confirmation" in request.POST:
  479. ctx["wrong_confirmation"] = True
  480. return render(request, "accounts/close_account.html", ctx)
  481. @require_POST
  482. @login_required
  483. def remove_project(request, code):
  484. project = get_object_or_404(Project, code=code, owner=request.user)
  485. project.delete()
  486. return redirect("hc-index")
  487. def _get_credential_data(request, form):
  488. """ Complete WebAuthn registration, return binary credential data.
  489. This function is an interface to the fido2 library. It is separated
  490. out so that we don't need to mock ClientData, AttestationObject,
  491. register_complete separately in tests.
  492. """
  493. try:
  494. auth_data = FIDO2_SERVER.register_complete(
  495. request.session["state"],
  496. ClientData(form.cleaned_data["client_data_json"]),
  497. AttestationObject(form.cleaned_data["attestation_object"]),
  498. )
  499. except ValueError:
  500. return None
  501. return auth_data.credential_data
  502. @login_required
  503. @require_sudo_mode
  504. def add_webauthn(request):
  505. if not settings.RP_ID:
  506. return HttpResponse(status=404)
  507. if request.method == "POST":
  508. form = forms.AddWebAuthnForm(request.POST)
  509. if not form.is_valid():
  510. return HttpResponseBadRequest()
  511. credential_data = _get_credential_data(request, form)
  512. if not credential_data:
  513. return HttpResponseBadRequest()
  514. c = Credential(user=request.user)
  515. c.name = form.cleaned_data["name"]
  516. c.data = credential_data
  517. c.save()
  518. request.session["added_credential_name"] = c.name
  519. return redirect("hc-profile")
  520. credentials = [c.unpack() for c in request.user.credentials.all()]
  521. # User handle is used in a username-less authentication, to map a credential
  522. # received from browser with an user account in the database.
  523. # Since we only use security keys as a second factor,
  524. # the user handle is not of much use to us.
  525. #
  526. # The user handle:
  527. # - must not be blank,
  528. # - must not be a constant value,
  529. # - must not contain personally identifiable information.
  530. # So we use random bytes, and don't store them on our end:
  531. options, state = FIDO2_SERVER.register_begin(
  532. {
  533. "id": token_bytes(16),
  534. "name": request.user.email,
  535. "displayName": request.user.email,
  536. },
  537. credentials,
  538. )
  539. request.session["state"] = state
  540. ctx = {"options": base64.b64encode(cbor.encode(options)).decode()}
  541. return render(request, "accounts/add_credential.html", ctx)
  542. @login_required
  543. @require_sudo_mode
  544. def add_totp(request):
  545. if request.profile.totp:
  546. # TOTP is already configured, refuse to continue
  547. return HttpResponseBadRequest()
  548. if "totp_secret" not in request.session:
  549. request.session["totp_secret"] = pyotp.random_base32()
  550. totp = pyotp.totp.TOTP(request.session["totp_secret"])
  551. if request.method == "POST":
  552. form = forms.TotpForm(totp, request.POST)
  553. if form.is_valid():
  554. request.profile.totp = request.session["totp_secret"]
  555. request.profile.totp_created = now()
  556. request.profile.save()
  557. request.session["enabled_totp"] = True
  558. request.session.pop("totp_secret")
  559. return redirect("hc-profile")
  560. else:
  561. form = forms.TotpForm(totp)
  562. uri = totp.provisioning_uri(name=request.user.email, issuer_name=settings.SITE_NAME)
  563. qr_data_uri = segno.make(uri).png_data_uri(scale=8)
  564. ctx = {"form": form, "qr_data_uri": qr_data_uri}
  565. return render(request, "accounts/add_totp.html", ctx)
  566. @login_required
  567. @require_sudo_mode
  568. def remove_totp(request):
  569. if request.method == "POST" and "disable_totp" in request.POST:
  570. request.profile.totp = None
  571. request.profile.totp_created = None
  572. request.profile.save()
  573. request.session["disabled_totp"] = True
  574. return redirect("hc-profile")
  575. ctx = {"is_last": not request.user.credentials.exists()}
  576. return render(request, "accounts/remove_totp.html", ctx)
  577. @login_required
  578. @require_sudo_mode
  579. def remove_credential(request, code):
  580. if not settings.RP_ID:
  581. return HttpResponse(status=404)
  582. try:
  583. credential = Credential.objects.get(user=request.user, code=code)
  584. except Credential.DoesNotExist:
  585. return HttpResponseBadRequest()
  586. if request.method == "POST" and "remove_credential" in request.POST:
  587. request.session["removed_credential_name"] = credential.name
  588. credential.delete()
  589. return redirect("hc-profile")
  590. if request.profile.totp:
  591. is_last = False
  592. else:
  593. is_last = request.user.credentials.count() == 1
  594. ctx = {"credential": credential, "is_last": is_last}
  595. return render(request, "accounts/remove_credential.html", ctx)
  596. def _check_credential(request, form, credentials):
  597. """ Complete WebAuthn authentication, return True on success.
  598. This function is an interface to the fido2 library. It is separated
  599. out so that we don't need to mock ClientData, AuthenticatorData,
  600. authenticate_complete separately in tests.
  601. """
  602. try:
  603. FIDO2_SERVER.authenticate_complete(
  604. request.session["state"],
  605. credentials,
  606. form.cleaned_data["credential_id"],
  607. ClientData(form.cleaned_data["client_data_json"]),
  608. AuthenticatorData(form.cleaned_data["authenticator_data"]),
  609. form.cleaned_data["signature"],
  610. )
  611. except ValueError:
  612. return False
  613. return True
  614. def login_webauthn(request):
  615. # We require RP_ID. Fail predicably if it is not set:
  616. if not settings.RP_ID:
  617. return HttpResponse(status=500)
  618. # Expect an unauthenticated user
  619. if request.user.is_authenticated:
  620. return HttpResponseBadRequest()
  621. if "2fa_user" not in request.session:
  622. return HttpResponseBadRequest()
  623. user_id, email, timestamp = request.session["2fa_user"]
  624. if timestamp + 300 < time.time():
  625. return redirect("hc-login")
  626. try:
  627. user = User.objects.get(id=user_id, email=email)
  628. except User.DoesNotExist:
  629. return HttpResponseBadRequest()
  630. credentials = [c.unpack() for c in user.credentials.all()]
  631. if request.method == "POST":
  632. form = forms.WebAuthnForm(request.POST)
  633. if not form.is_valid():
  634. return HttpResponseBadRequest()
  635. if not _check_credential(request, form, credentials):
  636. return HttpResponseBadRequest()
  637. request.session.pop("state")
  638. request.session.pop("2fa_user")
  639. auth_login(request, user, "hc.accounts.backends.EmailBackend")
  640. return _redirect_after_login(request)
  641. options, state = FIDO2_SERVER.authenticate_begin(credentials)
  642. request.session["state"] = state
  643. ctx = {
  644. "options": base64.b64encode(cbor.encode(options)).decode(),
  645. "offer_totp": True if user.profile.totp else False,
  646. }
  647. return render(request, "accounts/login_webauthn.html", ctx)
  648. def login_totp(request):
  649. # Expect an unauthenticated user
  650. if request.user.is_authenticated:
  651. return HttpResponseBadRequest()
  652. if "2fa_user" not in request.session:
  653. return HttpResponseBadRequest()
  654. user_id, email, timestamp = request.session["2fa_user"]
  655. if timestamp + 300 < time.time():
  656. return redirect("hc-login")
  657. try:
  658. user = User.objects.get(id=user_id, email=email)
  659. except User.DoesNotExist:
  660. return HttpResponseBadRequest()
  661. if not user.profile.totp:
  662. return HttpResponseBadRequest()
  663. totp = pyotp.totp.TOTP(user.profile.totp)
  664. if request.method == "POST":
  665. if not TokenBucket.authorize_totp_attempt(user):
  666. return render(request, "try_later.html")
  667. form = forms.TotpForm(totp, request.POST)
  668. if form.is_valid():
  669. if not TokenBucket.authorize_totp_code(user, form.cleaned_data["code"]):
  670. return render(request, "try_later.html")
  671. request.session.pop("2fa_user")
  672. auth_login(request, user, "hc.accounts.backends.EmailBackend")
  673. return _redirect_after_login(request)
  674. else:
  675. form = forms.TotpForm(totp)
  676. return render(request, "accounts/login_totp.html", {"form": form})
  677. @login_required
  678. def appearance(request):
  679. profile = request.profile
  680. ctx = {
  681. "page": "appearance",
  682. "profile": profile,
  683. "status": "default",
  684. }
  685. if request.method == "POST":
  686. theme = request.POST.get("theme", "")
  687. if theme in ("", "dark"):
  688. profile.theme = theme
  689. profile.save()
  690. ctx["status"] = "info"
  691. return render(request, "accounts/appearance.html", ctx)