demarches-normaliennes/app/controllers/api_controller.rb

45 lines
1.2 KiB
Ruby
Raw Normal View History

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
before_action :ensure_authorized_network, if: -> { @api_token.present? }
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
2023-09-20 09:28:03 +02:00
def check_api_token
if @api_token.nil?
render json: {}, status: :unauthorized
end
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])
end
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
end
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
2017-04-04 15:27:04 +02:00
end