After a customer has unlocked a post, I want to add his profile to the list of profiles that have unlocked the post.
def unlockpostview(request, post_id):
if userthatisunlockingprofile in post.unlockedby.all():
pass
else:
post.unlockedby.add(userthatisunlockingprofile)
When the user has paid I listen to the Stripe's succeeded
event and execute the view like so:
if (result.paymentIntent.status === 'succeeded') {
$.get("{% url 'postsapp:unlockpostview' post.post_id %}")
window.alert("Unlocked")
}
My problem was that anybody could go to the post and simply add /unlock
to the end of the URL and execute the view.
Then I added
if request.is_ajax():
to the view but this still isn't the optimal solution. I do not expect a complete solution to this but please point me in the right direction if you can. Thanks :)
CodePudding user response:
in POST request you don't give variables to the URL and also a CSRF token is a gift with it. And dump users can't send POST requests on browser easily
if (result.paymentIntent.status === 'succeeded') {
$.ajax({
type: "POST",
url: "{% url 'postsapp:unlockpostview' %}",
headers: {
'X-CSRFToken': '{{ csrf_token }}'
},
data: {
'operation': 'unlock_action',
'post_id': {{ post.post_id }}, //IDK how do you take it
'user': {{ request.user.id }}
},
dataType: "json",
success: function(response) {
if(response.success == true){
window.alert("Unlocked")
}
},
error: function(rs, e) {
console.log('error')
}
});
}
Just remove the post_id attribute from your url or:
urls.py
urlpatterns = [
path('unlockpostview/', views.unlockpostview, name="unlockpostview"),
]
views.py:
def unlockpostview(request):
if request.user.is_authenticated:
if request.method == 'POST' and request.POST.get("operation") == "unlock_action":
post = Post.objects.get(id=request.POST.get("post_id"))
userthatisunlockingprofile = User.objects.get(id=request.POST.get("user"))
#then your logic
if userthatisunlockingprofile in post.unlockedby.all():
ctx={"succes":True,"status":"exist"}
else:
post.unlockedby.add(userthatisunlockingprofile)
ctx={"succes":True,"status":"created"}
return JsonResponse(ctx)
else:
return redirect("home")
#Here is the security