If I have a view which the only purpose is to update a value in my session, is it safe to use it over GET or should I use POST and CSRF protection?
The value modified in the session is only used to change the user's context and if somebody manage to change the user's context in his own browser that should be harmless.
I personally don't ever consider it safe to use GET for a request that will have side effects.
I try to always follow the practice of POST + redirection to another page.
This solves all kinds of problems, such as F5 refreshing the action, the user bookmarking a URL which has a side effect and so on.
In your case, the update is harmless, but using POST at least conveys the fact that it's an update and may be useful for tools such as caching software (POST requests usually aren't cached).
On top of that, applications often change, and you may at some point need to modify the app in such a way that the update isn't so harmless anymore.
It's also generally difficult to guarantee that anything is completely secure in web development, so I prefer to stay on the safe side.
Related
I just stated using Flask and was trying to implement a small feature in my project. The objective is to set a cookie only if the request comes from a authenticated user.
I found two ways of doing this.
First method
#app.before_request
def before_request():
# set cookie if user is logged in
Second method, by implementing something like this
adding-a-simple-middleware-to-your-flask-application
Can someone explain to me what are the main differences between the two methods and when and where which method should be used.
Also, I am currently using "flask-login" to keep track of the logged in user.
If I use the first method, I can easily verify if someone is logged in by importing the current_user
from flask.ext.login import current_user
but if I try to do the same while using the second method, the current_user is always "None" as the application context is incorrect.
So, I wanted to know if I decided to go ahead with the second implementation, how do I check if the user is logged in or not.
I've never used the second method you've mentioned. I'm sure that it can be done with it, but it's very uncommon. I would suggest to use more common features of flask. For sake of maintainers of your code :)
So the first method you've mentioned is fine.
Or you can use decorators for more granular access restrictions. Keep in mind that setting cookies in flask can be done when making actual response object. That means you should use Deferred Request Callbacks for setting cookies in decorated function.
I need to implement caching on my Django 1.8 site (to speed up rendering, obviously). Plan is to use Memcache, although this question isn't directly tied to it.
Right now, a lot of traffic goes to a specific set of blog posts that remain constant. But, there is a universal dynamic topbar across the whole site which can vary from logged-in user to logged-in user, so I need a cache function that kicks in if and only if the user is anonymous - e.g. one that is bypassed altogether if the user is logged in.
It looks like Django's builtin cache doesn't really distinguish between logged-in and logged-out users, so if I use it, there will be adverse effects for logged-in people.
I'll probably have to write my own cache decorator/cache function using the lower-level cache API and attach it to all of the logged-out-accessible URLs/views on the site. While it doesn't seem difficult, this does seem like an incredibly common feature. Is there really nothing in Django that does this properly already? I'm worried I might have missed something and am reimplementing the wheel.
Thank you!
First of all template caching is over rated. First use django debug toolbar to determine if template rendering is indeed slow on your django installation. I am betting that it's not the bottleneck. If you find that it's slow. YOu can cache on a per user basis as follows:
{% cache 300 FULL_PAGE request.build_absolute_uri request.user %}
The first parameter to the cache template tag is the timeout and the second one is the name others uniquely identify the fragment.
I am in the midst of writing a web app in CherryPy. I have set it up so that it uses OpenID auth, and can successfully get user's ID/email address.
I would like to have it set so that whenever a page loads, it checks to see if the user is logged in, and if so displays some information about their login.
As I see it, the basic workflow should be like this:
Is there a userid stored in the current session? If so, we're golden.
If not, does the user have cookies with a userid and login token? If so, process them, invalidate the current token and assign a new one, and add the user information to the session. Once again, we're good.
If neither condition holds, display a "Login" link directing to my OpenID form.
Obviously, I could just include code (or a decorator) in every public page that would handle this. But that seems very... irritating.
I could also set up a default index method in each class, which would do this and then use a (page-by-page) helper method to display the rest of the content. But this seems like a nightmare when it comes to the occasional exposed method other than index.
So, my hope is this: is there a way in CherryPy to set some code to be run whenever a request is received? If so, I could use this to have it set up so that the current session always includes all the information I need.
Alternatively, is it safe to create a wrapper around the cherrypy.expose decorator, so that every exposed page also runs this code?
Or, failing either of those: I'm also open to suggestions of a different workflow. I haven't written this kind of system before, and am always open to advice.
Edit: I have included an answer below on how to accomplish what I want. However, if anybody has any workflow change suggestions, I would love the advice! Thanks all.
Nevermind, folks. Turns out that this isn't so bad to do; it is simply a matter of doing the following:
Write a function that does what I want.
Make the function in to a custom CherryPy Tool, set to the before_handler hook.
Enable that tool globally in my config.
I have an application that uses the requests library to make calls to a web service. On django, I use a table to keep sessions using the standard django_session library.
I've noticed that I have a new record in the database for every time the requests library fires off a call. I find this quite bizarre, since I'm not using request sessions (explicitly) and most of my calls are single GET calls that shouldn't need any kind of persistance.
Has anybody else had this problem?
django.contrib.sessions.middleware.SessionMiddleware will create a new session for each request.
If you want to disable this behavior, consider replacing django.contrib.sessions.middleware.SessionMiddleware with a custom middleware that extends django.contrib.sessions.middleware.SessionMiddleware but prevents sessions from being created in instances where you don't want them.
This answer provides an example of how to do so. It parses request.path_info to determine whether a session should be created, but you could use a number of different techniques, such as adding a custom header to your request, including a post variable, etc.
Turns out I had this setting turned on
SESSION_SAVE_EVERY_REQUEST=True
When I started with sessions I wanted to be safe to make sure nothing falls through the cracks. Turns out this was then writing empty session information to the db.
The behavior I propose:
A user loads up my "search" page, www.site.com/search, types their query into a form, clicks submit, and then ends up at www.site.com/search/the+query instead of www.site.com/search?q=the+query. I've gone through a lot of the Pylons documentation already and just finished reading the Routes documentation and am wondering if this can/should happen at the Routes layer. I have already set up my application to perform a search when given www.site.com/search/the+query, but can not figure out how to send a form to this destination.
Or is this something that should happen inside a controller with a redirect_to()?
Or somewhere else?
Followup:
This is less an actual "set in stone" desire right now and more a curiosity for brainstorming future features. I'm designing an application which uses a Wikipedia dump and have observed that when a user performs a search on Wikipedia and the search isn't too ambiguous it redirects directly to an article link: en.wikipedia.org/wiki/Apple. It is actually performing an in-between HTTP 302 redirect step, and I am just curious if there's a more elegant/cute way of doing this in Pylons.
You can send whatever content you want for any URL, but if you want a particular URL to appear in the browser's address bar, you have to use a redirect. This is independent of whether you use Pylons, Django or Rails on the server side.
In the handling for /search (whether POST or GET), one would normally run the query in the back end, and if there was only one search result (or one overwhelmingly relevant result) you would redirect to that result, otherwise to a page showing links to the top N results. That's just normal practice, AFAIK.
HTML forms are designed to go to a specific URL with a query string (?q=) or an equivalent body in a POST -- either you write clever and subtle Javascript to intercept the form submission and rewrite it in your preferred weird way, or use redirect_to (and the latter will take some doing).
But why do you need such weird behavior rather than just following the standard?! Please explain your use case in terms of application-level needs...!