uncloud-mravi/uncloud_django_based/uncloud/uncloud_auth/views.py

42 lines
1.6 KiB
Python
Raw Normal View History

2020-03-18 13:36:40 +00:00
from rest_framework import viewsets, permissions, status
from .serializers import *
from django_auth_ldap.backend import LDAPBackend
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import mixins
2020-03-18 13:36:40 +00:00
class UserViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
permission_classes = [permissions.IsAuthenticated]
2020-03-18 13:36:40 +00:00
serializer_class = UserSerializer
def list(self, request, format=None):
# This is a bit stupid: we have a user, we create a queryset by
# matching on the username. But I don't know a "nicer" way.
# Nico, 2020-03-18
user = get_user_model().objects.get(
username=self.request.user.username)
serializer = self.get_serializer(user, context = {'request': request})
return Response(serializer.data)
class AdminUserViewSet(viewsets.ReadOnlyModelViewSet):
# FIXME: make this admin
2020-03-18 13:36:40 +00:00
permission_classes = [permissions.IsAuthenticated]
def get_serializer_class(self):
if self.action == 'import_from_ldap':
return ImportUserSerializer
2020-03-18 13:36:40 +00:00
else:
return UserSerializer
def get_queryset(self):
return get_user_model().objects.all()
@action(detail=False, methods=['post'], url_path='import_from_ldap')
def import_from_ldap(self, request, pk=None):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
ldap_username = serializer.validated_data.pop("username")
user = LDAPBackend().populate_user(ldap_username)
2020-03-18 13:36:40 +00:00
return Response(UserSerializer(user, context = {'request': request}).data)