module LoginVerification
  extend ActiveSupport::Concern

  included do
    before_action :authenticate
    helper_method :current_company,:current_login_employee

  end


  protected
  # Authenticate the user with token based authentication
  def authenticate
    authenticate_session_token || render_unauthorized
  end

  def authenticate_session_token
    token = session[:session_token]
    if (token)
      #@current_user = User.find_by(api_key: token)
      Rails.logger.debug "token - " + token.to_s

      @user = Employee.authenticate_by_token(token)
      if @user
        return true
        #Maybe log - login?
      end
    end
  end

  def render_unauthorized()
    redirect_to root_path
  end


  #this is base api base controller to need to inherit.
  #all token authentication must be done here
  #response format must be set to JSON
  def current_company
    begin
     return Company.first
    rescue
      return nil
    end

  end

  def current_login_employee
    @employee = Employee.find_by_token_session(session[:session_token])
  end

  private
  def check_installation
    if current_company.nil?
      redirect_to install_path
    end
  end

end
