def jwt_create_token(token_model, user, serializer): """Create the token to return Token from simplejwt overrides __str__ which calls jwt.encode. - This function returns the instance, then the serializer calls __str__ when it's serializing it. This function creates the instance, then injects some extra fields for when it gets serialized Args: token_model: REST_AUTH_TOKEN_MODEL user: logged in user serializer: REST_AUTH_SERIALIZERS::TOKEN_SERIALIZER Returns: dict: Token instance. """ # FIXME # Fork simplejwt or create a new TokenBackend class - might just have to # monkeypatch it in simplejwt/state.py token = token_model.for_user(user) serializer = import_callable(settings.ZCONNECT_JWT_SERIALIZER) extra_user_data = serializer(user).data # no update() method for k, v in extra_user_data.items(): token[k] = v logger.debug("Claims: %s", token.payload) return token
def register_permission_classes(): permission_classes = [ AllowAny, ] for klass in getattr(settings, 'REST_AUTH_REGISTER_PERMISSION_CLASSES', tuple()): permission_classes.append(import_callable(klass)) return tuple(permission_classes)
def pre_save(cls, sender, document, **kwargs): # pylint: disable=unused-argument try: strategy_hook = import_callable(document.strategy_class) except ImportError as e: raise django.core.exceptions.ValidationError( "Invalid strategy class '{}'".format( document.strategy_class)) from e strategy_hook.on_create(document)
def get_user(self, obj): """ Required to allow using custom USER_DETAILS_SERIALIZER in JWTSerializer. Defining it here to avoid circular imports """ rest_auth_serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {}) JWTUserDetailsSerializer = import_callable( rest_auth_serializers.get('USER_DETAILS_SERIALIZER', UserDetailsSerializer) ) user_data = JWTUserDetailsSerializer(obj['user'], context=self.context).data return user_data
def handle(self, *args, **options): device_serializer = import_callable(settings.ZCONNECT_DEVICE_SERIALIZER) product_id = options['product'] product = Product.objects.get(pk=product_id) devices = [_Device(product=product) for _ in range(0, options['number'])] for d in devices: d.save() serialized_devices = [device_serializer(d).data for d in devices] self.handle_output(serialized_devices, **options)
def device_to_dict(device): """convert device to dictionary note: if the keys are different then the error message given by tavern might be a bit confusing. comparing a dict to an ordereddict (as returned by the serializer) works, but if a key is different then it will also complain about the types being different """ serializer = import_callable(settings.ZCONNECT_DEVICE_SERIALIZER) dumped = serializer(instance=device).data return dumped
def jwt_response_payload_handler(token, user=None, request=None): """ Returns the response data for both the login and refresh views. Override to return a custom response such as including the serialized representation of the User. Example: def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data } """ serializers = getattr(settings, "REST_AUTH_SERIALIZERS", {}) serializer_class = import_callable( serializers.get("JWT_SERIALIZER", DefaultJWTSerializer)) data = {"user": user, "token": token} serializer = serializer_class(instance=data, context={"request": request}) return serializer.data
def get_product_state_serializer(product): """Get serializer that can be used to validate a device's state update messages. See documentation for get_state_serializer_cls for information on args etc. """ # Use this by default state_serializer_cls = serializers.JSONField if product: serializer_name = product.state_serializer_name if not serializer_name: logger.warning("Product passed with no explicit state_serializer_name - using JSONField which will match ANY data") else: try: state_serializer_cls = import_callable(serializer_name) except (ValueError,ImportError) as e: raise exceptions.BadMessageSchemaError("Error loading schema verifier from '{}'".format(serializer_name)) from e else: logger.info("No product - using JSONField to validate input") return state_serializer_cls
user_permissions = CustomPermissionsSerializer(many=True) """ User model w/o password """ class Meta: model = CustomUser fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'user_permissions') read_only_fields = ('email', 'user_permissions') # This is to allow you to override the UserDetailsSerializer at any time. # If you're sure you won't, you can skip this and use DefaultUserDetailsSerializer directly rest_auth_serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {}) UserDetailsSerializer = import_callable( rest_auth_serializers.get('USER_DETAILS_SERIALIZER', CustomUserDetailsSerializer)) class CustomTokenSerializer(serializers.ModelSerializer): user = UserDetailsSerializer(read_only=True) class Meta: model = TokenModel fields = ('key', 'user') class QuestionSerializer(serializers.ModelSerializer): id = serializers.ModelField(model_field=Question()._meta.get_field('id')) class Meta:
else: import boto3 as aws_api ''' # Local from .serializers import (RegisterSerializer, LoginSerializer, ResendVerificationEmailSerializer, UpdateProfileSerializer, ) from oauth2.oauth2 import scope_expression_to_symbols from oauth2_provider.models import (get_access_token_model, get_application_model) serializers = getattr(settings, 'REST_AUTH_REGISTER_SERIALIZERS', {}) RegisterSerializer = import_callable( serializers.get('REGISTER_SERIALIZER', RegisterSerializer)) sensitive_post_parameters_m = method_decorator( sensitive_post_parameters('password1', 'password2') ) def register_permission_classes(): permission_classes = [AllowAny, ] for klass in getattr(settings, 'REST_AUTH_REGISTER_PERMISSION_CLASSES', tuple()): permission_classes.append(import_callable(klass)) return tuple(permission_classes) def get_relevant_models(request, **kwargs): namespace = 'catena'
def get_serializer_class(self): if self.request.user.is_staff or self.request.user.is_superuser: if self.request.method == 'POST': return CreateUserSerializer return import_callable(settings.ZCONNECT_ADMIN_USER_SERIALIZER) return import_callable(settings.ZCONNECT_USER_SERIALIZER)
class ProductViewSet(NestedViewSetMixin, viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = import_callable(settings.ZCONNECT_PRODUCT_SERIALIZER) permission_classes = [ IsAdminOrReadOnly, ]
def setup(self): self.product_serializer = import_callable( settings.ZCONNECT_PRODUCT_SERIALIZER)