From ffaaea497c44f362a619d95da097def836a28b50 Mon Sep 17 00:00:00 2001
From: Philip Sargent <philip.sargent@klebos.com>
Date: Sat, 27 Mar 2021 18:22:07 +0000
Subject: [PATCH] re-ordering middleware and logon system

---
 core/views_other.py               |  6 +++++-
 core/views_survex.py              |  8 ++++----
 settings.py                       | 14 ++++++++------
 templates/base.html               |  2 +-
 templates/frontpage.html          |  4 ++--
 templates/pagenotfound.html       |  5 ++++-
 templates/registration/login.html |  7 +++++++
 templates/tasks.html              | 27 +++++++++++++++++++++++++++
 urls.py                           |  9 +++++++--
 9 files changed, 65 insertions(+), 17 deletions(-)

diff --git a/core/views_other.py b/core/views_other.py
index 0944d55..67726cc 100644
--- a/core/views_other.py
+++ b/core/views_other.py
@@ -34,7 +34,11 @@ def troggle404(request): # cannot get this to work. Handler404 in urls.py not ri
 def showrequest(request):
     return HttpResponse(request.GET)
 
-def frontpage(request):
+def frontpage(request): 
+    '''never seen in practice'''
+    # bthe messages system does a popup on this page if there is a recent message, e.g. from the admin site actions.
+    # via django.contrib.messages.middleware.MessageMiddleware 
+    # this is set in the templates.
     if request.user.is_authenticated():
         return render(request,'tasks.html')
 
diff --git a/core/views_survex.py b/core/views_survex.py
index 2928897..9bec952 100644
--- a/core/views_survex.py
+++ b/core/views_survex.py
@@ -146,7 +146,7 @@ class SvxForm(forms.Form):
         return "SAVED ."
 
     def Process(self):
-        print("....\n\n\n....Processing\n\n\n")
+        print(">>>>....\n\n\n....Processing\n\n\n")
         froox = os.fspath(survexdatasetpath / (self.data['filename'] + ".svx"))
         froog = os.fspath(survexdatasetpath / (self.data['filename'] + ".log"))
         cwd = os.getcwd()
@@ -184,7 +184,7 @@ def svx(request, survex_file):
             rcode = rform.cleaned_data['code']
             outputtype = rform.cleaned_data['outputtype']
             difflist = form.DiffCode(rcode)
-            #print("ssss ", rform.data)
+            #print(">>>> ", rform.data)
             
             if "revert" in rform.data:
                 pass
@@ -225,7 +225,7 @@ def svx(request, survex_file):
             'difflist': difflist,
             'logmessage':logmessage,
             'form':form}
-    vmap.update(csrf(request))
+    # vmap.update(csrf(request)) # this now refreshes to the wrong value, now that we user render(request, 
     
     if outputtype == "ajax":
         return render(request, 'svxfiledifflistonly.html', vmap)
@@ -331,7 +331,7 @@ def survexcaveslist(request):
         arealist = sorted([ (area, -int(re.match(r"\d*", f).group(0) or "0"), f)  for f in os.listdir(cavesdir) ])
         fnumlist += arealist
     
-    print(fnumlist)
+    #print(fnumlist)
     
     # go through the list and identify the contents of each cave directory
     for area, num, cavedir in fnumlist:
diff --git a/settings.py b/settings.py
index 61d0bfc..20a0d63 100644
--- a/settings.py
+++ b/settings.py
@@ -126,16 +126,18 @@ INSTALLED_APPS = (
     'troggle.flatpages', # Written by Martin Green 2011. This is NOT django.contrib.flatpages which stores HTML in the database
 )
 
+# See the recommended order of these in https://docs.djangoproject.com/en/2.2/ref/middleware/
 MIDDLEWARE_CLASSES = (
-    'django.middleware.csrf.CsrfViewMiddleware', # Cross Site Request Forgeries by adding hidden form fields to POST
-    'django.middleware.security.SecurityMiddleware', # SECURE_SSL_REDIRECT and SECURE_SSL_HOST
-    'django.contrib.sessions.middleware.SessionMiddleware', # Manages sessions across requests
+    #'django.middleware.security.SecurityMiddleware', # SECURE_SSL_REDIRECT and SECURE_SSL_HOST # we don't use this
+    'django.middleware.gzip.GZipMiddleware', # not needed as expofiles and photos served by apache
+    'django.contrib.sessions.middleware.SessionMiddleware', # Manages sessions, if CSRF_USE_SESSIONS then it needs to be early
     'django.middleware.common.CommonMiddleware', # DISALLOWED_USER_AGENTS, APPEND_SLASH and PREPEND_WWW
+    'django.middleware.csrf.CsrfViewMiddleware', # Cross Site Request Forgeries by adding hidden form fields to POST
     'django.contrib.auth.middleware.AuthenticationMiddleware',  # Adds the user attribute, representing the currently-logged-in user
-    'django.contrib.admindocs.middleware.XViewMiddleware',
-    'django.contrib.messages.middleware.MessageMiddleware', # Cookie-based and session-based message support
+    'django.contrib.admindocs.middleware.XViewMiddleware', # this and docutils needed by admindocs
+    'django.contrib.messages.middleware.MessageMiddleware', # Cookie-based and session-based message support. Needed by admin system
     'django.middleware.clickjacking.XFrameOptionsMiddleware', # clickjacking protection via the X-Frame-Options header
-    'troggle.middleware.SmartAppendSlashMiddleware' # Outdated & unneeded?
+    'troggle.middleware.SmartAppendSlashMiddleware' # 
 )
 
 ROOT_URLCONF = 'troggle.urls'
diff --git a/templates/base.html b/templates/base.html
index 081d5a2..2a61aac 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -23,7 +23,7 @@
     You are logged in as {{ user.username }} 
     	{% if user.person %}(<a href="{{ user.person.get_absolute_url }}">{{ user.person }}</a>)
         {% endif %}.
-    | <a href="{% url "auth_logout" %}">Log out</a> {% else %} <a href='{% url "registration_register" %}'>Sign up</a> | <a href='{% url "auth_login" %}'>Log in</a> {% endif %}
+    | <a href="{% url "auth_logout" %}">Log out</a> {% else %} <a href='/accounts/logout'>Sign up</a> | <a href='{% url "auth_login" %}'>Log in</a> {% endif %}
     {% endblock%}
     {% block editLink %}
 
diff --git a/templates/frontpage.html b/templates/frontpage.html
index 5f0bf18..534602d 100644
--- a/templates/frontpage.html
+++ b/templates/frontpage.html
@@ -4,7 +4,7 @@
 {% block title %}Cambridge Expeditions to Austria{% endblock %}
 
 	{% block related %}
-        <h2>Recent Actions</h2>
+        <h2>Recent Actions - admin user</h5>
             {% load log %}
             {% get_admin_log 10 as admin_log for_user 1 %}
             {% if not admin_log %}
@@ -16,7 +16,7 @@
                 {% if entry.is_deletion %}
                     {{ entry.object_repr }}
                 {% else %}
-                    <a href="admin/{{ entry.get_admin_url }}/">{{ entry.object_repr }}</a>
+                    <a href="{{ entry.get_admin_url }}/">{{ entry.object_repr }}</a>
                 {% endif %}
                 <br/>
                 {% if entry.content_type %}
diff --git a/templates/pagenotfound.html b/templates/pagenotfound.html
index 4fdfe2a..2791dd9 100644
--- a/templates/pagenotfound.html
+++ b/templates/pagenotfound.html
@@ -2,6 +2,9 @@
 {% block title %}Page not found {{ path }}{% endblock %}
 {% block body %}
 <h1>Page not found {{ path }}</h1>
-<a href="{%url "editflatpage" path %}">Create this page.</a>
+<p>Probably a mistake. But you can use <a href="{%url "editflatpage" path %}">this link</a>
+<p>
+ or 'Edit this page' in the menu on the left to create this page if you aare logged in.
+ <p>If you can't see that option in the menu, then you are not logged in and you can't create anything.
 {% include "menu.html" %}
 {% endblock %}
diff --git a/templates/registration/login.html b/templates/registration/login.html
index 388d41b..da61169 100644
--- a/templates/registration/login.html
+++ b/templates/registration/login.html
@@ -7,14 +7,21 @@
 <p>Your username and password didn't match. Please try again.</p>
 {% endif %}
 
+<div align="center">
+<pre>This uses the registration/login.html template</pre>
+
 <form method="post" action=".">{% csrf_token %}
 <table>
 <tr><td>{{ form.username.label_tag }}</td><td>{{ form.username }}</td></tr>
 <tr><td>{{ form.password.label_tag }}</td><td>{{ form.password }}</td></tr>
 </table>
 
+
+
 <input type="submit" value="login" />
 <input type="hidden" name="next" value="{{ next }}" />
 </form>
 
+
+</div>
 {% endblock %}
diff --git a/templates/tasks.html b/templates/tasks.html
index 4a6a02b..e9b12a9 100644
--- a/templates/tasks.html
+++ b/templates/tasks.html
@@ -4,6 +4,33 @@
 
 {% block title %}Cambridge Expeditions to Austria{% endblock %}
 
+	{% block related %}
+        <h2>Recent Actions - admin user</h5>
+            {% load log %}
+            {% get_admin_log 10 as admin_log for_user 1 %}
+            {% if not admin_log %}
+            <p>No recent actions</p>
+            {% else %}
+            <ul class="actionlist">
+            {% for entry in admin_log %}
+            <li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}">
+                {% if entry.is_deletion %}
+                    {{ entry.object_repr }}
+                {% else %}
+                    <a href="{{ entry.get_admin_url }}/">{{ entry.object_repr }}</a>
+                {% endif %}
+                <br/>
+                {% if entry.content_type %}
+                    <span class="mini quiet">{% filter capfirst %}{{entry.content_type.name}}{% endfilter %}</span>
+                {% else %}
+                    <span class="mini quiet">Unknown content</span>
+                {% endif %}
+            </li>
+            {% endfor %}
+            </ul>
+            {% endif %}
+	{% endblock %}
+    
 {% block content %}
 <h2>This is not fully working currently</h2>
 <h2>The code behind this page is under repair</h2>
diff --git a/urls.py b/urls.py
index 4968ad8..2c61054 100644
--- a/urls.py
+++ b/urls.py
@@ -44,14 +44,19 @@ else:
 actualurlpatterns = [
     url(r'^expofiles/', include(expofilesurls)), 
     
-    url(r'^troggle$',    views_other.frontpage,      name="frontpage"),
+    url(r'^troggle$',    views_other.frontpage,      name="frontpage"), # control panel. Shows recent actions.
     url(r'^caves$',      views_caves.caveindex,      name="caveindex"),
     url(r'^indxal.htm$', views_caves.caveindex,      name="caveindex"), # ~420 hrefs to this url in expoweb files
     url(r'^people/?$',   views_logbooks.personindex, name="personindex"),
 
     url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # needs docutils Python module (http://docutils.sf.net/).
     url(r'^admin/', admin.site.urls),
-    url(r'^accounts/', include('registration.backends.default.urls')), #LOGIN_URL = '/accounts/login/' # default
+    
+    # setting LOGIN_URL = '/accounts/login/' is default
+    #url(r'^accounts/', include('registration.backends.default.urls')), # deprecated, replace with .model_activation.urls
+    url(r'^accounts/', include('registration.backends.model_activation.urls')),  # deprecated in Dj3.0, but must not be commented out.
+    url(r'^accounts/', include('django.contrib.auth.urls')),  # from Dj3.0, see site-packages\registration\auth_urls_classes.py
+    
 
     url(r'^newqmnumber/?$',              views_other.ajax_QM_number, ),
 #   url(r'^lbo_suggestions/?$',              logbook_entry_suggestions),   #broken, removed.