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.
Related
I have to implement a function in my website where there can only be one login per account. So, if a user logs into one browser, the others will automatically be logged out. I am using Flask for backend. Is there any such implementation in Flask, and if not, what are some ways by which I can implement this?
I don't know of any implementation. The first thing that comes to my mind is to modify the user model. You could add a column for logged_in, which get's changed to True when the user is logged in and to False if the user logs out/ the session is dropped.
You would need to check this attribute when verifying the user login. For further specific help consider posting an MRE of your question.
I wish to make a route for "forgot password"-functionality, while using Flask-Restless. My idea was that the request could look like this:
POST /api/user/<id>/forgot_password
and Flask-Restless would send this request to a custom "forgot password"-route which I provided. This way, I could define my own complex operations here on the user object (store intermediate stuff in DB, email password reset link, etc.)
I have not been able to find such functionality in the docs for Flask-Restless. Also, while trying to make a quick (hacky) separate route (outside of Flask-Restless) which simply corresponded to the above route, Flask-Restless still picked up on the request and returned a 405 (Method Not Allowed).
One can imagine this kind of functionality for other complex operations as well (e.g. change password, change email).
Is it possible to achieve this routing scheme somehow? If so, how?
If not, what would be an alternative? An ordinary route in a separate blueprint?
This is not possible within the Flask-Restless extension. One might be able to add it manually.
I made a feature request for this on the Flask-Restless issue tracker, and it was determined to be out of scope by the author.
I'm trying to use Tornado with SqlAlchemy, I need to pass the current user from RequestHandler (tornado) to models (SqlAlchemy) in the insert or update action. But I don't want to pass the value directly to the model, example:
#### RequestHandler POST method...
user = Session.query(User).get(1)
user.name = "bla, bla, bla..."
user.updated_by = self.current_user # don't use...
session.commit()
I'm using a global variable, in a __ init__.py file, and set the current user value in the RequestHandler and after, get the value, in before update event with SqlAlchemy.
The idea is to know what user is the creator and updater.
Why I don't want pass the current user directly to model like the before example ?, because this will be a tool for other developers, and I'm trying to make comfortable for them, also, they can forget about it and it is important.
Is this a good idea, or maybe is there other better way ?
Your solution will have issues if you're handling more than one request at a time. Tornado is an async web framework so another request might overwrite your global var and set the user to someone else. It's good practice to store request depending data on self, tornado will make sure that data is altered by other simultaneous requests.
A solution that might work for you is to add your tool in the basic handler or create a decorator. It's tricky to sugest more details, please include more info in your question if you would like to get better alternatives.
The current user is available in every handler (and template). How you determine, authenticate and set the current user is up to you.
Basically just subclass tornado.web.RequestHandlerand override the get_current_user method in your new/own BaseHandler.
Here the quote from the tornado docs:
tornado User authentication
User authentication
The currently authenticated user is available in every request handler as self.current_user, and in every template as current_user. By default, current_user is None.
To implement user authentication in your application, you need to override the get_current_user() method in your request handlers to determine the current user based on, e.g., the value of a cookie. Here is an example that lets users log into the application simply by specifying a nickname, which is then saved in a cookie.
You can see a fully working example in the official tornado blog demo
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'm using python to develop a web app.
I defined both "get" and "post" method in the same request handler to serve different purpose. That is, I use "get" method to present a form to user, and "post" method to handle the submitted form.
It works fine, but is this approach appropriate? Or should I better define get and post separately in different request handler? Thanks!
Your approach is appropriate. According to the newest documentation you can even define post and get as functions outside request handler and just as other functions in your module and that's a way I would choose since it eliminates problems that can happen when instanciating request handlers.
If starting a new app from scratch I probably would try to put my get and post function outside of request handler with the new python 2.7 runtime that according to docs supports that.