views.py 1.92 KB
Newer Older
1
2
3
"""
go/views.py

David Haynes's avatar
David Haynes committed
4
5
6
The functions that handle a request to a given URL. Get some data, manipulate
it, and return a rendered template.
"""
David Haynes's avatar
David Haynes committed
7
8
9
# Python stdlib imports
from datetime import timedelta

10
# Django Imports
11
from django.conf import settings
David Haynes's avatar
David Haynes committed
12
13
14
15
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.exceptions import PermissionDenied  # ValidationError
from django.core.mail import EmailMessage, send_mail
16
from django.http import HttpResponseServerError  # Http404
17
from django.http import HttpResponseRedirect
David Haynes's avatar
David Haynes committed
18
from django.shortcuts import get_object_or_404, redirect, render
19
from django.utils import timezone
David Haynes's avatar
David Haynes committed
20
# Other imports
21
from ratelimit.decorators import ratelimit
22

23
# App Imports
David Haynes's avatar
David Haynes committed
24
from .forms import EditForm, SignupForm, URLForm
25
from .models import URL, RegisteredUser
David Haynes's avatar
David Haynes committed
26

David Haynes's avatar
David Haynes committed
27

28
29
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
David Haynes's avatar
David Haynes committed
30
from rest_framework import permissions
David Haynes's avatar
David Haynes committed
31
from .serializers import URLSerializer
32

David Haynes's avatar
David Haynes committed
33
34
35
36
class URLPermission(permissions.BasePermission):
    message = "You do not have the necessary approvals to perform that action."
    def has_permission(self, request, view):
        return request.user.registereduser.approved or request.user.is_staff
37

David Haynes's avatar
David Haynes committed
38
    def has_object_permission(self, request, view, obj):
David Haynes's avatar
David Haynes committed
39
        return obj.owner == request.user.registereduser or request.user.is_staff
40

David Haynes's avatar
David Haynes committed
41
class URLViewSet(viewsets.ModelViewSet):
42
    """
David Haynes's avatar
David Haynes committed
43
    API endpoint that handles creation/read/update/deletion of URL objects.
44
    """
David Haynes's avatar
David Haynes committed
45
    serializer_class = URLSerializer
David Haynes's avatar
David Haynes committed
46
    permission_classes = (URLPermission,)
47
    lookup_field = 'short'
David Haynes's avatar
David Haynes committed
48
49
50
51
52
53
54
55
56

    def get_queryset(self):
        if not self.request.user.is_staff:
            return URL.objects.filter(owner=self.request.user.registereduser)
        else:
            return URL.objects.all()

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user.registereduser)