LoginSignup
0
0

【Rails】devise-token-authを用いたユーザー登録機能の作成

Posted at

devise_token_authを用いたログイン機能の実装を備忘録として残します。

・Gemファイルの準備/インストール

Gemfileにdevise_token_authをGemに準備する。
以下の内容をGemfileに記載し、bundle installを行う。

Gemfile
gem "rack-cors"
gem 'devise'
gem 'devise_token_auth'
gem 'devise-i18n'

下記の2つのコマンドを実行することで、devise_token_authをインストールする。

rails g devise:install
rails g devise_token_auth:install User auth

・ログイン機能の実装

まずは認証のコントローラーを準備するため、下記のコマンドを実行する。

rails g controller api/v1/registrations

できたコントローラーファイルを下記のように修正する。
classを設定することで、DeviseTokenAuth::RegistrationsControllerを引き継ぐ設定ができる。

api/v1/auth/registrations_controller.rb
class Api::V1::Auth::RegistrationsController < DeviseTokenAuth::RegistrationsController
  private

    def sign_up_params
      params.permit(:name, :email, :password, :password_confirmation)
    end
    
    def account_update_params
      params.permit(:name, :email)
    end
end

sign_up_params ⇒ サインアップ(新規登録)の際に必要とするデータ
account_update_params ⇒ 登録情報の更新をすることができるデータ

・ルーティングを修正

api/v1/authでコントローラーを作成したため、ルーティングは下記のように書き換える。

config/routes.rb
Rails.application.routes.draw do
  root to: "home#index"

  namespace :api do
    namespace :v1 do
      mount_devise_token_auth_for "User", at: "auth", controllers: {
        registrations: "api/v1/auth/registrations"
      }
      resources :articles
    end
  end
end

namespaceは名前空間の中にルーティングをグループ化するときに使われる。
これにより、関連ルートが視覚的にグループ化され、コードの整理や保守がしやすくなる。
mount_devise_token_auth_for 'User', at: 'auth'とは
サインインやサインアウトなどの認証ができるようにするために書く必要がある。

・devise_token_auth.rbを修正

config/initializers/devise_token_auth.rb
DeviseTokenAuth.setup do |config|
#中略
config.change_headers_on_each_request = false
#元々はtrueのものをfalseに書き換える
#リクエストの度に毎回ヘッダーの情報が変わらないようにしている

#中略
config.token_lifespan = 2.weeks
#トークンが有効な期間を2週間としている

#中略
config.headers_names = { 'access-token': "access-token",
                           client: "client",
                           expiry: "expiry",
                           uid: "uid",
                           'token-type': "token-type" }
#ヘッダーに書き込まれる情報を上記のように修正している。

以上で、ユーザー登録機能が実装できています。
Postman等で処理が通るか確認してください。

0
0
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
0
0