Y
Y
yuki2022-02-11 20:45:38
Python
yuki, 2022-02-11 20:45:38

AnonymousUser on every request (simplejwt)?

I have an extended user model

class ExtUser(AbstractUser):
    avatar = models.ImageField(upload_to=upload_to, verbose_name="Аватар", blank=True, null=True, default=None)
    discord = models.CharField(max_length=32, verbose_name="Discord", blank=True, null=True, default=None)
    skype = models.CharField(max_length=64, verbose_name="Skype", blank=True, null=True, default=None)
    REQUIRED_FIELDS = ["password", "email"]
    USERNAME_FIELD = "username"


Settings.py contains all data
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    'SEARCH_PARAM': 'q',
    'ORDERING_PARAM': 'ordered_by',
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
    ],
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.OrderingFilter',
    ],
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=10) if DEBUG else timedelta(minutes=10),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=30) if DEBUG else timedelta(days=5),
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',)
}

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'drf_yasg',
    'rest_framework',
    'django_filters',
    'corsheaders',
    'ident_system.apps.IdentSystemConfig',
    'tags.apps.TagsConfig',
    'user_space.apps.UserSpaceConfig',
    'courses.apps.CoursesConfig',
    'rest_framework_simplejwt',
]

AUTH_USER_MODEL = "user_space.ExtUser"


In views.py where the reg and authorization also seem to be all right
class SignUp(CreateAPIView):
    queryset = User.objects.all()
    permission_classes = [permissions.AllowAny]
    serializer_class = SignUpSerializer

    def post(self, request, *args, **kwargs):
        try:
            user = User.objects.create_user(**request.data)
            group = Group.objects.get(name="user")
            group.user_set.add(user)
        except Exception as e:
            return Response({"detail": "Пользователь с таким именем уже существует"}, status=status.HTTP_409_CONFLICT)
        return Response(status=status.HTTP_201_CREATED)


class JWTLogIn(TokenObtainPairView):
    serializer_class = ExtendedTokenSerializer
    permission_classes = [permissions.AllowAny]


Serializer to token
class ExtendedTokenSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    def validate(self, attrs):
        data = super().validate(attrs)
        token = self.get_token(self.user)
        data["refresh"] = str(token)
        data["access"] = str(token.access_token)
        if len(self.user.groups.all()) == 0:
            if self.user.is_superuser:
                group = Group.objects.get(name="admin")
            elif self.user.is_staff:
                group = Group.objects.get(name="moderator")
            else:
                group = Group.objects.get(name="user")
            group.user_set.add(self.user)
        data["user"] = UserSerializer(self.user).data
        return data


Something went wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question