如何获取用户的IP地址的最后一次登录以及当前登录用户的IP地址?

问题描述 投票:-1回答:1

我在rails框架中使用'devise'gem来验证如何获得用户的IP地址的最后登录,并且用户的IP地址的当前登录是可能的设计或任何其他替代方式来获得它。

ruby-on-rails session devise ruby-on-rails-5
1个回答
1
投票

在您的控制器中,您可以通过request.remote_ip访问当前的IP。

因此,您可以覆盖authenticate_user!设计方法,或者只是简单地编写自己的before_action。这需要current_ip模型上的User列。

class ApplicationController < ActionController::Base
  before_action :hit_user

  def current_ip
    # request is the object that carries all the information from the 
    # request to the controller
    request.remote_ip
  end

  private

  def hit_user
    current_user.hit!(current_ip) 
  end
end

class User < ApplicationRecord
  def hit!(current_ip)
    # use update_attribute since this happens on every request and you 
    # dont want to trigger User validations all the time
    self.update_attribute(current_ip: current_ip)
  end
end

这样,您就拥有了current_ip和用于请求的最后一个。

© www.soinside.com 2019 - 2024. All rights reserved.