Skip to content

Instantly share code, notes, and snippets.

@skyforest
Created February 2, 2023 14:51
Show Gist options
  • Save skyforest/0a5e32491156c0650ef4ce1fa5afc3ac to your computer and use it in GitHub Desktop.
Save skyforest/0a5e32491156c0650ef4ce1fa5afc3ac to your computer and use it in GitHub Desktop.
An example flask decorator that checks if the current users has 'saml_user' in session and redirects to the login flow if not.
from functools import wraps
from flask import request, redirect, url_for
# custom decorator
def check_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if 'saml_user' not in session:
return redirect(url_for('login'))
return func(*args, **kwargs)
return decorated
# route with decorator
@app.route('/hello/')
@check_auth
def hello():
return render_template('hello.html')
@skyforest
Copy link
Author

The check_auth decorator checks if the saml_user is in the session. If it is not present, the user is redirected to the login page. If the saml_user is present, the original function is called.

This code requires python3-saml and have properly added the authenticated user to the session under the key saml_user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment