khaganat-web/neluser/nsfw.py
2018-06-02 21:43:23 +02:00

79 lines
2.3 KiB
Python

from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseRedirect, QueryDict
from django.template.loader import render_to_string
from django.urls.exceptions import Resolver404
from django.shortcuts import render
from django.contrib import messages
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):
if isinstance(request.user, NelUser):
request.user.nsfw_allowed = False
request.user.save()
next_url = reverse('index')
response = HttpResponseRedirect(next_url)
response.delete_cookie(settings.KHAGANAT_NSFW_NAME)
return response
def enable_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)
def alert(request):
msg = render_to_string('neluser/nsfw_message.html')
messages.info(request, msg, extra_tags='safe')