Module: FirebaseAuth::ControllerHelpers::ClassMethods

Defined in:
lib/firebase_auth/controller_helpers.rb

Instance Method Summary collapse

Instance Method Details

#authenticate_with_firebase(model_name) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/firebase_auth/controller_helpers.rb', line 8

def authenticate_with_firebase(model_name)
  define_method("authenticate_#{model_name.downcase}") do
    id_token = request.headers['Authorization']&.split(' ')&.last
    if id_token
      project_id = Rails.application.credentials.dig(:firebase, :project_id)
      decoded_token = FirebaseAuthService::FirebaseAuthService.new(project_id).verify_id_token(id_token)
      if decoded_token
        instance_variable_set("@current_#{model_name.downcase}", model_name.constantize.find_by(email: decoded_token['email']))
      end
    end
    unless instance_variable_get("@current_#{model_name.downcase}")
      render json: { error: 'Unauthorized' }, status: :unauthorized
    end
  end
  before_action "authenticate_#{model_name.downcase}".to_sym
end