Remove JS from login page

* Okay so we're not doing HTTP Basic Auth, that was an awful experience with those pop-ups.
* But we set the cookie with Django on the server-side, instead of needing JS
* So this should improve browser compatibility. No promises.
This commit is contained in:
Matthias Portzel 2022-01-06 12:05:18 -08:00
parent 0674bfee54
commit 293ac50d98
3 changed files with 23 additions and 13 deletions

View File

@ -18,17 +18,10 @@
Please enter the password to access this page.
</span>
<form id="password-form">
<input type="password" id="password">
<form id="password-form" method="POST">
{% csrf_token %}
<input type="password" name="password" id="password">
<input type="submit" value="Login">
</form>
{% endblock %}
{% block scripts %}
<script>
document.getElementById("password-form").addEventListener("submit", evt => {
document.cookie = `password=${document.getElementById("password").value}; max-age=15768000; samesite=strict`;
window.location.reload();
})
</script>
{% endblock %}

View File

@ -5,9 +5,9 @@ import base64
import magic
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.utils.crypto import constant_time_compare
from django.http import HttpResponse
from django.http import HttpResponse, HttpResponseRedirect
from whispermaphone import settings
from .models import Thought, ThoughtForm, ALLOWED_MEDIA_TYPES
@ -18,6 +18,7 @@ def check_authenticated(request):
authenticated = False
try:
if constant_time_compare(request.COOKIES["password"], settings.PASSWORD):
print("Authorization success")
authenticated = True
except KeyError:
pass
@ -64,9 +65,24 @@ def index(request):
})
def login(request):
if check_authenticated(request):
return redirect("post")
if request.method == "POST":
if constant_time_compare(request.POST["password"], settings.PASSWORD):
res = redirect("post")
res.set_cookie("password", request.POST["password"])
return res
# Returning 401 here causes `links` to always prompt for HTTP basic auth, which is annoying.
# But the alternative is not following the HTTP spec, so I think this is fine.
return render(request, "whispermaphone/login.html", status=401)
def post(request):
if not check_authenticated(request):
return render(request, "whispermaphone/login.html", status=401)
return redirect("login")
if request.method == "POST":
# We post in hours, so we need to convert back to minutes for saving

View File

@ -11,6 +11,7 @@ from haystack.forms import SearchForm
urlpatterns = [
path("", views.index, name="index"),
path("about", views.about, name="about"),
path("login", views.login, name="login"),
path("post", views.post, name="post"),
path("feed", MainFeed()),
path("search", SearchView(form_class=SearchForm), name="thoughts_search")