from django.contrib.auth import logout from django.http import JsonResponse from django.middleware.csrf import get_token from django.shortcuts import redirect from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from gregui import mailutils def get_csrf(request): response = JsonResponse({"detail": "CSRF cookie set"}) response["X-CSRFToken"] = get_token(request) return response def logout_view(request): if not request.user.is_authenticated: return JsonResponse({"detail": "You're not logged in."}, status=400) logout(request) return JsonResponse({"detail": "Successfully logged out."}) def login_view(request): """ View for pointing login links to Sesame will take the query string automatically and use it to create a session for the user, so all this needs to do is redirect the user wherever they're supposed to go after successfully logging in. """ # TODO: redirect to whatever path the frontend ends up living at (prob '/') return redirect("/api/ui/v1/whoami/") def send_test_email(request): mailutils.send_registration_mail("test@example.no", "Foo Bar") return JsonResponse({"detail": "Created task to send test mail."}) class SessionView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] @staticmethod # pylint: disable=W0622 def get(request, format=None): return JsonResponse({"isAuthenticated": True}) class WhoAmIView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] @staticmethod # pylint: disable=W0622 def get(request, format=None): return JsonResponse({"username": request.user.username})