Authenticated session data

Brooks Swinnerton edited this page Sep 16, 2015 · 5 revisions

Warden scopes provide a mechanism to allow multiple authenticated to reside within a single session.

As an example, consider that you have two scopes that you use. :admin, and :user. The :user scope is used when a general user logs in, and is used for access to the application. The :admin scope is used to login users who are admins. This is not really about authorization, this is just a way to organize your session. It's up to you to decide what the difference is between them in the strategy.

Now, consider that this :admin is logged in, and wants to view your site as a particular user. We can log in both users into the same session to allow the admin to impersonate the user and visit the site.

warden = env['warden']
if warden.authenticated?(:admin)
  warden.authenticated?(:user) && warden.logout(:user)
  warden.set_user(@user, scope: :user)
end

Now go visit your site logged in as @user. During your visit to the site with the :user scope (default) you might store things into the session.

env['warden'].session(:user)[:redirect_back] = "/some/url"

This will store {redirect_back: "/some/url"}. This data is scoped to the :user scope. If we expand the impersonation example above a little to use this technique.

warden = env['warden']
if warden.authenticated?(:admin)
  warden.authenticated?(:user) && warden.logout(:user)
  warden.session(:admin)[:redirect_back] = "/admin/path/to/somewhere"
  warden.set_user(@user, scope: :user)
end

Now when we set the user session data, we now have two :redirect_back keys in the session. One for the admin, and one for the user.

warden.session(:admin)[:redirect_back] # "/admin/path/to/somewhere"
warden.session(:user)[:redirect_back]  # "/some/url"

The two sets of session data are scoped, but still reside in the same session. Now lets assume that we've stopped impersonating.

warden = env['warden']
warden.authenticated?(:admin) && warden.authenticated?(:user) # activate both sessions
warden.logout(:user) # log out only the user session, and only the user session data is cleared.

redirect_to warden.session(:admin)[:redirect_back] || "/admin"

When you log out the user in the example above, the user is removed from the overall session (they're logged out) but their scoped session data is also cleared. The admin's scoped session data is, however, left intact.

If you just want to log out all sessions and clear all session data:

env['warden'].logout

When no scope is given, all known scopes are logged out and all known data is cleared. Before you call this, you'll need to at least call

env['warden'].authenticated?(scope)

for each scope. This makes warden aware of the scopes.