1

actually I want: if a user is authenticated: then create/get the Cart with user, else: create/get the Cart with session key. But at first problem happened with authentication.

At first I tried to register the user and saved the key(got from drf) in local storage.

in Reactjs:

signupHandler=()=>{
        fetch('http://127.0.0.1:8000/api/rest-auth/registration/', {
            method: 'POST',
            headers:{
                'content-type':'application/json',
            },
            body:JSON.stringify({
                'username':this.state.username,
                'email': this.state.email,
                'password1': this.state.pass1,
                'password2': this.state.pass2
            })
        })
        .then((response)=>{
            response.json().then((result)=>{
                if (result.key !== undefined){
                    localStorage.setItem('login', JSON.stringify({login: true,token:result.key}))
                    this.setState({registered: true})
                }
            })
        })
    }

I think no problem here. if I console.log() the key , it prints the key successfully.

now look at my views.py . I think the problem is here.

@api_view(['GET'])
#@permission_classes((IsAuthenticated,))<<< if i comment out this line, and try to call this function, it shows >>>Forbidden: /addToCart/21/
def addToCart(request, pk):
    print(request.user)#>>>AnonymousUser
    product = get_object_or_404(Product, pk=pk)
    
    if request.user.is_authenticated:
        print('authenticated')#>>> nothing prints
        mycart, __ = Cart.objects.get_or_create(user=request.user)
        mycart.product.add(product)
    else:
        print('session')#>>>session
        if not request.session.exists(request.session.session_key):
            request.session.create() 
        mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key)
        mycart.product.add(product)

    return Response({'response':'ok'})

now i made a button and if i click, this function call

reactjs:

addToCart=()=>{
        var id = this.props.id
        let store = JSON.parse(localStorage.getItem('login'))
        console.log(store.token);//successfully print the key
        var url = 'http://127.0.0.1:8000/addToCart/'+id+'/'
        fetch(url,{
            method:'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Token '+store.token
            }
        }).then(res=>res.json().then(result=>{
            if(result.response === 'ok'){
                this.props.dispatch({
                    type: 'itemInCart',
                })
                this.setState({addedToCart: true})
            }
        }))
    }

So my question is:

*why it shows Forbidden if I comment out the line @permission_classes((IsAuthenticated,)) though i don't want this line. because I also want, user can add item with session.

*(in views.py) when i print request.user it shows >>>AnonymousUser. how to print the real user?

  • Finally, How can I add an item to the Cart with an Authenticated user?
2
  • The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise. This permission is suitable if you want your API to only be accessible to registered users. mentioned here Commented Jun 6, 2021 at 13:07
  • @Bubai, sir, but i'm authenticated and my key is stored in local storage. I called the function with Authorization token. So, please, can you tell me why i'm still un-authenticated? Commented Jun 6, 2021 at 13:14

1 Answer 1

1

You need to add either DEFAULT_AUTHENTICATION_CLASSES in settings.py or add a decorator @authentication_classes([TokenAuthentication]) to the api_view if not done already.
Since you need the API to also be accessible to unauthenticated users, @permission_classes is not required.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.