예제 #1
0
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
예제 #2
0
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)
예제 #3
0
    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)
예제 #4
0
 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
예제 #5
0
    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)
예제 #6
0
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
예제 #7
0
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
예제 #8
0
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
예제 #9
0
    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:
예제 #10
0
파일: views.py 프로젝트: projectpai/paipass
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'
예제 #11
0
 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)
예제 #12
0
class ProductViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = import_callable(settings.ZCONNECT_PRODUCT_SERIALIZER)
    permission_classes = [
        IsAdminOrReadOnly,
    ]
예제 #13
0
 def setup(self):
     self.product_serializer = import_callable(
         settings.ZCONNECT_PRODUCT_SERIALIZER)