feature(api): store any ip used

This commit is contained in:
simon lehericey 2023-12-21 15:58:03 +01:00
parent b127f13515
commit afb6eacf57
4 changed files with 29 additions and 0 deletions

View file

@ -41,6 +41,7 @@ class API::V2::BaseController < ApplicationController
if @api_token.present? if @api_token.present?
@api_token.touch(:last_v2_authenticated_at) @api_token.touch(:last_v2_authenticated_at)
@api_token.store_new_ip(request.remote_ip)
@current_user = @api_token.administrateur.user @current_user = @api_token.administrateur.user
Current.user = @current_user Current.user = @current_user
end end

View file

@ -29,6 +29,7 @@ class APIController < ApplicationController
if @api_token.present? if @api_token.present?
@api_token.touch(:last_v1_authenticated_at) @api_token.touch(:last_v1_authenticated_at)
@api_token.store_new_ip(request.remote_ip)
@current_user = @api_token.administrateur.user @current_user = @api_token.administrateur.user
end end
end end

View file

@ -58,6 +58,13 @@ class APIToken < ApplicationRecord
Base64.urlsafe_encode64(id).slice(0, 5) Base64.urlsafe_encode64(id).slice(0, 5)
end end
def store_new_ip(ip)
set = Set.new(stored_ips)
if set.add?(IPAddr.new(ip))
update!(stored_ips: set.to_a)
end
end
class << self class << self
def generate(administrateur) def generate(administrateur)
plain_token = generate_unique_secure_token plain_token = generate_unique_secure_token

View file

@ -157,4 +157,24 @@ describe APIToken, type: :model do
it { is_expected.to be_nil } it { is_expected.to be_nil }
end end
end end
describe '#store_new_ip' do
let(:api_token) { APIToken.generate(administrateur).first }
let(:ip) { '192.168.0.1' }
subject do
api_token.store_new_ip(ip)
api_token.stored_ips
end
context 'when none ip is stored' do
it { is_expected.to eq([IPAddr.new(ip)]) }
end
context 'when the ip is already stored' do
before { api_token.update!(stored_ips: [ip]) }
it { is_expected.to eq([IPAddr.new(ip)]) }
end
end
end end