Skip to content

Commit

Permalink
max_number_of_devices should be used in a new session as well
Browse files Browse the repository at this point in the history
  • Loading branch information
MaicolBen committed Mar 14, 2018
1 parent 7a83ada commit 76fca0e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
16 changes: 9 additions & 7 deletions app/models/devise_token_auth/concerns/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ def create_token(client_id: nil, token: nil, expiry: nil, **token_extras)
expiry: expiry
}.merge!(token_extras)

clean_old_tokens

[client_id, token, expiry]
end

Expand Down Expand Up @@ -196,25 +198,19 @@ def build_auth_header(token, client_id='default')

def update_auth_header(token, client_id='default')
headers = build_auth_header(token, client_id)
while tokens.length > 0 && DeviseTokenAuth.max_number_of_devices < tokens.length
oldest_client_id, _tk = tokens.min_by { |_cid, v| v[:expiry] || v["expiry"] }
tokens.delete(oldest_client_id)
end

clean_old_tokens
save!

headers
end


def build_auth_url(base_url, args)
args[:uid] = uid
args[:expiry] = tokens[args[:client_id]]['expiry']

DeviseTokenAuth::Url.generate(base_url, args)
end


def extend_batch_buffer(token, client_id)
self.tokens[client_id]['updated_at'] = Time.now
update_auth_header(token, client_id)
Expand Down Expand Up @@ -257,4 +253,10 @@ def remove_tokens_after_password_reset
end
end

def clean_old_tokens
while tokens.length > 0 && DeviseTokenAuth.max_number_of_devices < tokens.length
oldest_client_id, _tk = tokens.min_by { |_cid, v| v[:expiry] || v["expiry"] }
tokens.delete(oldest_client_id)
end
end
end
27 changes: 27 additions & 0 deletions test/controllers/devise_token_auth/sessions_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,33 @@ class DeviseTokenAuth::SessionsControllerTest < ActionController::TestCase
assert_equal '0.0.0.0', @new_last_sign_in_ip
end
end

describe "with multiple clients and headers don't change in each request" do
before do
DeviseTokenAuth.max_number_of_devices = 1
DeviseTokenAuth.change_headers_on_each_request = false
@tokens = []
(1..3).each do |n|
post :create,
params: {
email: @existing_user.email,
password: 'secret123'
}
@tokens << @existing_user.reload.tokens
end
end

test 'should delete old tokens' do
current_tokens = @existing_user.reload.tokens
assert_equal 1, current_tokens.count
assert_equal @tokens.pop.keys.first, current_tokens.keys.first
end

after do
DeviseTokenAuth.max_number_of_devices = 10
DeviseTokenAuth.change_headers_on_each_request = true
end
end
end

describe 'get sign_in is not supported' do
Expand Down

0 comments on commit 76fca0e

Please sign in to comment.