PROBLEM STATEMENT
I'm working on a flask app that uses Stormpath for authentication. In my app I have two user groups: normal users
and admins
. After a user logs in, I'd like to redirect them to a specific page based on the group they belong to. So if a user is a normal user they'd be redirected to /dashboard
and if they are an admin, they'd be redirected to /admin_dashboard
. As of right now, I have STORMPATH_REDIRECT_URL = '/dashboard'
so every time they log in they get redirected to /dashboard
regardless of the group they belong to. How can I redirect them to a specific page based on their Stormpath group?
CURRENT CODE SNIPPETS:
Note: I am using the default Flask-Stormpath login views and the app allows social login through Google.
/app/__init__.py:
def create_app(config_name):
...
# App config here
...
stormpath_manager = StormpathManager()
stormpath_manager.init_app(app)
...
return app
/config.py:
class Config(Object):
...
STORMPATH_REDIRECT_URL = '/dashboard'
...
/app/dashboard/views.py:
@dashboard_blueprint.route('/dashboard')
@login_required
@groups_required(['normal-users'])
def dashboard():
return render_template('dashboard/index.html', title="Dashboard")
@dashboard_blueprint.route('/admin_dashboard')
@login_required
@groups_required(['admins'])
def admin_dashboard():
return render_template('dashboard/admin_index.html', title="Admin Dashboard")
SOLUTION
flask_stormpath has a User
class as seen here, which takes in an Account
as an argument. From the stormpath-sdk-python
, we can see that an Account
has a has_group(self, resolvable)
function as seen here.
So to display a specific page after a user logs in, based on the group the user belongs to, I made the following changes to /app/dashboard/views.py
while keeping the others unchanged:
from flask_stormpath import User
from flask_stormpath import current_user
@dashboard_blueprint.route('/dashboard')
@login_required
def dashboard():
if User.has_group(current_user, 'normal-users'):
return render_template('dashboard/index.html', title="Dashboard")
elif User.has_group(current_user, 'admins'):
return render_template('dashboard/admin_index.html', title="Admin Dashboard")
else:
return render_template('dashboard/error.html', title="Error Page")