first commit
This commit is contained in:
54
accounts/middleware.py
Normal file
54
accounts/middleware.py
Normal file
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
Custom middleware for social authentication.
|
||||
"""
|
||||
|
||||
from django.contrib.auth import logout
|
||||
from django.http import HttpResponseForbidden, JsonResponse
|
||||
|
||||
|
||||
class SocialAuthExceptionMiddleware:
|
||||
"""
|
||||
Middleware to handle social auth exceptions and redirect properly.
|
||||
"""
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
response = self.get_response(request)
|
||||
return response
|
||||
|
||||
def process_exception(self, request, exception):
|
||||
"""Handle social auth exceptions."""
|
||||
from social_core.exceptions import AuthException
|
||||
from django.http import HttpResponseRedirect
|
||||
|
||||
if isinstance(exception, AuthException):
|
||||
return HttpResponseRedirect(f'/api/v1/auth/social/error/?error={str(exception)}')
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class AccountExpirationMiddleware:
|
||||
"""
|
||||
Deactivate users automatically when their access period has expired.
|
||||
"""
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
user = getattr(request, 'user', None)
|
||||
|
||||
if user and user.is_authenticated and hasattr(user, 'deactivate_if_expired'):
|
||||
if user.deactivate_if_expired():
|
||||
logout(request)
|
||||
if request.path.startswith('/api/'):
|
||||
return JsonResponse(
|
||||
{'detail': 'Account expired. Please contact an administrator.'},
|
||||
status=403,
|
||||
)
|
||||
return HttpResponseForbidden('Account expired. Please contact an administrator.')
|
||||
|
||||
return self.get_response(request)
|
||||
|
||||
Reference in New Issue
Block a user