Sha256: 7a33c626764a5cc97b80a1243492ad8481740c8be2154cf918287e059d003da2

Contents?: true

Size: 1.19 KB

Versions: 1

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

require 'ditty/models/user'

module Ditty
  module Helpers
    module Authentication
      def current_user
        return nil if current_user_id.nil?

        @current_user ||= User[current_user_id]
      rescue Sequel::DatabaseError => e
        Services::Logger.warn "Could not fetch current user: #{e.message} / #{current_user_id}"
        Services::Logger.debug e
        nil
      end

      def current_user=(user)
        env['rack.session'] = {} if env['rack.session'].nil?
        env['rack.session']['user_id'] = user.id if user
        @current_user = user
      end

      def current_user_id
        return env['rack.session']['user_id'] if env['rack.session'] && env['rack.session']['user_id']

        env['omniauth.auth']&.uid
      end

      def authenticate
        authenticated?
      end

      def authenticated?
        current_user && !current_user.role?('anonymous')
      end

      def authenticate!
        raise NotAuthenticated unless authenticated?

        true
      end

      def logout
        env['rack.session']&.delete('user_id')
        env.delete('omniauth.auth')
      end
    end

    class NotAuthenticated < StandardError
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ditty-0.11.1 lib/ditty/helpers/authentication.rb