Is there a way to prevent users from accessing some (or all) URLs in application? For example, I am following Django tutorial and one of the examples has a URL:
#music/album/<pk>/delete
url(r'image/(?P<pk>[0-9]+)/delete/$', views.ImageDelete.as_view(), name='image-delete'),
that deletes database entry give pk as a parameter. Of course, now it is possible to delete this entry with just copy-pasting the URL with any existing primary-key, so what is the best practice to avoid it? Thanks
EDIT. Based on the replies and comments, I decided to elaborate a bit more. I am actually using DeleteView and forms with POST request as #solarissmoke suggested in answer.
<form action="{% url 'album:image-delete' image.id%}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="image_id" value="{{ image.id }}"/>
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
and in my views.py:
class ImageDelete(DeleteView):
model = Album
# if you successfully delete the object, page redirects to <homepage>
success_url = reverse_lazy('album:index')
So, there were few suggestions on checkin whether the user is verified to delete URL entry (e.x. the image) and to add pop up/notification to verify if the user indeed wants to delete the entry. However, it does not feel like a complete solution. In the comments I brought example of Facebook, where you can not delete imeage/post by just copy-pasting the delete URL. Surely I'm not asking for Facebook-like security, however, I'm really curious how can secure URLs so that it's nearly impossible for regular user to delete entry with simple copy-pasting. Thanks again!
Best practice is that you should not be allowing modification of data like this through HTTP GET requests, which are intended (as the name suggests) for getting data rather than updating it.
You should use forms and POST requests to perform actions like deleting objects etc. Django provides lots of helper views for doing this. For example DeleteView:
A view that displays a confirmation page and deletes an existing object. The given object will only be deleted if the request method is POST. If this view is fetched via GET, it will display a confirmation page that should contain a form that POSTs to the same URL.
The advantages of using these views are:
You can make sure the user has permissions to edit an object before making any changes. Django will perform the basic checks (e.g., CSRF) for you. You can augment the views to perform additional checks like making sure a user is logged in or checking any other permission.
You can enforce Cross-Site Request Forgery Protection.
It is not possible to accidentally delete an object by visiting a URL a second time (as the documentation above explains).
there are many ways.. e.g:
user = request.user
if user.is_authenticated() and user.profile.can_delete_image(image_pk):
# only then, image can be deleted by this user
# can_delete_image(image_pk) is defined by you
else:
raise DeletePermissionDenied # you can define your own Exception, just for fun
Related
I am creating an app that does some analysis, given a user enters in some IDs into the form. For example, if a user types 12345, 23456 into the TextField form, the app will run some analysis on these IDs and then display the results. My problem is that currently, when the user clicks "Submit" and the data analysis completes, it always redirects the user to www.website.com/results. I need to create unique url's like www.website.com/results/12345+23456 so that 1) I can have multiple users and 2) users can send this link to people to re-generate the analysis.
Now, there are some questions on StackOverflow that are similar to my question but they are not the same and did not help me. So first, let me show some code before discussing that.
I have a home page which contains the the form:
<div>
<form action="https://website.com/results/" class="form-inline" method="post">
<div class="form-group">
<label for="PubmedID">Pubmed ID(s)</label>
<input type="text" class="form-control" id="PubmedID" name="pmid" value="{{request.form.pmid}}">
</div>
<button type="submit" id= "myButton" class="btn btn-default" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
</div>
As you can see, the value for the form is request.form.pmid. My Flask-Wtform for this is here:
class pmidForm(Form):
pmid = TextField('PubmedID')
Since the action of this form points towards website.com/results that triggers my Flask function to be called:
#app.route('/results/', methods=["POST"])
def results():
form = pmidForm()
try:
if request.method == 'POST':
#entry = request.form or request.data doesn't help me...
entry = form.pmid.data #This is the user input from the form!
# DO LOTS OF STUFF WITH THE ENTRY
return render_template('results.html')
except Exception as e:
return(str(e))
As you can see I am using POST and form.pmid.data to get the data from the textfield form.
Again, I don't want to just redirect to /results, I'd like to expand on that. I tried to modify my form so that the form action pointed to https://website.com/results/{{request.form.pmid}}/ and then update the results function to be
#app.route('/results/<form_stuff>', methods=["POST"])
def results(form_stuff):
But this never worked and would re-direct me to a 404 not found page. Which I believe makes sense because there is no form data in the action when the HTML is first rendered anyway.
Now, the other post that mine is similar to is: Keeping forms data in url with flask, but it quite doesn't answer or solve my problem. For tthis post, the key point that people made was to use POST (which I already do), and to obtain and return the data with return request.args['query']. For me, I'm already processing the form data as I need to, and I have my return render_template() exactly how I want it. I just need to add something to the results URL so that it can be unique for whatever the user put into the form.
What do I need to add to my form in the html and to my Flask /results function in order to have the form data added into the URL? Please let me know if there's any other information I can provide to make my problem more clear. I appreciate the help! Thanks
This isn't really a question about Flask.
If you want the data to show in the URL when you submit the form, you should use method="get" rather than "post". Then the URL will be in the form https://website.com/results/?pmid=12345.
PROBLEM STATEMENT
I'm working on a Flask web app that displays a list of items in a table. The user can select a row and hit a Delete button to delete the item. However, before the item is deleted from the database, the user is first routed to a confirmation screen where some item details are displayed as well as a Confirm button. The url for the confirmation page follows this pattern: dashboard/confirm-delete/<id> and the url for the actual delete page follows this pattern: dashboard/delete/<id>. See admin/views.py below for more details.
While the system works, the problem I have is that a user can simply skip the confirmation page by typing dashboard/delete/<id>, where <id> is substituted by an actual item id, into the address bar.
QUESTIONS
Is there a way to prevent users from accessing dashboard/delete/<id> unless they first go to dashboard/confirm-delete/<id> (the confirmation screen)? Alternatively, is my approach wrong and is there a better one available?
CURRENT CODE:
Function in my dashboard.html page called when a row is selected and the delete button is pressed:
$('#remove').click(function () {
var id = getId();
window.location.href="/dashboard/confirm-delete" + $.trim(id);
});
Confirm button in confirm-delete.html (the delete confirmation page):
<a class="btn btn-default" href="{{ url_for('admin.delete_item', id=item.id) }}" role="button">Confirm Delete</a>
My admins/views.py:
#admin_blueprint.route('dashboard/confirm-delete/<id>')
#login_required
#groups_required(['admin'})
def confirm_delete_item(id)
item = Item.query.get_or_404(id)
return render_template('admin/confirm-delete.html', item=item, title="Delete Item")
#admin_blueprint.route('dashboard/delete/<id>', methods=['GET', 'POST'])
#login_required
#groups_required(['admin'})
def delete_item(id)
item = Item.query.get_or_404(id)
db.session.delete(item)
db.commit()
return redirect(url_for('home.homepage'))
SOLUTION
Based on the answer marked as accepted I solved the problem as follows:
First, I created a new form to handle the Submit button in the confirm-delete.html page:
admin/forms.py:
from flask_wtf import FlaskForm
from wtforms import SubmitField
class DeleteForm(FlaskForm):
submit = SubmitField('Confirm')
I substituted the Confirm Button code with the following to confirm-delete.html:
<form method="post">
{{ form.csrf_token }}
{{ form.submit }}
</form>
Finally, I merged both of the functions in app/views.py as follows:
#admin_blueprint.route('dashboard/confirm-delete/<id>', methods=['GET', 'POST'])
#login_required
#groups_required(['admin'})
def confirm_delete_item(id)
form = DeleteForm()
item = Item.query.get_or_404(id)
if form.validate_on_submit():
if form.submit.data:
db.session.delete(item)
db.commit()
return redirect(url_for('home.homepage'))
return render_template('admin/confirm-delete.html', item=item, form=form, title="Delete Item")
This way, a user can't bypass the delete confirmation screen by typing a specific link in the address bar, plus it simplifies the code.
As already mentioned in comments, one way of solving your problem is checking for a certain cookie as the user sends a request. But personally I would not recommend this method, because such cookies can very likely be compromised unless you come up with some sort of hashing algorithm to hash the cookie values and check them in some way.
To my mind, the most easy, secure and natural way of doing it is protecting /delete route with CSRF-token. You can implement it with Flask_WTF extension.
In a word, you have to create something like DeleteForm, then you put {{form.csrf_token}} in your confirm-delete.htmland validate it in delete_view() with form.validate_on_submit()
Check out their docs:
http://flask-wtf.readthedocs.io/en/stable/form.html
http://flask-wtf.readthedocs.io/en/stable/csrf.html
I would make the delete page POST-only. The browser may skip a GET request or try it many times, you have no control over it. A crawler could follow an anonymous delete link and delete all your wiki articles. A browser prefetcher could prefetch a logout link.
REST purists would insist you use GET, POST, DELETE and PUT methods for their intended purposes.
https://softwareengineering.stackexchange.com/questions/188860/why-shouldnt-a-get-request-change-data-on-the-server
So,
In HTML
<form action='/dashboard/delete/{{id}}' method='post'>
In Flask
#app.route('/dashboard/delete/<int:id>', methods=['POST'])
def delete(id):
I think there's a mistake in parenthesis.
#groups_required(['admin'})
Shouldn't it be ??
#groups_required(['admin'])
Let's say I have the following pointless example view:
def foo(request, input):
return HttpResponse()
and in a template I have a form:
<form method="get" action="{% url 'foo' ??? %}">
<input id="myinput" type="text" name="myinput">
...
</form>
Finally, I have the following url in my URLconf:
urlpatterns = [
url(r'^foo/(.+)/', views.foo, name='foo'),
]
What I would like to do, is pass the value entered by the user into the input with the id of #myinput to the foo() view function. To put it another way, you should be able to enter bar in the html input, and when you submit the form it will take you to foo/bar/.
I know that within the foo view I could access the value of the input easily with request.GET['myinput'], but I want it to show up in the url as well.
This seems like it should be a fairly common task, but I have not been able to come up with a solution yet. Any suggestions would be appreciated. My Frankenstein's Monster of a first Django site is almost complete, and this is one of last pieces I am missing.
The source of my misunderstanding
Although I did not make this clear in an attempt to simplify my example and avoid using app-specific code, my use case is a simple search view. The view was actually one of the first views I wrote in the start of my Django journey, and I mistakenly was POSTing my data instead of GETing it. This was making it so that if I was searching for the item foo, it would take me to the detail page for foo, but the url would be mysite/search/ (i.e., the search query is not included in the url though it is included in the request), and I can't return to those search results by visiting the url mysite/search/.
While I was using a GET request in my toy example in this question, I didn't realize that I had been using a POST in my app, and that with some minor tweaking I can get the functionality I want for free very easily. I know that all of this is extremely obvious to veteran and even intermediate web developers, but for someone starting from scratch without web or cs experience, things like HTTP can be a little confusing. At least for me it is. Thanks so much to #Two-Bit Alchemist for explaining this in a way that I can understand.
Applying all this to my toy example
I would get rid of the passed parameter in my view:
def foo(request):
# If I want to do something with the search query, I can access it with
# request.GET['search_query']
return HttpResponse()
change my form in my template to:
<form method="get" action="{% url 'foo' %}">
<input id="myinput" type="text" name="search_query">
...
</form>
and change my url to:
urlpatterns = [
url(r'^foo/search/', views.foo, name='foo'),
]
As #Two-Bit Alchemist said: "The rest will happen like magic". If a user enters bar in the input and submits the form, they will be taken to foo/search/?search_query=bar. This is what I was looking for.
I've spend hours today figuring out how to delete objects in Django.
Now I have found and tried 4 different approaches on the Net, that only differ in whether a form/POST/GET approach is used or not. CSRF attacks are irrelevant for me, as the page is supposed to run locally.
What does the app do? So far only uploading files under a certain project name. This name is slugified and used as a key to hash files of a project together. Now I want to also delete files (later whole projects).
Here one of the approaches:
In the .html:
<a href="{{file.pk}}/delete" class="btn btn-sm" role="button" title="Delete File">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</a>
This link is diplayed in a detail view, so the url already looks somethin like /files/SLUG/
Then in urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^upload/$', views.file_upload, name ='upload'),
url(r'^upload/(?P<slug>[\w-]+)/$', views.file_upload, name ='upload'),
url(r'^(?P<slug>[\w-]+)/$', views.file_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/(?P<pk>\d+)/delete$', views.file_delete, name="file_delete"),
]
And finally the views.py:
def file_delete(request, slug=None, pk=None):
instance = get_object_or_404(File, slug=slug, pk=pk)
# instance = File.objects.filter(pk=pk, slug=slug)[0] # the same as above
instance.delete() #does not work
return redirect("index") # or anything, this part is no problem
Everything runs through without any errors, but when I check the database on /admin, no file is gone. It simply does not get deleted. Sometimes, when logging in on /admin after trying a couple of times, I see multiple "File successfully deleted" messages at the login screen. But then the files are still in the database list.
Django Docs tells me delete() should return some kind of dictionary and how many objects were deleted e.g. like so:
>>> e.delete()
(1, {'weblog.Entry': 1})
But in may case it just says: None or returns a path starting with a slug.
I'd be very gratefull for any hint. I know there is at least one other post on stackoverflow concerning this, but unfortunately no answers
The queryset delete method (e.g. File.objects.filter(...).delete()) returns a tuple.
When you delete an instance (e.g. instance.delete()) it returns None.
I'm not sure what you mean by 'when I check the file list, no file is gone'. Note that when you delete a model instance, it will remove the row from the database. If the model has a FileField, it won't automatically delete the associated file.
I had a similar problem (that's how I found this), and I think if you simply put a '/' in the end of the URL for delete, it should work. At least thats what worked with me.
...
url(r'^(?P<slug>[\w-]+)/(?P<pk>\d+)/delete/<<<<$', views.file_delete, name="file_delete"),
]
Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django
How can I do this all without using this existing django admin interface.
You will want to wire your URL to the Django create_object generic view, and pass it either "model" (the model you want to create) or "form_class" (a customized ModelForm class). There are a number of other arguments you can also pass to override default behaviors.
Sample URLconf for the simplest case:
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object
from my_products_app.models import Product
urlpatterns = patterns('',
url(r'^admin/products/add/$', create_object, {'model': Product}))
Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my_products_app/product_form.html"):
<form action="." method="POST">
{{ form }}
<input type="submit" name="submit" value="add">
</form>
Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. Otherwise it won't know where to redirect to after save.
This topic is covered in Django tutorials.
Follow the Django tutorial for setting up the "admin" part of an application. This will allow you to modify your database.
Django Admin Setup
Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using.