From 6e5678d1c2aa60e3a2d8285698e7f4750d86dc95 Mon Sep 17 00:00:00 2001 From: simon lehericey Date: Thu, 21 Dec 2023 13:59:21 +0100 Subject: [PATCH] feature(api): add forbidden_network? to api_token --- app/models/api_token.rb | 6 ++++++ spec/models/api_token_spec.rb | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/app/models/api_token.rb b/app/models/api_token.rb index 9245e0cd8..da02cba23 100644 --- a/app/models/api_token.rb +++ b/app/models/api_token.rb @@ -65,6 +65,12 @@ class APIToken < ApplicationRecord end end + def forbidden_network?(ip) + return false if authorized_networks.blank? + + authorized_networks.none? { |range| range.include?(ip) } + end + class << self def generate(administrateur) plain_token = generate_unique_secure_token diff --git a/spec/models/api_token_spec.rb b/spec/models/api_token_spec.rb index 1afc9dfdc..df70d5b2c 100644 --- a/spec/models/api_token_spec.rb +++ b/spec/models/api_token_spec.rb @@ -177,4 +177,36 @@ describe APIToken, type: :model do it { is_expected.to eq([IPAddr.new(ip)]) } end end + + describe '#forbidden_network?' do + let(:api_token_and_packed_token) { APIToken.generate(administrateur) } + let(:api_token) { api_token_and_packed_token.first } + let(:authorized_networks) { [] } + + before { api_token.update!(authorized_networks: authorized_networks) } + + subject { api_token.forbidden_network?(ip) } + + context 'when no authorized networks are defined' do + let(:ip) { '192.168.1.1' } + + it { is_expected.to be_falsey } + end + + context 'when a single authorized network is defined' do + let(:authorized_networks) { [IPAddr.new('192.168.1.0/24')] } + + context 'and the request comes from it' do + let(:ip) { '192.168.1.1' } + + it { is_expected.to be_falsey } + end + + context 'and the request does not come from it' do + let(:ip) { '192.168.2.1' } + + it { is_expected.to be_truthy } + end + end + end end