RushRed
RushRed

Reputation: 75

Rails: How to track users last logged in ip address?

How would I go about tracking the last IP address of a signed in user not the current as I'm sure that can be achieved by

@ip = request.remote_ip

Upvotes: 1

Views: 1472

Answers (3)

jedi
jedi

Reputation: 2198

Use Devise gem for authentication (if not familiar with yet). It offers IP tracking out of the box

Upvotes: 1

Raaj Baskaran
Raaj Baskaran

Reputation: 85

Storing the current user's IP address is how you will have access to the IP address of the last user. If for every session you recorded the IP address of the person logged in, you will eventually have a record of all the users that have ever logged in. To get the last user's IP address, just query for the last record that was added.

A simple solution is to create a table with one column and add to it as you go.

Here is what the migration file is going to look like.

class CreateUserIp < ActiveRecord::Migration[5.0]
  def change
    create_table :user_ip do |t|
      t.string :ip_address

      t.timestamps
    end
  end
end

Be sure to run the migration from the terminal

rails db:migrate

Now, every time a user logs in, for every session you can insert the current IP address into the table.

UserIp.create(ip_address: request.remote_ip)

Now you can retrieve the latest record like so,

last_users_ip = UserIp.order(created_at: :asc).reverse_order.limit(10).reverse.first

There you go!

Upvotes: 1

rselvaganesh
rselvaganesh

Reputation: 1122

It is better to use request.remote_ip that's simple and it works.

class ApplicationController < ActionController::Base
      def remote_ip
        if request.remote_ip == '127.0.0.1'
          # Hard coded remote address
          '123.45.67.89'
        else
          request.remote_ip
        end
      end
    end

    class MyController < ApplicationController
      def index
        @client_ip = remote_ip()
      end
    end

When you visit a site locally you're coming from the local IP address, ie 127.0.0.1.

What you're doing is the correct way to the visitors IP address, and the result you're seeing is as expected.

You want to use

@ip = request.remote_ip

because that takes into account most cases of reverse proxies and other situations you might encounter where request.env['REMOTE_ADDR'] might be nil or the address of the local proxy.

Upvotes: 0

Related Questions