Skip to content

Commit

Permalink
Split IP resolution from update_tracked_fields
Browse files Browse the repository at this point in the history
This permits users to easily customize where the ip address
should be resolved.  When fronting the application with a webserver or
load balancer, the ip address may be the server and not be the user.

E.g. consider the IP address is passed as the header: "X-Forwarded-For".

```ruby
class User
  devise :trackable

  protected
    def extract_ip_from(request)
      request.headers["X-Forwarded-For"]
    end
end
```
  • Loading branch information
mckramer authored and tegon committed Apr 3, 2018
1 parent 20bde34 commit b20de50
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/devise/models/trackable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def update_tracked_fields(request)
self.last_sign_in_at = old_current || new_current
self.current_sign_in_at = new_current

old_current, new_current = self.current_sign_in_ip, request.remote_ip
old_current, new_current = self.current_sign_in_ip, extract_ip_from(request)
self.last_sign_in_ip = old_current || new_current
self.current_sign_in_ip = new_current

Expand All @@ -39,6 +39,13 @@ def update_tracked_fields!(request)
update_tracked_fields(request)
save(validate: false)
end

protected

def extract_ip_from(request)
request.remote_ip
end

end
end
end
18 changes: 18 additions & 0 deletions test/models/trackable_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,22 @@ class TrackableTest < ActiveSupport::TestCase

assert_not user.update_tracked_fields!(request)
end

test 'extract_ip_from should be overridable' do
class UserWithOverride < User
protected
def extract_ip_from(request)
"127.0.0.2"
end
end

request = mock
request.stubs(:remote_ip).returns("127.0.0.1")
user = UserWithOverride.new

user.update_tracked_fields(request)

assert_equal "127.0.0.2", user.current_sign_in_ip
assert_equal "127.0.0.2", user.last_sign_in_ip
end
end

0 comments on commit b20de50

Please sign in to comment.