Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Login automatically to anonymous user #10

Merged
merged 3 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 0 additions & 22 deletions lidiabrowser/lidia/management/commands/initgroups.py

This file was deleted.

10 changes: 6 additions & 4 deletions lidiabrowser/lidia/tests.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import pytest
from django.contrib.auth.models import Group, Permission
from django.core.management import call_command

from lidiabrowser.init import initiate_groups


@pytest.mark.django_db
class TestInitgroups:
def test_basic(self):
call_command("initgroups")
groups = initiate_groups()
assert isinstance(groups["view_all"], Group)
view_all = Group.objects.get(name="view_all")
viewpublicationpermission = Permission.objects.get_by_natural_key(
"view_publication", "lidia", "publication"
Expand All @@ -15,5 +17,5 @@ def test_basic(self):

def test_double(self):
# Calling twice on the same database should be fine
call_command("initgroups")
call_command("initgroups")
initiate_groups()
initiate_groups()
4 changes: 3 additions & 1 deletion lidiabrowser/lidiabrowser/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@
class LidiaBrowserAdminSite(admin.AdminSite):
site_header = "LIDIA Annotation Browser"
site_title = "LIDIA Annotation Browser"
site_url = None
site_url = None # type: ignore
logout_template = "lidiabrowser/logged_out.html"
login_template = "lidiabrowser/login.html"
16 changes: 16 additions & 0 deletions lidiabrowser/lidiabrowser/autologin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.contrib.auth import login
from django.http import HttpRequest, HttpResponseRedirect
from django.urls import reverse

from lidiabrowser.init import get_anonymous_user


def index_view_autologin(request: HttpRequest):
# If the user is not authenticated, automatically login to the
# anonymous user, which should be created if necessary.
if not request.user.is_authenticated:
# Create anonymous user and viewer group if necessary
anonymous_user = get_anonymous_user()
login(request, anonymous_user)
return HttpResponseRedirect(reverse("admin:index"))

43 changes: 43 additions & 0 deletions lidiabrowser/lidiabrowser/init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from django.contrib.auth.models import Group, Permission, User

ANONYMOUSUSERNAME = "anonymous"


def initiate_groups() -> dict[str, Group]:
ar-jan marked this conversation as resolved.
Show resolved Hide resolved
"""Create groups for viewer accounts and return a dictionary containing
the group objects."""
# For now, only create a 'view all' group - no distinction yet
# between all or restricted access
view_all, _ = Group.objects.get_or_create(name="view_all")
models = [
'publication', 'language', 'annotation', 'articleterm',
'lidiaterm', 'category', 'termgroup'
]
permissions = []
for model in models:
permissions.append(Permission.objects.get_by_natural_key(
"view_" + model, "lidia", model
))
view_all.permissions.add(*permissions)
return {
"view_all": view_all
}


def create_anonymous_user(view_all_group: Group) -> User:
anonymous_user = User.objects.create_user(
ANONYMOUSUSERNAME,
is_staff=True
)
anonymous_user.groups.add(view_all_group)
return anonymous_user


def get_anonymous_user() -> User:
try:
anonymous_user = User.objects.get(username=ANONYMOUSUSERNAME)
except User.DoesNotExist:
groups = initiate_groups()
anonymous_user = create_anonymous_user(groups["view_all"])
return anonymous_user

2 changes: 1 addition & 1 deletion lidiabrowser/lidiabrowser/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"DIRS": ["lidiabrowser/templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
Expand Down
13 changes: 13 additions & 0 deletions lidiabrowser/lidiabrowser/templates/lidiabrowser/logged_out.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{% extends "registration/logged_out.html" %}

{% load i18n %}

{% block content %}

<p>{% translate "You are now logged out." %}</p>

<p><a href="{% url 'admin:index' %}">{% translate "Log in again" %}</a></p>

<p><a href="{% url 'index' %}">{% translate "Log in as an anonymous user" %}</a></p>

{% endblock %}
54 changes: 54 additions & 0 deletions lidiabrowser/lidiabrowser/templates/lidiabrowser/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{% extends "admin/login.html" %}
{% load i18n %}
{% block content %}
{% if form.errors and not form.non_field_errors %}
<p class="errornote">
{% blocktranslate count counter=form.errors.items|length %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktranslate %}
</p>
{% endif %}

{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
<p class="errornote">
{{ error }}
</p>
{% endfor %}
{% endif %}

<div id="content-main">

{% if user.is_authenticated %}
<p class="errornote">
{% blocktranslate trimmed %}
You are authenticated as {{ username }}, but are not authorized to
access this page. Would you like to login to a different account?
{% endblocktranslate %}
</p>
{% endif %}

<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
<div class="form-row">
{{ form.username.errors }}
{{ form.username.label_tag }} {{ form.username }}
</div>
<div class="form-row">
{{ form.password.errors }}
{{ form.password.label_tag }} {{ form.password }}
<input type="hidden" name="next" value="{{ next }}">
</div>
{% url 'admin_password_reset' as password_reset_url %}
{% if password_reset_url %}
<div class="password-reset-link">
<a href="{{ password_reset_url }}">{% translate 'Forgotten your password or username?' %}</a>
</div>
{% endif %}
<div style="text-align: center">
<a href="{% url "index" %}">{% translate 'Log in as anonymous user' %}</a>
</div>
<div class="submit-row">
<input type="submit" value="{% translate 'Log in' %}">
</div>
</form>

</div>
{% endblock %}
14 changes: 9 additions & 5 deletions lidiabrowser/lidiabrowser/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,30 @@
from django.contrib.auth import views as auth_views
from django.urls import path

from .autologin import index_view_autologin


urlpatterns = [
path(
"password_reset/",
"browser/password_reset/",
auth_views.PasswordResetView.as_view(),
name="admin_password_reset",
),
path(
"password_reset/done/",
"browser/password_reset/done/",
auth_views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
path(
"reset/<uidb64>/<token>/",
"browser/reset/<uidb64>/<token>/",
auth_views.PasswordResetConfirmView.as_view(),
name="password_reset_confirm",
),
path(
"reset/done/",
"browser/reset/done/",
auth_views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
path("", admin.site.urls),
path("browser/", admin.site.urls),
path("", index_view_autologin, name="index"),
]