Refactor and remove thaliawebsite views

parent ecf7b09a
"""Tests for things provided by this module"""
import doctest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase, override_settings
from django.test import TestCase
from activemembers.models import Committee, MemberGroupMembership, Society
from members.models import Profile
from thaliawebsite.templatetags import bleach_tags
from thaliawebsite import sitemaps
from thaliawebsite.templatetags import bleach_tags
def load_tests(_loader, tests, _ignore):
......@@ -21,159 +17,6 @@ def load_tests(_loader, tests, _ignore):
return tests
class WikiLoginTestCase(TestCase):
"""Tests event registrations"""
fixtures = ['member_groups.json']
@classmethod
def setUpTestData(cls):
cls.user = get_user_model().objects.create_user(
username='testuser',
first_name='first',
last_name='last_name',
email='foo@bar.com',
password='top secret')
def test_login_get_request_denied(self):
"""GET shouldn't work for the wiki API"""
response = self.client.get('/api/wikilogin')
self.assertEqual(response.status_code, 405)
@override_settings(WIKI_API_KEY='wrongkey')
def test_login_wrong_apikey(self):
"""API key should be verified"""
response = self.client.post('/api/wikilogin',
{'apikey': 'rightkey',
'username': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['status'], 'error')
@override_settings(WIKI_API_KEY='key')
def test_login(self):
"""Test a correct log in attempt"""
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'user': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {'admin': False,
'committees': [],
'msg': 'Logged in',
'mail': 'foo@bar.com',
'name': 'first last_name',
'status': 'ok'})
@override_settings(WIKI_API_KEY='key')
def test_login_with_profile(self):
"""A user that has a profile should be able to log in"""
Profile.objects.create(
user=self.user,
student_number='s1234567'
)
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'user': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {'admin': False,
'committees': [],
'msg': 'Logged in',
'mail': 'foo@bar.com',
'name': 'first last_name',
'status': 'ok'})
@override_settings(WIKI_API_KEY='key')
def test_login_with_committee_group_membership(self):
"""A user that has a profile should be able to log in"""
committee = Committee.objects.get(pk=1)
MemberGroupMembership.objects.create(
member=self.user,
group=committee
)
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'user': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {'admin': False,
'committees': ['testcie1:ns'],
'msg': 'Logged in',
'mail': 'foo@bar.com',
'name': 'first last_name',
'status': 'ok'})
@override_settings(WIKI_API_KEY='key')
def test_login_with_society_group_membership(self):
"""A user that has a profile should be able to log in"""
society = Society.objects.get(pk=4)
MemberGroupMembership.objects.create(
member=self.user,
group=society
)
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'user': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {'admin': False,
'committees': [],
'msg': 'Logged in',
'mail': 'foo@bar.com',
'name': 'first last_name',
'status': 'ok'})
@override_settings(WIKI_API_KEY='key')
def test_board_permission(self):
"""The board should get access to the board wiki"""
self.user.user_permissions.add(
Permission.objects.get(codename='board_wiki'))
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'user': 'testuser',
'password': 'top secret'})
self.assertEqual(response.json(), {'admin': False,
'committees': ['bestuur'],
'msg': 'Logged in',
'mail': 'foo@bar.com',
'name': 'first last_name',
'status': 'ok'})
self.assertEqual(response.status_code, 200)
@override_settings(WIKI_API_KEY='key')
def test_wrongargs(self):
"""Check that the arguments are correct"""
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'username': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['status'], 'error')
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'user': 'testuser'})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['status'], 'error')
@override_settings(WIKI_API_KEY='key')
def test_login_wrong_password(self):
"""Check that the password is actually checked"""
response = self.client.post('/api/wikilogin',
{'apikey': 'key',
'user': 'testuser',
'password': 'wrong secret'})
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['status'], 'error')
class SitemapTest(TestCase):
fixtures = ['members.json', 'member_groups.json']
......
......@@ -33,12 +33,12 @@ from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import LoginView
from django.contrib.sitemaps.views import sitemap
from django.views.generic import TemplateView
from django.urls import path
from django.views.i18n import JavaScriptCatalog
import members
from activemembers.sitemaps import sitemap as activemembers_sitemap
from documents.sitemaps import sitemap as documents_sitemap
from events.sitemaps import sitemap as events_sitemap
......@@ -48,8 +48,14 @@ from members.views import ObtainThaliaAuthToken
from partners.sitemaps import sitemap as partners_sitemap
from thabloid.sitemaps import sitemap as thabloid_sitemap
from thaliawebsite.forms import AuthenticationForm
from thaliawebsite.views import (
PrivacyPolicyView, EventTermsView,
SiblingAssociationsView, TestCrashView,
ContactView, IndexView,
BecomeActiveView,
StyleGuideView
)
from utils.media.views import (generate_thumbnail, private_media)
from . import views
from .sitemaps import StaticViewSitemap
__all__ = ['urlpatterns']
......@@ -66,34 +72,31 @@ THALIA_SITEMAP.update(events_sitemap)
# pragma pylint: disable=line-too-long
urlpatterns = [ # pylint: disable=invalid-name
url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
url(r'^error/', TemplateView.as_view(template_name='403.html'), name='error'),
url(r'^privacy-policy/', TemplateView.as_view(template_name='singlepages/privacy_policy.html'), name='privacy-policy'),
url(r'^event-registration-terms/', TemplateView.as_view(template_name='singlepages/event_registration_terms.html'), name='event-registration-terms'),
url(r'^admin/', admin.site.urls),
url(r'^alumni/$', AlumniEventsView.as_view(), name='alumni'),
path('', IndexView.as_view(), name='index'),
path('privacy-policy/', PrivacyPolicyView.as_view(), name='privacy-policy'),
path('event-registration-terms/', EventTermsView.as_view(), name='event-registration-terms'),
path('alumni/', AlumniEventsView.as_view(), name='alumni'),
url(r'^registration/', include('registrations.urls')),
url(r'^events/', include('events.urls')),
url(r'^pizzas/', include('pizzas.urls')),
url(r'^newsletters/', include('newsletters.urls')),
url(r'^nieuwsbrief/', include('newsletters.urls', namespace='newsletters-legacy'),), # for legacy reasons
url(r'^', include([ # 'association' menu
url(r'^', include('activemembers.urls')),
url(r'^merchandise/', include('merchandise.urls')),
url(r'^documents/', include('documents.urls')),
url(r'^sibling-associations', TemplateView.as_view(template_name='singlepages/sibling_associations.html'), name='sibling-associations'),
path('sibling-associations/', SiblingAssociationsView.as_view(), name='sibling-associations'),
url(r'^thabloid/', include('thabloid.urls')),
])),
url(r'^', include([ # 'for members' menu
url(r'^become-active/', login_required(TemplateView.as_view(template_name='singlepages/become_active.html')), name='become-active'),
path('become-active/', BecomeActiveView.as_view(), name='become-active'),
url(r'^photos/', include('photos.urls')),
url(r'^styleguide/$', views.styleguide, name='styleguide'),
url(r'^styleguide/file/(?P<filename>[\w\-_\.]+)$', views.styleguide_file, name='styleguide-file'),
path('statistics/', members.views.statistics, name='statistics'),
path('styleguide/', StyleGuideView.as_view(), name='styleguide'),
])),
url(r'^career/', include('partners.urls')),
url(r'^contact$', TemplateView.as_view(template_name='singlepages/contact.html'), name='contact'),
url(r'^contact$', ContactView.as_view(), name='contact'),
url(r'^api/', include([
url(r'wikilogin', views.wiki_login),
url(r'^v1/', include([
url(r'^token-auth', ObtainThaliaAuthToken.as_view()),
url(r'^', include('activemembers.api.urls')),
......@@ -122,7 +125,7 @@ urlpatterns = [ # pylint: disable=invalid-name
# Javascript translation catalog
url(r'jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
# Provide something to test error handling. Limited to admins.
url(r'crash/$', views.crash),
path('crash/', TestCrashView.as_view()),
# Custom media paths
url(r'^media/generate-thumbnail/(?P<request_path>.*)', generate_thumbnail, name='generate-thumbnail'),
url(r'^media/private/(?P<request_path>.*)$', private_media, name='private-media'),
......
"""General views for the website"""
import os.path
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.http import (HttpResponseBadRequest, Http404,
HttpResponseForbidden, JsonResponse)
from django.shortcuts import render
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.debug import (sensitive_variables,
sensitive_post_parameters)
from django.views.decorators.http import require_POST
from sendfile import sendfile
@login_required
def styleguide(request):
from django.http import (HttpResponseForbidden, HttpResponse)
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.views.generic.base import View
class IndexView(TemplateView):
template_name = 'index.html'
@method_decorator(login_required, 'dispatch')
class StyleGuideView(TemplateView):
"""Static page with the style guide"""
return render(request, 'singlepages/styleguide.html')
@sensitive_variables()
@sensitive_post_parameters()
@require_POST
@csrf_exempt
def wiki_login(request):
"""
Provides an API endpoint to the wiki to authenticate Thalia members
"""
apikey = request.POST.get('apikey')
user = request.POST.get('user')
password = request.POST.get('password')
if apikey != settings.WIKI_API_KEY:
return HttpResponseForbidden('{"status":"error","msg":"invalid key"}',
content_type='application/json')
if user is None or password is None:
return HttpResponseBadRequest(
'{"status":"error","msg":"Missing username or password"}',
content_type='application/json')
user = authenticate(username=user, password=password)
if user is not None:
memberships = [
x.group.committee.wiki_namespace for x in
user.membergroupmembership_set
.exclude(until__lt=timezone.now().date())
.select_related('group')
if hasattr(x.group, 'committee') and
x.group.committee.wiki_namespace is not None]
if user.has_perm('activemembers.board_wiki'):
memberships.append('bestuur')
return JsonResponse({'status': 'ok',
'name': user.get_full_name(),
'mail': user.email,
'admin': user.is_superuser,
'msg': 'Logged in',
'committees': memberships})
return JsonResponse({'status': 'error',
'msg': 'Authentication Failed'},
status=403)
@login_required
def styleguide_file(request, filename):
"""Obtain the styleguide files"""
path = os.path.join(settings.MEDIA_ROOT, 'styleguide')
filepath = os.path.join(path, filename)
if not (os.path.commonpath([path, filepath]) == path and
os.path.isfile(filepath)):
raise Http404("File not found.")
return sendfile(request, filepath, attachment=True)
@staff_member_required
def crash(request):
"""Intentionally crash to test the error handling."""
if not request.user.is_superuser:
return HttpResponseForbidden("This is not for you")
raise Exception("Test exception")
template_name = 'singlepages/styleguide.html'
@method_decorator(login_required, 'dispatch')
class BecomeActiveView(TemplateView):
"""Static page with info about becoming an active member"""
template_name = 'singlepages/become_active.html'
class PrivacyPolicyView(TemplateView):
"""Static page with the privacy policy"""
template_name = 'singlepages/privacy_policy.html'
class EventTermsView(TemplateView):
"""Static page with the event registration terms"""
template_name = 'singlepages/event_registration_terms.html'
class SiblingAssociationsView(TemplateView):
"""Static page with the sibling associations"""
template_name = 'singlepages/sibling_associations.html'
class ContactView(TemplateView):
"""Static page with contact info"""
template_name = 'singlepages/contact.html'
@method_decorator(staff_member_required, 'dispatch')
class TestCrashView(View):
"""Test view to intentionally crash to test the error handling."""
def dispatch(self, request, *args, **kwargs) -> HttpResponse:
if not request.user.is_superuser:
return HttpResponseForbidden("This is not for you")
raise Exception("Test exception")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment