2019-08-21 12:27:21 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
|
2023-10-10 09:52:52 +00:00
|
|
|
from django.utils.translation import gettext as _
|
|
|
|
from rest_framework import serializers
|
|
|
|
from rest_framework.response import Response
|
2023-08-08 02:16:23 +00:00
|
|
|
|
2023-10-12 08:17:32 +00:00
|
|
|
from authentication.permissions import UserConfirmation
|
2023-10-10 09:52:52 +00:00
|
|
|
from common.api import JMSModelViewSet
|
2022-04-19 11:10:36 +00:00
|
|
|
from rbac.permissions import RBACPermission
|
2023-10-10 09:52:52 +00:00
|
|
|
from ..const import ConfirmType
|
2023-08-08 02:16:23 +00:00
|
|
|
from ..serializers import AccessKeySerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
|
2023-10-10 09:52:52 +00:00
|
|
|
class AccessKeyViewSet(JMSModelViewSet):
|
2023-08-08 02:16:23 +00:00
|
|
|
serializer_class = AccessKeySerializer
|
2023-10-10 09:52:52 +00:00
|
|
|
search_fields = ['^id']
|
2022-04-19 11:10:36 +00:00
|
|
|
permission_classes = [RBACPermission]
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
return self.request.user.access_keys.all()
|
|
|
|
|
2023-10-10 09:52:52 +00:00
|
|
|
def get_permissions(self):
|
|
|
|
if self.is_swagger_request():
|
|
|
|
return super().get_permissions()
|
|
|
|
|
|
|
|
if self.action == 'create':
|
|
|
|
self.permission_classes = [
|
|
|
|
RBACPermission, UserConfirmation.require(ConfirmType.PASSWORD)
|
|
|
|
]
|
|
|
|
return super().get_permissions()
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def perform_create(self, serializer):
|
|
|
|
user = self.request.user
|
2023-10-10 09:52:52 +00:00
|
|
|
if user.access_keys.count() >= 10:
|
|
|
|
raise serializers.ValidationError(_('Access keys can be created at most 10'))
|
|
|
|
key = user.create_access_key()
|
|
|
|
return key
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
serializer = self.get_serializer(data=request.data)
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
key = self.perform_create(serializer)
|
|
|
|
return Response({'secret': key.secret, 'id': key.id}, status=201)
|