2024-04-29 00:17:15 +02:00
# frozen_string_literal: true
2015-12-21 17:51:49 +01:00
class APIController < ApplicationController
2018-03-16 10:10:43 +01:00
before_action :default_format_json
2023-09-20 09:28:03 +02:00
before_action :authenticate_from_token
2023-12-21 14:00:07 +01:00
before_action :ensure_authorized_network , if : - > { @api_token . present? }
2024-01-17 09:31:21 +01:00
before_action :ensure_token_is_not_expired , if : - > { @api_token . present? }
2018-09-26 15:39:45 +02:00
2023-10-17 12:00:16 +02:00
before_action do
Current . browser = 'api'
end
2018-09-26 16:27:58 +02:00
private
2016-02-19 16:59:18 +01:00
def default_format_json
2018-01-11 19:04:39 +01:00
request . format = " json " if ! request . params [ :format ]
2016-02-19 16:59:18 +01:00
end
2018-08-24 15:53:57 +02:00
2023-09-20 09:28:03 +02:00
def check_api_token
if @api_token . nil?
render json : { } , status : :unauthorized
end
2018-09-26 15:39:45 +02:00
end
2023-09-20 09:28:03 +02:00
def authenticate_from_token
@api_token = authenticate_with_http_token { | t , _o | APIToken . authenticate ( t ) }
# legacy way of sending the token by url
# not available in api v2
if @api_token . nil?
@api_token = APIToken . authenticate ( params [ :token ] )
2018-08-24 15:53:57 +02:00
end
2018-09-26 15:39:45 +02:00
2023-09-20 09:28:03 +02:00
if @api_token . present?
@api_token . touch ( :last_v1_authenticated_at )
2023-12-21 15:58:03 +01:00
@api_token . store_new_ip ( request . remote_ip )
2023-09-20 09:28:03 +02:00
@current_user = @api_token . administrateur . user
end
2018-09-26 15:39:45 +02:00
end
2023-12-21 14:00:07 +01:00
def ensure_authorized_network
if @api_token . forbidden_network? ( request . remote_ip )
address = IPAddr . new ( request . remote_ip )
render json : { errors : [ " request issued from a forbidden network. Add #{ address . to_string } / #{ address . prefix } to your allowed adresses in your /profil " ] } , status : :forbidden
end
end
2024-01-17 09:31:21 +01:00
def ensure_token_is_not_expired
if @api_token . expired?
render json : { errors : [ 'token expired' ] } , status : :unauthorized
end
end
2017-04-04 15:27:04 +02:00
end