LoginSignup
0
1

More than 5 years have passed since last update.

DeviseAuthTokenでログイン時に返される値を変更する

Posted at

2018-06-25

Rails (5.0.7)
devise (4.4.3)
devise_token_auth (0.1.43)

はじめに

Diviseでログイン認証をする際に返却されるユーザー情報の項目を修正したかったが、日本語の記事が見当たらなかったので投稿してみた。(あるのかなぁ探せなかった)

1. Userモデル

models/user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
          :confirmable,
          :recoverable, :rememberable, :trackable, :validatable

...
...

  # 追記
  def token_validation_response                                                                                                                                         
    Api::App::UserSerializer.new( self, root: false )

  end

end

2. UserSerializer

serializeres/user_serializer.rb
module Api
  module App
    class UserSerializer < ActiveModel::Serializer
      attributes :id, :email,

        # 追加したい項目を追加
        :confirmed_at,

        :created_at, :updated_at
    end
  end
end


結果

json
{
    "data": {
        "id": 1,
        "email": "ex@example.com",
        "confirmed_at": "2018-04-24T09:35:29.488Z",
        "created_at": "2018-06-21T00:47:20.161Z",
        "updated_at": "2018-06-25T06:16:44.449Z"
    }
}

めでたしめでたし。

参考

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