2018-11-19 21:18:17 +01:00
|
|
|
class API::V2::BaseController < ApplicationController
|
2022-09-28 12:40:44 +02:00
|
|
|
# Disable forgery protection for API controllers when the request is authenticated
|
|
|
|
# with a bearer token. Otherwise the session will be nullified and we'll lose curent_user
|
|
|
|
protect_from_forgery with: :null_session, unless: :token?
|
|
|
|
skip_before_action :setup_tracking
|
|
|
|
prepend_before_action :authenticate_administrateur_from_token
|
2018-11-19 21:18:17 +01:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def context
|
2022-11-30 10:14:23 +01:00
|
|
|
# new token
|
|
|
|
if api_token.present?
|
2023-02-13 14:57:51 +01:00
|
|
|
api_token.context
|
2022-10-03 18:08:03 +02:00
|
|
|
# web interface (/graphql) give current_administrateur
|
|
|
|
elsif current_administrateur.present?
|
2023-02-13 14:57:51 +01:00
|
|
|
{
|
|
|
|
administrateur_id: current_administrateur.id,
|
|
|
|
procedure_ids: current_administrateur.procedure_ids,
|
|
|
|
write_access: true
|
|
|
|
}
|
2022-10-03 18:08:03 +02:00
|
|
|
# old token
|
2022-09-28 12:40:44 +02:00
|
|
|
else
|
2023-02-13 14:57:51 +01:00
|
|
|
{
|
|
|
|
token: authorization_bearer_token,
|
|
|
|
write_access: true
|
|
|
|
}
|
2022-09-28 12:40:44 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def token?
|
|
|
|
authorization_bearer_token.present?
|
2018-11-19 21:18:17 +01:00
|
|
|
end
|
|
|
|
|
2022-11-30 10:14:23 +01:00
|
|
|
def authenticate_administrateur_from_token
|
|
|
|
if api_token.present?
|
|
|
|
@current_user = api_token.administrateur.user
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def api_token
|
|
|
|
if @api_token.nil?
|
|
|
|
@api_token = APIToken.find_and_verify(authorization_bearer_token) || false
|
|
|
|
end
|
|
|
|
@api_token
|
|
|
|
end
|
|
|
|
|
2018-11-19 21:18:17 +01:00
|
|
|
def authorization_bearer_token
|
2022-09-28 12:40:44 +02:00
|
|
|
@authorization_bearer_token ||= begin
|
|
|
|
received_token = nil
|
|
|
|
authenticate_with_http_token do |token, _options|
|
|
|
|
received_token = token
|
|
|
|
end
|
|
|
|
received_token
|
|
|
|
end
|
|
|
|
end
|
2018-11-19 21:18:17 +01:00
|
|
|
end
|