【发布时间】:2021-08-23 19:29:10
【问题描述】:
实际上我想要:如果用户通过了身份验证:然后使用用户创建/获取 Cart, else: 使用会话密钥创建/获取购物车。但起初身份验证出现问题。
起初我尝试注册用户并将密钥(从 drf 获取)保存在本地存储中。
在 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})
}
})
})
}
我认为这里没有问题。如果我 console.log() key ,它会成功打印密钥。
现在看看我的 views.py 。我认为问题就在这里。
@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'})
现在我做了一个按钮,如果我点击,这个函数调用
反应:
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})
}
}))
}
所以我的问题是:
*为什么它显示 Forbidden 如果我注释掉 @permission_classes((IsAuthenticated,)) 行虽然我不想要这一行。因为我也想要,用户可以添加带有会话的项目。
*(在views.py中)当我打印request.user时它显示>>>AnonymousUser。如何打印真实用户?
- 最后,我如何将商品添加到购物车与经过身份验证的用户?
【问题讨论】:
-
IsAuthenticated权限类将拒绝任何未经身份验证的用户的权限,否则允许权限。如果您希望您的 API 仅供注册用户访问,则此权限适用。提到here -
@Bubai,先生,但我已通过身份验证,并且我的密钥存储在本地存储中。我用授权令牌调用了该函数。所以,拜托,你能告诉我为什么我还没有通过身份验证吗?
标签: javascript python reactjs django django-rest-framework