8
3

【Rails・Next.js】devise-token-authによるログイン認証 Part3

Posted at

はじめに

【Rails・Next.js】devise-token-authによるログイン認証のPart3です。
Part2はこちらです。

ユーザ新規作成APIの動作確認

  • メソッド: POST
  • URL: http://localhost:3000/api/v1/auth
  • HEADERS: Content-Type: application/json
Body
{
  "email": "test2@example.com",
  "password":"password",
  "confirm_success_url": "http://localhost:8000"
}

スクリーンショット 2023-12-15 16.50.24.png

200 OK がレスポンスとして返ってくること=ユーザーが新規作成できたことを確認してください。

一方、現状メール認証での確認ができておらず、confirmd_atがnilになっています。

  create_table "users", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
    t.string "provider", default: "email", null: false
    t.string "uid", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.boolean "allow_password_change", default: false
    t.datetime "remember_created_at"
    t.string "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string "unconfirmed_email"
    t.string "name"
    t.string "nickname"
    t.string "image"
    t.string "email"
    t.text "tokens"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["uid", "provider"], name: "index_users_on_uid_and_provider", unique: true
  end
[5] pry(main)> User.find(2).confirmed_at
  User Load (1.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
=> nil
[6] pry(main)> 

http://localhost:3000/letter_opener に認証用のメールが送信されているので、アカウントを有効化にします。

スクリーンショット 2023-12-15 17.13.48.png

この手続きにより、新規登録メール認証が完了したので次にログインAPIを動作確認します。

ログインAPIの動作確認

  • メソッド: POST
  • URL: http://localhost:3000/api/v1/auth/sign_in
  • HEADERS: Content-Type: application/json
Body
{
  "email": "test2@example.com",
  "password":"password"
}

スクリーンショット 2023-12-15 17.17.44.png

レスポンスにaccess-token,client,uidが含まれています。
Next側を実装する際に、これらの情報でログインユーザがどうかを判定していきます。

スクリーンショット 2023-12-15 17.24.14.png

ログインユーザ取得用アクションの実装

app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < ApplicationController
  alias_method :current_user, :current_api_v1_user
  alias_method :authenticate_user!, :authenticate_api_v1_user!
  alias_method :user_signed_in?, :api_v1_user_signed_in?
end

current_userauthenticate_user!,user_signed_in?がdeviseから提供されています。

これらのメソッド名で参照できるのはcontrollers配下であり、api/v1/xxxx_controllerの場合、current_api_v1_userというメソッド名で参照する必要があり、可読性が悪くなるためエイリアスを設定します。

ルーティングを追加します。

config/routes.rb
Rails.application.routes.draw do
  mount LetterOpenerWeb::Engine, at: "/letter_opener" if Rails.env.development?
  namespace :api do
    namespace :v1 do
      get "health_check", to: "health_check#index"
      mount_devise_token_auth_for "User", at: "auth"

      namespace :current do
        resource :user, only: [:show] #追加
      end
    end
  end
end

レスポンスボディを制御したいため、シリアライザーを導入します。

Gemfile
gem "active_model_serializers"
rails g serializer current_user
app/serializers/current_user_serializer.rb
class CurrentUserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email
end

コントローラを作成します。

rails g controller api/v1/current/users_controller
app/controllers/api/v1/current/users_controller.rb
class Api::V1::Current::UsersController < Api::V1::BaseController
  before_action :authenticate_user!

  def show
    render json: current_user, serializer: CurrentUserSerializer
  end
end

ログインユーザ取得用APIの動作確認

  • メソッド: GET
  • URL: http://localhost:3000/api/v1/current/user
  • HEADERS: 以下参照
HEADERS
access-token: ログインAPIで取得できた値
client: ログインAPIで取得できた値
uid: ログインAPIで取得できた値

スクリーンショット 2023-12-15 18.04.16.png

正常にレスポンスが確認でき、idnameemailのみデータが返ってきていれば実装完了です。

8
3
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
8
3