Skip to content

Commit ab71265

Browse files
authored
Merge pull request #1122 from thecourseforum/django_session
Django session
2 parents 060e12e + 4702108 commit ab71265

File tree

14 files changed

+321
-132
lines changed

14 files changed

+321
-132
lines changed

tcf_core/context_processors.py

Lines changed: 9 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
"""Inject extra context to TCF templates."""
22

3-
import ast
4-
53
from django.conf import settings
64

75
from tcf_website.models import Discipline, Semester, Subdepartment
@@ -16,53 +14,25 @@ def base(request):
1614
}
1715

1816

19-
def history_cookies(request):
20-
"""Puts history from cookies into context variables."""
21-
if "previous_paths" in request.COOKIES:
22-
previous_paths = request.COOKIES["previous_paths"]
23-
previous_paths = ast.literal_eval(previous_paths)
24-
else:
25-
previous_paths = ""
26-
27-
if "previous_paths_titles" in request.COOKIES:
28-
previous_paths_titles = request.COOKIES["previous_paths_titles"]
29-
previous_paths_titles = ast.literal_eval(previous_paths_titles)
30-
else:
31-
previous_paths_titles = ""
32-
33-
previous_paths_titles = [title[:80] + "..." for title in previous_paths_titles]
34-
35-
previous_paths_and_titles = None
36-
if len(previous_paths) > 0 and len(previous_paths_titles) > 0:
37-
previous_paths_and_titles = zip(previous_paths, previous_paths_titles)
38-
39-
return {
40-
"previous_paths": previous_paths,
41-
"previous_path_titles": previous_paths_titles,
42-
"previous_paths_and_titles": previous_paths_and_titles,
43-
}
44-
45-
4617
def searchbar_context(request):
4718
"""Provide context for the search bar."""
4819
latest_semester = Semester.latest()
4920
recent_semesters = Semester.objects.filter(
5021
number__gte=latest_semester.number - 50 # 50 = 5 years * 10 semesters
5122
).order_by("-number")
5223

53-
# Get saved filters from the session (or use defaults)
54-
saved_filters = request.session.get("search_filters", {})
55-
24+
# No longer use session to store filters
25+
# Empty defaults are provided instead
5626
context = {
5727
"disciplines": Discipline.objects.all().order_by("name"),
5828
"subdepartments": Subdepartment.objects.all().order_by("mnemonic"),
5929
"semesters": recent_semesters,
60-
"selected_disciplines": saved_filters.get("disciplines", []),
61-
"selected_subdepartments": saved_filters.get("subdepartments", []),
62-
"selected_weekdays": saved_filters.get("weekdays", []),
63-
"from_time": saved_filters.get("from_time", ""),
64-
"to_time": saved_filters.get("to_time", ""),
65-
"open_sections": saved_filters.get("open_sections", False),
66-
"min_gpa": saved_filters.get("min_gpa", 0.0),
30+
"selected_disciplines": [],
31+
"selected_subdepartments": [],
32+
"selected_weekdays": [],
33+
"from_time": "",
34+
"to_time": "",
35+
"open_sections": False,
36+
"min_gpa": 0.0,
6737
}
6838
return context

tcf_core/settings/base.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,6 @@
131131
"django.contrib.auth.context_processors.auth",
132132
"django.contrib.messages.context_processors.messages",
133133
"tcf_core.context_processors.base",
134-
"tcf_core.context_processors.history_cookies",
135134
"tcf_core.context_processors.searchbar_context",
136135
],
137136
},

tcf_core/settings/record_middleware.py

Lines changed: 8 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,23 @@
11
"""Middleware for recording cookie information."""
22

3-
import ast
4-
53

64
class RecordMiddleware: # pylint: disable=too-few-public-methods
7-
"""Records information about course section info into cookies."""
5+
"""
6+
Previously recorded course section info into cookies.
7+
Now does nothing as this functionality has been moved to client-side
8+
localStorage to avoid polluting Django sessions.
9+
"""
810

911
def __init__(self, get_response):
1012
self.get_response = get_response
1113

1214
def __call__(self, request):
13-
if "previous_paths_titles" in request.COOKIES:
14-
previous_paths = request.COOKIES["previous_paths"]
15-
# Converts string representation of list into list object
16-
previous_paths = ast.literal_eval(previous_paths)
17-
18-
previous_paths_titles = request.COOKIES["previous_paths_titles"]
19-
# Converts string representation of list into list object
20-
previous_paths_titles = ast.literal_eval(previous_paths_titles)
21-
else:
22-
previous_paths = []
23-
previous_paths_titles = []
24-
15+
# Process the request and get response
2516
response = self.get_response(request)
26-
if (
27-
check_path(request.path)
28-
and request.session.get("instructor_fullname") is not None
29-
):
30-
previous_paths.insert(0, request.build_absolute_uri())
31-
previous_paths = list(dict.fromkeys(previous_paths))
32-
33-
title = request.session.get("course_code")
34-
if request.session.get("instructor_fullname") is not None:
35-
title += " - " + request.session.get("instructor_fullname")
36-
title += " - " + request.session.get("course_title")
37-
38-
previous_paths_titles.insert(0, title)
39-
previous_paths_titles = list(dict.fromkeys(previous_paths_titles))
4017

41-
# Keeps top 10 items in list
42-
if len(previous_paths) > 10:
43-
previous_paths = previous_paths[:10]
44-
previous_paths_titles = previous_paths_titles[:10]
18+
# We no longer set cookies for history tracking
19+
# All history is now managed via localStorage in the browser
4520

46-
response.set_cookie("previous_paths", previous_paths)
47-
response.set_cookie("previous_paths_titles", previous_paths_titles)
4821
return response
4922

5023

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/**
2+
* This file handles the recently viewed courses/instructors using localStorage
3+
* It replaces the server-side session storage with client-side storage
4+
*/
5+
6+
document.addEventListener("DOMContentLoaded", function () {
7+
// Check if we're on a course page by looking for course code and title in the page
8+
saveCourseInfoIfPresent();
9+
});
10+
11+
/**
12+
* Saves course information to localStorage if we're on a course or course-instructor page
13+
*/
14+
function saveCourseInfoIfPresent() {
15+
// Find course information in the page
16+
// This is adapting the session-based logic from browse.py and course_instructor views
17+
const courseCode = document.querySelector(
18+
'meta[name="course-code"]',
19+
)?.content;
20+
const courseTitle = document.querySelector(
21+
'meta[name="course-title"]',
22+
)?.content;
23+
24+
if (!courseTitle) {
25+
return; // Not on a course or club page, or missing required data
26+
}
27+
28+
// Get current URL
29+
const currentUrl = window.location.href;
30+
31+
// Create the title in the same format as the server-side code
32+
33+
let title = "";
34+
35+
if (courseCode) {
36+
title += courseCode + " | ";
37+
}
38+
39+
title += courseTitle;
40+
41+
// Get existing history from localStorage
42+
let previousPaths = [];
43+
let previousPathsTitles = [];
44+
45+
try {
46+
const savedPaths = localStorage.getItem("previous_paths");
47+
const savedTitles = localStorage.getItem("previous_paths_titles");
48+
49+
if (savedPaths && savedTitles) {
50+
previousPaths = JSON.parse(savedPaths);
51+
previousPathsTitles = JSON.parse(savedTitles);
52+
}
53+
} catch (e) {
54+
console.error("Error loading history from localStorage:", e);
55+
}
56+
57+
// Insert at beginning and remove duplicates
58+
// First check if the title already exists in the array
59+
const existingIndex = previousPathsTitles.indexOf(title);
60+
if (existingIndex !== -1) {
61+
// If the title exists, remove both the title and its corresponding path
62+
previousPathsTitles.splice(existingIndex, 1);
63+
previousPaths.splice(existingIndex, 1);
64+
}
65+
66+
// Add the new path and title at the beginning
67+
previousPaths.unshift(currentUrl);
68+
previousPathsTitles.unshift(title);
69+
70+
// Keep only the top 10 items
71+
if (previousPaths.length > 10) {
72+
previousPaths = previousPaths.slice(0, 10);
73+
previousPathsTitles = previousPathsTitles.slice(0, 10);
74+
}
75+
76+
// Save back to localStorage
77+
localStorage.setItem("previous_paths", JSON.stringify(previousPaths));
78+
localStorage.setItem(
79+
"previous_paths_titles",
80+
JSON.stringify(previousPathsTitles),
81+
);
82+
}

0 commit comments

Comments
 (0)