devise token auth and devise duplication in controllers

615 Views Asked by At

I have put together a Rails 6 backend with Devise and Devise token auth and a frontend Angular Nativescript application which uses the API. Ref;

Backend: https://github.com/map7/backend_rails6_template

Mobile Frontend: https://github.com/map7/frontend_nativescript

My question is, do I have to duplicate my controllers for the API and Web pages if I don't need versioning?

Devise_token_auth suggests I need namespacing if I'm going to use it alongside Devise.

At the moment I have a Home Controller for the Rails views;

class HomeController < ApplicationController
  before_action :authenticate_user!
end

Which uses this ApplicationController

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end

For the API calls I have another Home Controller in api/v1/home_controller with the following;

module Api
  module V1
    class HomeController < ApplicationController
      before_action :authenticate_user!
      
      def index
        render json: {message: "Welcome to the Ruby on Rails backend"}
      end
    end
  end
end

Which uses this ApplicationController

module Api
  module V1
    class ApplicationController < ActionController::API
      include DeviseTokenAuth::Concerns::SetUserByToken
      before_action :authenticate_user!
      before_action :configure_permitted_parameters, if: :devise_controller?
      
      protected

      def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_in, keys: [:email, :password])
      end
    end
  end
end

My routes.rb file looks like;

Rails.application.routes.draw do
  devise_for :users             # Standard devise routes must come first!
  resources :home, only: [:index]
  root to: "home#index"

  namespace :api, defaults: {format: 'json'} do # namespace devise token routes to stop duplication
    namespace :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
      resources :home, only: [:index]
    end
  end
end

It may not look like much duplication for now but I'm trying to convert a large app in which there would be a large amount of duplication. If I try to call the /home route for the API call then I get an 'unauthorized error'.

0

There are 0 best solutions below