This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hi everyone, I need some help. I just added a middleware to redirect the AnonymousUser to login page when they wants to buy a product.
I integrated stripe, when they click to checkout button they sent a post reqeust to /stripe/checkout/.
Here is my code:
# middleware
from django.shortcuts import redirect
from django.urls import reverse
class PaymentAuthenticationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
protected_urls = [
'/stripe/checkout/',
]
if request.path == reverse('account_login'):
return self.get_response(request)
if not request.user.is_authenticated:
for url in protected_urls:
if request.path.startswith(url):
return redirect(reverse('account_login'))
return self.get_response(request)
# settings
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware", # Locale
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"allauth.account.middleware.AccountMiddleware",
"_videos.middleware.MembershipAccessMiddleware",
'_accounts.middlewares.anon_user_preferred_currency.PreferredCurrencyForAnonymousUserMiddleware',
'_accounts.middlewares.authentication.PaymentAuthenticationMiddleware',
]
# nginx logs
024-09-20 21:52:50 192.168.65.1 - - [20/Sep/2024:19:52:50 0000] "POST /stripe/checkout/ HTTP/1.1" 302 0 "http://127.0.0.1/products/1/detail" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36" "-"
2024-09-20 21:52:50 192.168.65.1 - - [20/Sep/2024:19:52:50 0000] "GET /accounts/login/ HTTP/1.1" 200 6305 "http://127.0.0.1/products/1/detail" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36" "-"
When I debug, it successfully executes the redirect command, the response code is 302, however it does nothing.
I am confused, have anyone got similar thing before?
Edit: it is resolved, the problem was stripe checkout request was expecting a response back, however the middleware was cutting it. I decided to change logic to preventDefault for the button and redirect notauthenticated user to login page in the js script.
Subreddit
Post Details
- Posted
- 4 months ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/django/comm...