LoginSignup
4
4

More than 1 year has passed since last update.

devise_token_authについて

Posted at

devise_token_authについて

  • devise_token_authは、gemのインストール、その他簡単な設定を行うだけで、トークン認証を使用したAPIの実装が可能になるgemになります。

  • 今回は、導入までの手順及びcontrollerのカスタマイズについて学習したので、アウトプットとしてこの記事を作成します。

環境

  • Ruby ver 2.7.2

  • Rails ver 5.2.6

gemのインストール

  • まずは、下記のgemをGemfileに追加してください。
Gemfile
gem 'devise'
gem 'devise_token_auth'

追加したらbundle installしてください。

 deviseについては、devise_token_authに活用されているgemになりますが、これがインストールされていないとRailsのバージョンによっては、migrationファイルを作成する際にエラーが発生することがあります。

Userモデルの作成

  • bundle exec rails g devise_token_auth:install User authを実行してください。

  • コマンドの実行により、migrationファイル等が作成されますので、デフォルトの設定で問題なければ、bundle exec rails db:migrateしてください。

  • デフォルトの設定により、モデル内にはすでにコードが書かれていますが、必要に応じてrelationvalidatesを追加してください。

  • なお、注意点としてvalidatesについては、gemのデフォルト設定がありますので、確認してから追加しないと設定が崩れてしまうことがあります。

example/model/user.rb
# frozen_string_literal: true

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  include DeviseTokenAuth::Concerns::User
  has_many :articles, dependent: :destroy
  has_many :likes, dependent: :destroy
  has_many :comments, dependent: :destroy
  validates :nickname, uniqueness: true, presence: true
end

application_controllerの編集

  • application_controllerには下記のコードを追加してください。
app/contorllers/application_controller.rb

class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
end

  • このコードを追加することで、devise_token_authに定義されている様々なメソッドを使用できます。

ルーティングの変更

  • devise_token_authではデフォルト設定により、様々なroutesが設定されています。bundle exec rails routes | grep authでroutesを確認できます。
         new_user_session GET    /auth/sign_in(.:format)                                                                  devise_token_auth/sessions#new
             user_session POST   /auth/sign_in(.:format)                                                                  devise_token_auth/sessions#create
     destroy_user_session DELETE /auth/sign_out(.:format)                                                                 devise_token_auth/sessions#destroy
        new_user_password GET    /auth/password/new(.:format)                                                             devise_token_auth/passwords#new
       edit_user_password GET    /auth/password/edit(.:format)                                                            devise_token_auth/passwords#edit
            user_password PATCH  /auth/password(.:format)                                                                 devise_token_auth/passwords#update
                          PUT    /auth/password(.:format)                                                                 devise_token_auth/passwords#update
                          POST   /auth/password(.:format)                                                                 devise_token_auth/passwords#create
 cancel_user_registration GET    /auth/cancel(.:format)                                                                   devise_token_auth/registrations#cancel
    new_user_registration GET    /auth/sign_up(.:format)                                                                  devise_token_auth/registrations#new
   edit_user_registration GET    /auth/edit(.:format)                                                                     devise_token_auth/registrations#edit
        user_registration PATCH  /auth(.:format)                                                                          devise_token_auth/registrations#update
                          PUT    /auth(.:format)                                                                          devise_token_auth/registrations#update
                          DELETE /auth(.:format)                                                                          devise_token_auth/registrations#destroy
                          POST   /auth(.:format)                                                                          devise_token_auth/registrations#create
      auth_validate_token GET    /auth/validate_token(.:format)                                                           devise_token_auth/token_validations#validate_token

  • まずはroutes.rbで有効にしたいcontrollerの設定をします。
example/routes.rb
Rails.application.routes.draw do

  mount_devise_token_auth_for "User", at: "auth", controllers: {
        registrations: "devise_token_auth/registrations",
        sessions: "devise_token_auth/sessions"
      }
end

  • 上記例であれば、registrationsとsessionsのコントローラーが使用可能になっています。

コントローラーのカスタマイズ

  • デフォルト設定のコントローラーについては、公式ドキュメントを参照してください

  • このgemは、controller等についてgem内で定義されているので、デフォルトの設定を変更したい場合のみ、新たなcontrollerを作成し、継承元にデフォルト設定のcontroller名を記載します。
    例えばdevise_token_auth/registrations_controllerを作成する必要はありません。

  • controllerの変更については、まずroutes.rbを下記の例のように変更する必要があります。 なお今回はdevise_token_auth/registrationsapi/v1/auth/registrationsのように変更します。

example/routes.rb
Rails.application.routes.draw do
  namespace :api, format: "json" do
    namespace :v1 do
      mount_devise_token_auth_for "User", at: "auth", controllers: {
        registrations: "api/v1/auth/registrations"
      }
    end
  end
end

  • ルーティングの設定を変更した後は、bundle exec rails g controller api/v1/auth/registrationsによりregistrations_controller.rbを作成し、controllerは以下の例のようにしてください。
example/api/v1/registrations_controller.rb

class Api::V1::Auth::RegistrationsController < DeviseTokenAuth::RegistrationsController
  private

    def sign_up_params
      params.permit(:nickname, :email, :password)
    end
end

  • 上記のようにすることで、gemで定義されているcontrollerを継承することができます。 また、例のようにすることでdevise_token_auth/registrations_controller.rbで定義されているsign_up_paramsの設定を変更することができます。

参照

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4