[docs]classSocialAuthHandlingMiddleware:""" Middleware for doing nkdsu-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'))
[docs]classDomainChangeWarningMiddleware:message=mark_safe(""" The new domain name for nkdsu is <strong>requests.nekodesu.radio</strong>. We cannot guarantee that we'll be able to retain control over our original .su domain name. It will redirect as long as possible, but please update your bookmarks. """)query_param='redirected_from'get_response:Callable[[HttpRequest],HttpResponse]def__init__(self,get_response:Callable[[HttpRequest],HttpResponse])->None:self.get_response=get_responsedef__call__(self,request:HttpRequest)->HttpResponse:ifrequest.GET.get(self.query_param):scheme,netloc,path,params,query,fragment=urlparse(request.get_full_path())parsed_query=parse_qs(query)parsed_query.pop(self.query_param)new_query=urlencode(parsed_query)new_url=urlunparse(('','',path,params,new_query,fragment))messages.warning(request,self.message)returnredirect(new_url)returnself.get_response(request)