module Api
  module V1
    class BaseController < ApplicationController
   	before_filter :verify_server
    respond_to :json
    skip_before_filter :verify_authenticity_token

     private
      def authorize_client
      	verify_client || render_unauthorized
      end

      def verify_server
        restrict_access || render_server_unauthorized
      end

      def restrict_access
      	authenticate_or_request_with_http_token do |token, options|
	       ApiKey.pluck(:access_token).include?(token)
		    end
      end

      def render_server_unauthorized
        self.headers['WWW-Authenticate'] = 'Token realm="Application"'
        render json: 'Invalid Authorization Token', status: 401
      end

      def verify_client
      	site_token = request.headers[:HTTP_X_SITETOKEN]
      	site_id = request.headers[:HTTP_X_SITEID]
		    client_status  = Client.where(site_token: site_token).where(site_id: site_id).present?
      end

      def render_unauthorized
        self.headers['WWW-Authenticate'] = 'Token realm="Application"'
      	render json: 'Bad credentials', status: 401
      end
    end
  end
end
