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.

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