Using Multiple User Classes

View Live Multi-User Demos

This gem supports the use of multiple user models. One possible use case is to authenticate visitors using a model called User, and to authenticate administrators with a model called Admin. Take the following steps to add another authentication model to your app:
  1. 1.
    Run the install generator for the new model.
    1
    rails g devise_token_auth:install Admin admin_auth
    Copied!
    This will create the Admin model and define the model's authentication routes with the base path /admin_auth.
  2. 2.
    Define the routes to be used by the Admin user within a devise_scope.
    Example:
    1
    Rails.application.routes.draw do
    2
    # when using multiple models, controllers will default to the first available
    3
    # devise mapping. routes for subsequent devise mappings will need to defined
    4
    # within a `devise_scope` block
    5
    6
    # define :users as the first devise mapping:
    7
    mount_devise_token_auth_for 'User', at: 'auth'
    8
    9
    # define :admins as the second devise mapping. routes using this class will
    10
    # need to be defined within a devise_scope as shown below
    11
    mount_devise_token_auth_for "Admin", at: 'admin_auth'
    12
    13
    # this route will authorize requests using the User class
    14
    get 'demo/members_only', to: 'demo#members_only'
    15
    16
    # routes within this block will authorize requests using the Admin class
    17
    devise_scope :admin do
    18
    get 'demo/admins_only', to: 'demo#admins_only'
    19
    end
    20
    end
    Copied!
  3. 3.
    Configure any Admin restricted controllers. Controllers will now have access to the methods described here:
    • before_action :authenticate_admin!
    • current_admin
    • admin_signed_in?

Group access

It is also possible to control access to multiple user types at the same time using groups. The following example shows how to limit controller access to both User and Admin users.

Example: group authentication

1
class DemoGroupController < ApplicationController
2
devise_token_auth_group :member, contains: [:user, :admin]
3
before_action :authenticate_member!
4
5
def members_only
6
render json: {
7
data: {
8
message: "Welcome #{current_member.name}",
9
user: current_member
10
}
11
}, status: 200
12
end
13
end
Copied!
In the above example, the following methods will be available (in addition to current_user, current_admin, etc.):
  • before_action: :authenticate_member!
  • current_member
  • member_signed_in?