# frozen_string_literal: true
#
class PanelController < ApplicationController

  before_filter :authenticate_user_from_token!
  before_action :authenticate_user!
  after_filter  :set_csrf_cookie_for_ng
  load_and_authorize_resource except: [:create]

  #
  def set_csrf_cookie_for_ng
    cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
  end

  # before_filter do
  #   resource = controller_path.singularize.gsub('/', '_').to_sym
  #   method = 'item_params'
  #   params[resource] &&= send(method) if respond_to?(method, true)
  # end

  private

  def authenticate_user_from_token!
    user_email = params[:user_email].presence
    user       = user_email && User.find_by_email(user_email)
    if user && Devise.secure_compare(user.authentication_token, params[:user_token])
      sign_out current_user if current_user
      sign_in user
      redirect_to url_for(params.permit(:anchor)) and return
    end
  end

  protected

  def verified_request?
    super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
  end
end
