Sha256: 61fbbf96c160eefde86d7b65deb888d50afb8012399e29980e20989f1b778e3a

Contents?: true

Size: 1.83 KB

Versions: 2

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

module Maquina
  module Authenticate
    extend ActiveSupport::Concern

    included do
      before_action :require_authentication
      helper_method :signed_in?, :current_user, :authenticated?
    end

    class_methods do
      def allow_unauthenticated_access(...)
        skip_before_action(:require_authentication, ...)
      end
    end

    def authenticated?
      Maquina::Current.signed_in?
    end
    alias_method :signed_in?, :authenticated?

    def current_user
      Maquina::Current.user
    end

    def after_authentication_url
      session.delete(:return_to_after_authenticating) || root_url
    end

    def require_authentication
      load_session || request_authentication
    end

    private

    def request_authentication
      session[:return_to_after_authenticating] = request.url

      # TODO: Allow to configure sign in path
      redirect_to maquina.new_sessions_path, format: :html, status: :see_other
    end

    def authenticate
      load_session
    end

    def load_session
      active_session_id = session["--active_session"]
      return if active_session_id.blank?

      active_session = ActiveSession.eager_load(user: {memberships: :organization})
        .where(maquina_memberships: {blocked_at: nil})
        .where(maquina_organizations: {active: true})
        .or(
          ActiveSession.where(maquina_users: {management: true})
        )
        .find_by(id: active_session_id)

      return if active_session.blank?

      Maquina::Current.active_session = active_session
    end

    def start_new_session_for(user)
      ActiveSession.create(user: user, user_agent: request.user_agent, remote_addr: request.remote_ip).tap do |active_session|
        session["--active_session"] = active_session.id
        Maquina::Current.active_session = active_session
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
maquina-0.5.2 app/controllers/concerns/maquina/authenticate.rb
maquina-0.5.1 app/controllers/concerns/maquina/authenticate.rb