0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

railsのdeviseでuser agentもtrackする

Posted at

0. 前提

deviseが導入済み
devise trackableを導入済み

1. カラムの追加

今回はusers tableとします
current_sign_in_ip, にならい、current_とlast_と2つ作成します

add_column :users, :current_sign_in_user_agent, :string
add_column :users, :last_sign_in_user_agent, :string

2. config/initializers/devise.rbに追加

ファイル作ってもいんですけど、今回はdeviseを設定した直後にします

Devise.setup do |config|
  # ~~~
end

module DeviseExt
  module Models
    module Trackable
      def self.required_fields(klass)
        super + [ :current_sign_in_user_agent, :last_sign_in_user_agent ]
      end

      def update_tracked_fields(request)
        super
        old_current, new_current = self.current_sign_in_user_agent, extract_user_agent_from(request)
        self.last_sign_in_user_agent = old_current || new_current
        self.current_sign_in_user_agent = new_current
      end

      protected

      def extract_user_agent_from(request)
        request.user_agent
      end
    end
  end
end

Devise::Models::Trackable.prepend DeviseExt::Models::Trackable

3. 動作確認

Started POST "/users/sign_in" for ::1 at 2024-12-26 14:04:44 +0900
Processing by Devise::SessionsController#create as HTML
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"[FILTERED]", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
  User Load (1.4ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'test@example.com' ORDER BY "users"."id" ASC LIMIT 1 /*action='create',application='OidcServer',controller='sessions'*/
  TRANSACTION (0.2ms)  BEGIN /*action='create',application='OidcServer',controller='sessions'*/
  User Update (1.6ms)  UPDATE "users" SET "sign_in_count" = 2, "current_sign_in_at" = '2024-12-26 05:04:44.812636', "current_sign_in_user_agent" = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', "last_sign_in_user_agent" = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', "updated_at" = '2024-12-26 05:04:44.812949' WHERE "users"."id" = 1 /*action='create',application='OidcServer',controller='sessions'*/
  TRANSACTION (1.4ms)  COMMIT /*action='create',application='OidcServer',controller='sessions'*/
Redirected to http://localhost:3000/
Completed 303 See Other in 302ms (ActiveRecord: 4.5ms (2 queries, 0 cached) | GC: 6.1ms)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?