base_controller.rb 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. module Blazer
  2. class BaseController < ApplicationController
  3. # skip all filters
  4. filters = _process_action_callbacks.map(&:filter)
  5. if Rails::VERSION::MAJOR >= 5
  6. skip_before_action(*filters, raise: false)
  7. skip_after_action(*filters, raise: false)
  8. skip_around_action(*filters, raise: false)
  9. else
  10. skip_action_callback *filters
  11. end
  12. protect_from_forgery with: :exception
  13. if ENV["BLAZER_PASSWORD"]
  14. http_basic_authenticate_with name: ENV["BLAZER_USERNAME"], password: ENV["BLAZER_PASSWORD"]
  15. end
  16. if Blazer.before_action
  17. before_action Blazer.before_action
  18. end
  19. layout "blazer/application"
  20. private
  21. def process_vars(statement, data_source)
  22. (@bind_vars ||= []).concat(extract_vars(statement)).uniq!
  23. @bind_vars.each do |var|
  24. params[var] ||= Blazer.data_sources[data_source].variable_defaults[var]
  25. end
  26. @success = @bind_vars.all? { |v| params[v] }
  27. if @success
  28. @bind_vars.each do |var|
  29. value = params[var].presence
  30. if value
  31. if value =~ /\A\d+\z/
  32. value = value.to_i
  33. elsif value =~ /\A\d+\.\d+\z/
  34. value = value.to_f
  35. end
  36. end
  37. if var.end_with?("_at")
  38. value = Blazer.time_zone.parse(value) rescue nil
  39. end
  40. value.gsub!(" ", "+") if ["start_time", "end_time"].include?(var) # fix for Quip bug
  41. statement.gsub!("{#{var}}", ActiveRecord::Base.connection.quote(value))
  42. end
  43. end
  44. end
  45. def parse_smart_variables(var, data_source)
  46. query = data_source.smart_variables[var]
  47. if query.is_a? Hash
  48. smart_var = query.map { |k,v| [v, k] }
  49. elsif query.is_a? Array
  50. smart_var = query.map { |v| [v, v] }
  51. elsif query
  52. result = data_source.run_statement(query)
  53. smart_var = result.rows.map { |v| v.reverse }
  54. error = result.error if result.error
  55. end
  56. return smart_var, error
  57. end
  58. def extract_vars(statement)
  59. # strip commented out lines
  60. # and regex {1} or {1,2}
  61. statement.gsub(/\-\-.+/, "").gsub(/\/\*.+\*\//m, "").scan(/\{\w*?\}/i).map { |v| v[1...-1] }.reject { |v| /\A\d+(\,\d+)?\z/.match(v) || v.empty? }.uniq
  62. end
  63. helper_method :extract_vars
  64. def variable_params
  65. params.except(:controller, :action, :id, :host, :query, :dashboard, :query_id, :query_ids, :table_names, :authenticity_token, :utf8, :_method, :commit, :statement, :data_source, :name, :fork_query_id, :blazer).permit!
  66. end
  67. helper_method :variable_params
  68. def blazer_user
  69. send(Blazer.user_method) if Blazer.user_method && respond_to?(Blazer.user_method)
  70. end
  71. helper_method :blazer_user
  72. end
  73. end