Skip to content

How to add multiple user's type for Devise authentication

Maicol Bentancor edited this page Dec 22, 2017 · 2 revisions

In order to add a new kind of user to the API, add a new model that represents the new kind of user, for example "developer":

class Developer < ApplicationRecord
  include Authenticable
  include DeviseTokenAuth::Concerns::User
end

In routes.rb, add the devise routes to the new resource:

 mount_devise_token_auth_for 'Developer', at: '/api/v1/developers', controllers: {
    registrations:  'api/v1/registrations',
    sessions:  'api/v1/sessions',
    passwords:  'api/v1/passwords'
  }

In SessionController and RegistrationController change user per resource_name when requiring params, rendering info, etc. For example, instead of:

def resource_params
  params.require(:user).permit(:email, :password)
end

do

def resource_params
  params.require(resource_name).permit(:email, :password)
end

Create a controller per each kind of user (DeveloperApiController) that inherit from the ApiController to authenticate that kind of user or apply any callbacks to the endpoints of a specific user, for example:

module Api
  module V1
    class DevelopersApiController < Api::V1::ApiController
      before_action :authenticate_developer!, except: :status
    end
  end
end

As an optional, we can define a generic current_user or current_resource in the ApiController that is the OR of all the different current_kind_of_user, for example:

def current_resource
  current_developer || current_user
end