python flask do something at each route - python

I have a flask app where I have to delete and update user information, like this (simplified):
#app.route('/<user>')
def show_user(user):
""" Show user information """
render_template('show_user.html')
#app.route('/delete/<user>')
def delete_user(user):
""" Delete user from database """
delete_user_from_db(user)
return redirect(url_for('show_users', user=user)
#app.route('/update/<user>', method=["POST"])
def update_user(user):
""" Update user information """
update(user, stuff_from_POST)
return redirect(url_for('show_users', user=user)
For each of these methods I need to verify whether the user specified in the URL is really a valid user, so I'd do something like this at the beginning of all those functions:
if user not in mydb:
do(something)
abort(404)
This is rather cumbersome, and since I will be having more functions that depend on the user to be valid, I was wondering if it were possible to wrap that block in another function that gets automatically executed when those routes are called.
Thanks in advance.

Use the before_request hook function see docs
#app.before_request
def before_request():
if user not in mydb:
do(something)
abort(404)
Edit:
I tried this
from flask import Flask, request
app = Flask(__name__)
db = ['paul', 'steve', 'anna']
#app.before_request
def before_request():
if request.endpoint in ['show_user', 'delete_user', 'update_user']:
user = request.path[request.path.rfind('/') + 1:]
if user not in db:
return 'user not found', 404
#app.route('/<user>')
def show_user(user):
""" Show user information """
return 'hello %s' % user
#app.route('/other')
def show_other():
""" Demonstrates other routes are not effected by before_request """
return 'other stuff'
if __name__ == "__main__":
app.run()
It's not actually as neat as I hoped but it works.
It's a little unfortunate to have to maintain which endpoints do what in the before_request function. If you were doing REST you might be able to merge these endpoints into one and simply use different http methods for each action.

Related

Passing the destination URL through Flask and Flask-Login

Looking at the Flask-Login docs and several relatively old threads on Stackoverflow, I am concerned about the security of my solution for passing the restricted page URL through the login process.
First, I was getting Attribution Error when trying to use #login_manager.unauthorized_handler. ("login_manager does not have an attribute unauthorized_handler.") This a separate issue altogether, because it really should have worked. (See app factory below.)
When I applied a redirect_destination function without the modified #login_manager.unauthorized_handler, the login failed to redirect to the target destination.
def redirect_destination(dest_url, fallback):
try:
dest_url = url_for(dest_url)
except:
return redirect(fallback)
return redirect(dest_url)
Then I applied a session instance to be passed from the destination URL through login along with the fresh_login_required decorator and .is_authenticated property instead of the standard login_required.
target blueprint:
#target.route('/target', methods=['GET', 'POST'])
#fresh_login_required
def target():
if current_user.is_authenticated:
...
return render_template('target.html')
else:
session['dest_url']=request.endpoint
return redirect(url_for('account.login'))
auth blueprint:
#account.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
dest_url = session.get('dest_url')
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if not user:
return redirect(url_for('account.login'))
if user.check_password(form.password.data):
login_user(user, remember=form.remember_me.data)
...
return redirect_destination(dest_url, fallback=url_for('main.index'))
else:
return redirect(url_for('account.login'))
return render_template('account/login.html')
app factory:
...
login_manager = LoginManager()
login_manager.login_view = 'account.login' #hard-coded view
login_manager.refresh_view = 'account.refresh' #hard-coded view
def create_app():
app = Flask(__name__,
static_url_path='/',
static_folder='../app/static',
template_folder='../app/templates')
db.init_app(app)
login_manager.init_app(app)
from app import models
from .templates.account import account
from .templates.main import main
from .templates.target import target
app.register_blueprint(main)
app.register_blueprint(account)
app.register_blueprint(target)
return app
So, this solution works, and it can be applied to multiple blueprints. My concern is that I am missing some important details that necessitated other, more complex solutions. Is there a security weak point? Other issues?
References:
https://flask-login.readthedocs.io/en/latest/
How do I pass through the "next" URL with Flask and Flask-login?
Flask/Werkzeug, how to return previous page after login
Flask how to redirect to previous page after successful login
Get next URL using flask redirect
Flask Basic HTTP Auth use login page

Check Flask cookie for user_id and obtain User if it exists or redirect if not

What I'm after is something like what the #login_required decorators accomplish but I'm not sure if a custom decorator would allow me to pass the User option back to my route function. There are several pages in my app that require the user to be logged in to access them so I am looking for the most efficient way/least code to copy into each access-restricted route that will verify they have a user_id in their cookie (logged in), cache get/query for their User object using the user_id, and carry on with the route function, else redirect to the login page if user_id is not present.
What I was hoping to do was something like:
#noteBP.route('/note', methods=['GET', 'POST'])
def new_note():
user_details = return_user_details_if_logged_in_else_redirect_to_login_url(next=request.url)
...
And that function would check for the user_id in the session cookie and send back the User object or redirect to the login page:
def return_user_details_if_logged_in_else_redirect_to_login_url(next=None):
user_id = session.get('user_id')
if user_id:
user_details = user_util.get_user_details_by_id(user_id)
return user_details
else:
return redirect(url_for('usersBP.login', next=next))
Turns out, redirect does not work the same way as Abort where it gets called even if you are inside another function so now I have do do additional processing back in the route function to check:
user_details = return_user_details_if_logged_in_else_redirect_to_login_url(next=request.url)
if not user_details:
return redirect(redirect_url)
I'm looking to avoid having to paste this chunk of code at the top of every access-restricted route. Is there a more efficient way/DRY approach to do this? if with a decorator, how do I get the user_details into the route function?
If you want to redirect in a function called inside a view, raise a RequestRedirect. If you want to redirect in a decorator, check if the user is not logged in and return a redirect rather than the actual view (or use the previous function to raise the redirect).
import functools
from flask import url_for, redirect, g
from werkzeug.routing import RequestRedirect
def require_login():
if g.user is None:
raise RequestRedirect(url_for('login'))
def login_required(view):
#functools.wraps(view)
def wrapped_view(**kwargs):
require_login()
# or
# if g.user is None:
# return redirect(url_for('login'))
return view(**kwargs)
return wrapped_view
#app.route('/secret2')
#login_required
def secret1():
return 'secret 1'
#app.route('/secret2')
def secret2():
require_login()
return 'secret 2'
Populate g.user in a before_request handler.
from flask import session
#app.before_request
def load_user():
g.user = None
if 'user_id' in session:
# use whatever caching logic you want here.
g.user = User.query.get(session['user_id'])
Populate session['user_id'] in your login view.
#app.route('/login')
def login():
if request.method == 'POST':
user = User.query.filter_by(username=request.form['username']).first()
if user and user.check_password(request.form['password']:
session['user_id'] = user.id
return redirect(url_for('index'))
return render_template('login.html')
Now you can access g.user from any route, without passing it explicitly. If you do want to pass it explicitly, modify login_required.
def require_login():
if g.user is None:
raise RequestRedirect(url_for('login'))
return g.user
def login_required(view):
#functools.wraps
def wrapped_view(**kwargs):
user = require_login()
return view(user, **kwargs)
return wrapped_view
#app.route('/secret')
def secret(user):
return 'user {} is logged in'.format(user.id)
Give that all of this except passing the user is part of Flask-Login, you should really reconsider using Flask-Login instead of trying to maintain your own solution.
A decorator is a function that wraps and replaces another function. Since the original function is replaced, you need to remember to copy the original function’s information to the new function. Use functools.wraps() to handle this for you.
This example assumes that the login page is called 'login' and that the current user is stored in g.user and is None if there is no-one logged in.
from functools import wraps
from flask import g, request, redirect, url_for
def login_required(f):
#wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
To use the decorator, apply it as innermost decorator to a view function. When applying further decorators, always remember that the route() decorator is the outermost.
#app.route('/secret_page')
#login_required
def secret_page():
pass
Note:
The next value will exist in request.args after a GET request for the login page. You’ll have to pass it along when sending the POST request from the login form. You can do this with a hidden input tag, then retrieve it from request.form when logging the user in.
<input type="hidden" value="{{ request.args.get('next', '') }}"/>

python/flask find unique ids for each website visitor [duplicate]

I want to build a simple webapp as part of my learning activity. Webapp is supposed to ask for user to input their email_id if it encounters a first time visitor else it remembers the user through cookie and automatically logs him/her in to carry out the functions.
This is my first time with creating a user based web app. I have a blue print in my mind but I am unable to figure out how to implement it. Primarily I am confused with respect to the way of collecting user cookie. I have looked into various tutorials and flask_login but I think what I want to implement is much simpler as compared to what flask_login is implementing.
I also tried using flask.session but it was a bit difficult to understand and I ended up with a flawed implementation.
Here is what I have so far (it is rudimentary and meant to communicate my use case):
from flask import render_template, request, redirect, url_for
#app.route("/", methods= ["GET"])
def first_page():
cookie = response.headers['cookie']
if database.lookup(cookie):
user = database.get(cookie) # it returns user_email related to that cookie id
else:
return redirect_url(url_for('login'))
data = generateSomeData() # some function
return redirect(url_for('do_that'), user_id, data, stats)
#app.route('/do_that', methods =['GET'])
def do_that(user_id):
return render_template('interface.html', user_id, stats,data) # it uses Jinja template
#app.route('/submit', methods =["GET"])
def submit():
# i want to get all the information here
user_id = request.form['user_id']# some data
answer = request.form['answer'] # some response to be recorded
data = request.form['data'] # same data that I passed in do_that to keep
database.update(data,answer,user_id)
return redirect(url_for('/do_that'))
#app.route('/login', methods=['GET'])
def login():
return render_template('login.html')
#app.route('/loggedIn', methods =['GET'])
def loggedIn():
cookie = response.headers['cookie']
user_email = response.form['user_email']
database.insert(cookie, user_email)
return redirect(url_for('first_page'))
You can access request cookies through the request.cookies dictionary and set cookies by using either make_response or just storing the result of calling render_template in a variable and then calling set_cookie on the response object:
#app.route("/")
def home():
user_id = request.cookies.get('YourSessionCookie')
if user_id:
user = database.get(user_id)
if user:
# Success!
return render_template('welcome.html', user=user)
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
#app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
# You should really validate that these fields
# are provided, rather than displaying an ugly
# error message, but for the sake of a simple
# example we'll just assume they are provided
user_name = request.form["name"]
password = request.form["password"]
user = db.find_by_name_and_password(user_name, password)
if not user:
# Again, throwing an error is not a user-friendly
# way of handling this, but this is just an example
raise ValueError("Invalid username or password supplied")
# Note we don't *return* the response immediately
response = redirect(url_for("do_that"))
response.set_cookie('YourSessionCookie', user.id)
return response
#app.route("/do-that")
def do_that():
user_id = request.cookies.get('YourSessionCookie')
if user_id:
user = database.get(user_id)
if user:
# Success!
return render_template('do_that.html', user=user)
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
DRYing up the code
Now, you'll note there is a lot of boilerplate in the home and do_that methods, all related to login. You can avoid that by writing your own decorator (see What is a decorator if you want to learn more about them):
from functools import wraps
from flask import flash
def login_required(function_to_protect):
#wraps(function_to_protect)
def wrapper(*args, **kwargs):
user_id = request.cookies.get('YourSessionCookie')
if user_id:
user = database.get(user_id)
if user:
# Success!
return function_to_protect(*args, **kwargs)
else:
flash("Session exists, but user does not exist (anymore)")
return redirect(url_for('login'))
else:
flash("Please log in")
return redirect(url_for('login'))
return wrapper
Then your home and do_that methods get much shorter:
# Note that login_required needs to come before app.route
# Because decorators are applied from closest to furthest
# and we don't want to route and then check login status
#app.route("/")
#login_required
def home():
# For bonus points we *could* store the user
# in a thread-local so we don't have to hit
# the database again (and we get rid of *this* boilerplate too).
user = database.get(request.cookies['YourSessionCookie'])
return render_template('welcome.html', user=user)
#app.route("/do-that")
#login_required
def do_that():
user = database.get(request.cookies['YourSessionCookie'])
return render_template('welcome.html', user=user)
Using what's provided
If you don't need your cookie to have a particular name, I would recommend using flask.session as it already has a lot of niceties built into it (it's signed so it can't be tampered with, can be set to be HTTP only, etc.). That DRYs up our login_required decorator even more:
# You have to set the secret key for sessions to work
# Make sure you keep this secret
app.secret_key = 'something simple for now'
from flask import flash, session
def login_required(function_to_protect):
#wraps(function_to_protect)
def wrapper(*args, **kwargs):
user_id = session.get('user_id')
if user_id:
user = database.get(user_id)
if user:
# Success!
return function_to_protect(*args, **kwargs)
else:
flash("Session exists, but user does not exist (anymore)")
return redirect(url_for('login'))
else:
flash("Please log in")
return redirect(url_for('login'))
And then your individual methods can get the user via:
user = database.get(session['user_id'])

How to apply decorator to all blueprint urls in flask

I have a blueprint and some url functions,
admin_bp = Blueprint('admin', __name__)
#admin_bp.route('/dashboard', methods=['GET', ])
#flask_login.login_required
def dashboard():
context = {}
page = 'admin/dashboard.html'
return render_template(page, **context)
#admin_bp.route('/deny', methods=['GET', ])
#flask_login.login_required
def deny():
return 'hey bro you dont belong here'
I don't want to copy paste #flask_login.login_required decorator for all url functions under this blueprint. Is there a better way that I can apply decorator for all blueprint urls?
You can add before_request() as a function that will run before each request in a view.
You will then want to add decorators to inject additional functionality to the before_request function. You will want to import the login_required decorator to ensure each endpoint requires a logged in user. This decorator is part of the flask_login library.
Since it looks like your views are part of an admin, I'd also recommend adding a custom decorator to your before_request function with something like #role_required('admin'). The functionality for that decorator will live somewhere else and be imported.
#admin_bp.before_request
#login_required
def before_request():
""" Protect all of the admin endpoints. """
pass
Subclass Blueprint and override the route method.
import flask
class MyBlueprint(flask.Blueprint):
def route(self, rule, **options):
def decorator(f):
# these lines are copied from flask.Blueprint.route
endpoint = options.pop("endpoint", f.__name__)
self.add_url_rule(rule, endpoint, f, **options)
# At this point flask.Blueprint.route simply returns f.
# But you can nest a decorator.
def inner(*args, **kwargs):
# stuff you want to do before each request goes here
try:
result = f(*args, **kwargs)
# stuff you want to do on successful responses (probing status, headers, etc.) goes here
except Exception as e:
# stuff you want to do on error responses goes here
raise
return inner
Now use the new subclass in your blueprints:
-v1_blueprint = Blueprint('v1', __name__)
+v1_blueprint = MyBlueprint('v1', __name__)
No changes needed to individual routes.
The drawback of this approach is that it copies code from inside Flask. If the implementation of flask.Blueprint.route were to change in a future version, you'd need to sync MyBlueprint with it when you upgrade Flask.
How about checking the user first:
from flask.ext.login import current_user
#admin_bp.before_request
def check_user():
if not current_user.is_authenticated():
abort(401)
# your other functions without `#flask_login.login_required`

Testing Flask login and authentication?

I'm developing a Flask application and using Flask-security for user authentication (which in turn uses Flask-login underneath).
I have a route which requires authentication, /user. I'm trying to write a unit test which tests that, for an authenticated user, this returns the appropriate response.
In my unittest I'm creating a user and logging as that user like so:
from unittest import TestCase
from app import app, db
from models import User
from flask_security.utils import login_user
class UserTest(TestCase):
def setUp(self):
self.app = app
self.client = self.app.test_client()
self._ctx = self.app.test_request_context()
self._ctx.push()
db.create_all()
def tearDown(self):
if self._ctx is not None:
self._ctx.pop()
db.session.remove()
db.drop_all()
def test_user_authentication():
# (the test case is within a test request context)
user = User(active=True)
db.session.add(user)
db.session.commit()
login_user(user)
# current_user here is the user
print(current_user)
# current_user within this request is an anonymous user
r = test_client.get('/user')
Within the test current_user returns the correct user. However, the requested view always returns an AnonymousUser as the current_user.
The /user route is defined as:
class CurrentUser(Resource):
def get(self):
return current_user # returns an AnonymousUser
I'm fairly certain I'm just not fully understanding how testing Flask request contexts work. I've read this Flask Request Context documentation a bunch but am still not understanding how to approach this particular unit test.
The problem is different request contexts.
In your normal Flask application, each request creates a new context which will be reused through the whole chain until creating the final response and sending it back to the browser.
When you create and run Flask tests and execute a request (e.g. self.client.post(...)) the context is discarded after receiving the response. Therefore, the current_user is always an AnonymousUser.
To fix this, we have to tell Flask to reuse the same context for the whole test. You can do that by simply wrapping your code with:
with self.client:
You can read more about this topic in the following wonderful article:
https://realpython.com/blog/python/python-web-applications-with-flask-part-iii/
Example
Before:
def test_that_something_works():
response = self.client.post('login', { username: 'James', password: '007' })
# this will fail, because current_user is an AnonymousUser
assertEquals(current_user.username, 'James')
After:
def test_that_something_works():
with self.client:
response = self.client.post('login', { username: 'James', password: '007' })
# success
assertEquals(current_user.username, 'James')
The problem is that the test_client.get() call causes a new request context to be pushed, so the one you pushed in your the setUp() method of your test case is not the one that the /user handler sees.
I think the approach shown in the Logging In and Out and Test Adding Messages sections of the documentation is the best approach for testing logins. The idea is to send the login request through the application, like a regular client would. This will take care of registering the logged in user in the user session of the test client.
I didn't much like the other solution shown, mainly because you have to keep your password in a unit test file (and I'm using Flask-LDAP-Login, so it's nonobvious to add a dummy user, etc.), so I hacked around it:
In the place where I set up my test app, I added:
#app.route('/auto_login')
def auto_login():
user = ( models.User
.query
.filter_by(username="Test User")
.first() )
login_user(user, remember=True)
return "ok"
However, I am making quite a lot of changes to the test instance of the flask app, like using a different DB, where I construct it, so adding a route doesn't make the code noticeably messier. Obv this route doesn't exist in the real app.
Then I do:
def login(self):
response = self.app.test_client.get("/auto_login")
Anything done after that with test_client should be logged in.
From the docs: https://flask-login.readthedocs.io/en/latest/
It can be convenient to globally turn off authentication when unit testing. To enable this, if the application configuration variable LOGIN_DISABLED is set to True, this decorator will be ignored.

Categories

Resources