[docs]classSocialAuthHandlingMiddleware:""" Middleware for doing nkd.su-specific workarounds for unwanted Python Social Auth behaviour. """prefix:strget_response:Callable[[HttpRequest],HttpResponse]def__init__(self,get_response:Callable[[HttpRequest],HttpResponse])->None:# establish what the base social_auth URL is, so that we can only# affect social-auth URLsbegin_url=reverse('social:begin',kwargs={'backend':'twitter'})suffix='login/twitter/'assertbegin_url.endswith(suffix)# make sureself.prefix=begin_url[:-len(suffix)]assert(self.prefix=='/s/'),self.prefix# make sure both the derived and expected values are the sameself.get_response=get_responsedef__call__(self,request:HttpRequest)->HttpResponse:returnself.get_response(request)
[docs]defprocess_view(self,request:HttpRequest,view_func:Callable,view_args:Sequence[Any],view_kwargs:dict[str,Any],)->HttpResponse:ifnotrequest.path.startswith(self.prefix):# this is not a social auth request. do nothingreturnview_func(request,*view_args,**view_kwargs)# since we're catching exceptions, we might want to manually roll-back database transactions heretry:returnview_func(request,*view_args,**view_kwargs)exceptDoNotAuthThroughTwitterPleasease:messages.warning(request,e.msg)exceptNotAllowedToDisconnect:messages.warning(request,'you have to set a password or you will not be able to log back in',)ifrequest.user.is_authenticated:returnredirect(reverse('vote:profiles:profile',kwargs={'username':request.user.username},))else:returnredirect(reverse('login'))