Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How do I implement forms for user input to register and login in Django when I already have the views using JWT?

$
0
0

I´m learning how to work with JWT(pyJWT) in Django, in this case I´m trying to authenticate users with it, I followed a tutorial and using postman it worked, I use mysql and the passwords were hashed and the tokens were generated succesfully, now the only thing left is to create the forms so the user can input his credentials but I don´t know how to do proceed.

Views.py

class RegisterView(APIView):    def post(self, request):        serializer = UserSerializer(data=request.data)        serializer.is_valid(raise_exception=True)        serializer.save()        return Response(serializer.data)class LoginView(APIView):    def post(self, request):        email = request.data['email']        password = request.data['password']        user = User.objects.filter(email=email).first()        if user is None:            raise AuthenticationFailed('User not found')        if not user.check_password(password):            raise AuthenticationFailed('Incorrect password')        payload = {'id': user.id,'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=60),'iat': datetime.datetime.now(datetime.timezone.utc)        }        token = jwt.encode(payload, 'secret', algorithm='HS256')        response = Response()        response.set_cookie(key='jwt', value=token, httponly=True)        response.data = {"jwt": token        }        return responseclass UserView(APIView):    def get(self, request):        token = request.COOKIES.get('jwt')        if not token:            raise AuthenticationFailed('Unathenticated!')        try:            payload = jwt.decode(token, 'secret', algorithms=['HS256'])        except jwt.ExpiredSignatureError:            raise AuthenticationFailed('Uathenticated')        user = User.objects.filter(id=payload['id']).first()        serializer = UserSerializer(user)        return Response(serializer.data)class LogoutView(APIView):    def post(self, request):        response = Response()        response.delete_cookie('jwt')        response.data = {'message': 'Success'        }        return response

Serializers.py

class UserSerializer(serializers.ModelSerializer):    class Meta:        model = User        fields = ['id', 'email', 'password', 'first_name', 'last_name', 'username']        extra_kwargs = {'password': {'write_only': True}        }    def create(self, validated_data):        password = validated_data.pop('password', None)        instance = self.Meta.model(**validated_data)        if password is not None:            instance.set_password(password)        instance.save()        return instance

Models.py

class User(AbstractUser):    email = models.CharField(max_length=255, unique=True)    password = models.CharField(max_length=255)    first_name = models.CharField(max_length=255)    last_name = models.CharField(max_length=255)    username = models.CharField(max_length=255)    USERNAME_FIELD = 'email'    REQUIRED_FIELDS = []

Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>