devise_token_auth gem - thuy-econsys/rails_app GitHub Wiki

for adding gem to already created file

add devise_token_auth gem to Gemfile.

Model

add tokens attribute to User:

rails g migration AddDeviseTokenAuthToUsers tokens:json

if provider and uid attribute not already added:

rails g migration AddAuthColumnsToUsers uid:string provider:string

in the migration table, add indices to uid and provider:

class AddAuthColumnsToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :provider, :string,   null: false, default: "email"
    add_column :users, :uid, :string,        null: false, default: ""

    add_index :users, [:uid, :provider],     unique: true
  end
end

be aware of the fact that Devise Auth Token depends on Devise Confirmable

in the User model, be sure to include Rails Concern DeviseTokenAuth inside the User class and extend the Devise Models so that you can access Devise Modules.

app/models/user.rb

class User < ApplicationRecord
  extend Devise::Models # to access Devise 
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  include DeviseTokenAuth::Concerns::User
end

Controller

add concern to the base ApplicationController to allow access to authentication controller methods as well as an after_action that allows for auth token to be changed after each request:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
end

CORS

add gem gem 'rack-cors', :require => 'rack/cors' to Gemfile.

configure how API will be able to handle Cross-Origin Resource Sharing (CORS):

Rails.application.config.middleware.insert_before 0, Rack::Cors do 
  allow do
    origins 'http://localhost:3000'
    # limit to just authorize passthru and/or callback?
    resource '*',
      headers: :any,
      expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
      methods: [:get, :post]
  end
end

Cross Origin Requests (CORS) | devise-token-auth Documentation

References