from django.http import HttpResponseRedirect, QueryDict from django.urls.exceptions import Resolver404 from django.shortcuts import render from neluser.models import NelUser from django.urls import reverse, resolve from django.conf import settings def is_link_legit(url): try: resolve(url) except Resolver404: return False return True def is_nsfw_allowed(request): if isinstance(request.user, NelUser): if request.user.nsfw_allowed: return True s = request.COOKIES.get(settings.KHAGANAT_NSFW_NAME) or '' return s.lower() in settings.KHAGANAT_NSFW_OK def disable_view(request, max_age): try: max_age = int(max_age) or None except ValueError: max_age = None next_url = QueryDict(request.META.get('QUERY_STRING')).get('next') or '/' if not is_link_legit(next_url): next_url = '/' response = HttpResponseRedirect(next_url) if isinstance(request.user, NelUser) and not max_age: request.user.nsfw_allowed = True request.user.save() else: response.set_cookie( settings.KHAGANAT_NSFW_NAME, 'true', max_age=max_age ) return response def warn_view(request): next_url = QueryDict(request.META.get('QUERY_STRING')).get('next') or '/' if not is_link_legit(next_url): next_url = '/' context = { 'next_url': next_url, 'is_authenticated': request.user.is_authenticated, } return render(request, 'neluser/nsfw.html', context=context) def redirect(request): dest = '{to_url}?next={next_url}'.format( to_url=reverse(warn_view), next_url=request.get_full_path() ) return HttpResponseRedirect(dest)