Skip to content

Commit

Permalink
#132 don't force login unless user specific action takes place (#224)
Browse files Browse the repository at this point in the history
* revamp user login flow
  • Loading branch information
KartikeySharma authored Dec 3, 2024
1 parent c3c1fd7 commit 51947be
Show file tree
Hide file tree
Showing 10 changed files with 703 additions and 511 deletions.
10 changes: 3 additions & 7 deletions src/accounts/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.contrib.auth import views as auth_views
from django.urls import path, include

from .views import UserLoginView, ServiceProviderLoginView, register
from .views import UserLoginView, ServiceProviderLoginView, register, CustomLogoutView
from accounts import views


Expand All @@ -17,12 +17,8 @@
ServiceProviderLoginView.as_view(),
name="service_provider_login",
),
path(
"profile/", views.profile_view, name="profile_view"
), # TODO: what happen when logged in as service provider.
path(
"logout/", auth_views.LogoutView.as_view(next_page="user_login"), name="logout"
), # Logout URL
path("profile/", views.profile_view, name="profile_view"),
path("logout/", CustomLogoutView.as_view(), name="logout"), # Logout URL
path("", include("allauth.urls")), # This allows allauth URLs under /accounts/
path(
"password_reset/",
Expand Down
23 changes: 22 additions & 1 deletion src/accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from axes.models import AccessAttempt
from django.conf import settings
from django.contrib.auth import login
from django.contrib.auth.views import LoginView
from django.contrib.auth.views import LoginView, LogoutView
from django.core.exceptions import PermissionDenied
from django.db import models
from django.shortcuts import get_object_or_404, render, redirect
Expand Down Expand Up @@ -255,6 +255,27 @@ def get_success_url(self):
return reverse_lazy("login")


class CustomLogoutView(LogoutView):
def get_next_page(self):
# Get the default next page
next_page = super().get_next_page()
user = self.request.user

# Check if the user is authenticated
if user.is_authenticated:
if user.user_type == "service_provider":
# Redirect service providers to the service provider login page
next_page = reverse_lazy("service_provider_login")
else:
# Redirect normal users to the home page
next_page = reverse_lazy("home")
else:
# If the user is not authenticated, default to home page
next_page = reverse_lazy("home")

return next_page


# Login selection page view
def login_selection(request):
return render(request, "login_selection.html")
510 changes: 22 additions & 488 deletions src/home/templates/partials/_table.html

Large diffs are not rendered by default.

10 changes: 3 additions & 7 deletions src/home/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,9 @@
from . import views

urlpatterns = [
path("", login_required(views.home_view), name="home"),
path(
"submit_review/", login_required(views.submit_review), name="submit_review"
), # New URL
path(
"get_reviews/<str:service_id>/", views.get_reviews, name="get_reviews"
), # Fix this path
path("", views.home_view, name="home"),
path("submit_review/", login_required(views.submit_review), name="submit_review"),
path("get_reviews/<str:service_id>/", views.get_reviews, name="get_reviews"),
path("toggle_bookmark/", views.toggle_bookmark, name="toggle_bookmark"),
path("delete_review/<str:review_id>/", views.delete_review, name="delete_review"),
path("edit_review/<str:review_id>/", views.edit_review, name="edit_review"),
Expand Down
12 changes: 12 additions & 0 deletions src/home/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ def convert_decimals(obj):

@require_POST
def submit_review(request):
if not request.user.is_authenticated:
return JsonResponse({"error": "Authentication required."}, status=401)

try:
data = json.loads(request.body)
service_id = data.get("service_id")
Expand Down Expand Up @@ -232,6 +235,9 @@ def get_reviews(request, service_id):

@require_POST
def toggle_bookmark(request):
if not request.user.is_authenticated:
return JsonResponse({"error": "Authentication required."}, status=401)

try:
data = json.loads(request.body)
service_id = data.get("service_id")
Expand Down Expand Up @@ -265,6 +271,9 @@ def toggle_bookmark(request):

@require_http_methods(["DELETE"])
def delete_review(request, review_id):
if not request.user.is_authenticated:
return JsonResponse({"error": "Authentication required."}, status=401)

try:
repo = HomeRepository()
data = json.loads(request.body)
Expand All @@ -285,6 +294,9 @@ def delete_review(request, review_id):

@require_http_methods(["PUT"])
def edit_review(request, review_id):
if not request.user.is_authenticated:
return JsonResponse({"error": "Authentication required."}, status=401)

try:
data = json.loads(request.body)
new_rating = data.get("rating")
Expand Down
12 changes: 6 additions & 6 deletions src/public_service_finder/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@

def root_redirect_view(request):
if request.user.is_authenticated:
return (
redirect("services:list")
if request.user.user_type == "service_provider"
else redirect("home")
)
if request.user.user_type == "service_provider":
return redirect("services:list")
else:
return redirect("home")
else:
return redirect("user_login") # Redirect to user login if not logged in
# If the user is not authenticated, redirect to home page
return redirect("home") # Redirect to user login if not logged in


@login_required
Expand Down
2 changes: 1 addition & 1 deletion src/services/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
app_name = "services"

urlpatterns = [
path("", views.service_list, name="list"),
path("list/", views.service_list, name="list"),
path("create/", views.service_create, name="create"),
path("<str:service_id>/edit/", views.service_edit, name="edit"),
path("<str:service_id>/delete/", views.service_delete, name="delete"),
Expand Down
145 changes: 145 additions & 0 deletions src/static/js/home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// home.js

// Get CSRF token from cookie
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.startsWith(name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrfToken = getCookie('csrftoken');

// Function to show the login modal
function showLoginModal() {
const loginModal = document.getElementById('loginModal');
if (loginModal) {
loginModal.classList.remove('hidden');
}
}

// Function to hide the login modal
function hideLoginModal() {
const loginModal = document.getElementById('loginModal');
if (loginModal) {
loginModal.classList.add('hidden');
}
}

// Event listener for DOM content loaded
document.addEventListener('DOMContentLoaded', function() {
// Handle login form submission
const loginForm = document.getElementById('loginForm');
if (loginForm) {
loginForm.addEventListener('submit', function(event) {
event.preventDefault();

const username = document.getElementById('username').value;
const password = document.getElementById('password').value;

// Perform AJAX login
fetch('/ajax_login/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({
username: username,
password: password,
}),
})
.then(response => {
if (response.ok) {
hideLoginModal();
// Optionally refresh the page or update the UI to reflect the logged-in state
location.reload();
} else {
return response.json().then(data => {
alert(data.error || 'Login failed. Please try again.');
});
}
})
.catch(error => {
console.error('Login error:', error);
alert('An error occurred during login. Please try again.');
});
});
}

// Handle cancel button
const cancelLoginBtn = document.getElementById('cancelLogin');
if (cancelLoginBtn) {
cancelLoginBtn.addEventListener('click', function() {
hideLoginModal();
});
}

// Handle close button
const closeLoginModalBtn = document.getElementById('closeLoginModal');
if (closeLoginModalBtn) {
closeLoginModalBtn.addEventListener('click', function() {
hideLoginModal();
});
}

// Example: Handle user-specific actions (e.g., bookmarking)
const bookmarkButtons = document.querySelectorAll('.bookmark-btn');
bookmarkButtons.forEach(button => {
button.addEventListener('click', function() {
const serviceId = this.dataset.serviceId;
const action = this.dataset.action; // 'add' or 'remove'

toggleBookmark(serviceId, action, this);
});
});

// Function to toggle bookmark
function toggleBookmark(serviceId, action, button) {
fetch('/toggle_bookmark/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({
service_id: serviceId,
action: action,
}),
})
.then(response => {
if (response.status === 401) {
// User is not authenticated, show login modal
showLoginModal();
} else if (response.ok) {
return response.json().then(data => {
// Update bookmark UI
if (data.action === 'added') {
button.dataset.action = 'remove';
button.textContent = 'Unbookmark';
} else if (data.action === 'removed') {
button.dataset.action = 'add';
button.textContent = 'Bookmark';
}
});
} else {
return response.json().then(data => {
alert(data.error || 'Failed to toggle bookmark.');
});
}
})
.catch(error => {
console.error('Toggle bookmark error:', error);
alert('An error occurred while toggling the bookmark.');
});
}
});
2 changes: 1 addition & 1 deletion src/static/js/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ document.addEventListener('DOMContentLoaded', () => {
alert(data.error || 'Failed to toggle bookmark.');
} else {
if (action === 'remove') {
const serviceCard = this.closest('.bg-gray-50');
const serviceCard = this.closest('.bg-gray-700');
serviceCard.remove();

// Update counters after removing bookmark
Expand Down
Loading

0 comments on commit 51947be

Please sign in to comment.