Sha256: f0b79a4623ef75ee794322956e3d2c67ccfa0d91855c249b4e3c45bf46504c17

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

require 'ditty/models/user'
require 'ditty/models/role'
require 'ditty/models/identity'

module Ditty
  module Helpers
    module Authentication
      def current_user
        return anonymous_user if current_user_id.nil?
        @current_user ||= User[current_user_id]
      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['omniauth.auth'].uid if env['omniauth.auth']
      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') unless env['rack.session'].nil?
        env.delete('omniauth.auth')
      end

      def anonymous_user
        role = ::Ditty::Role.where(name: 'anonymous').first
        ::Ditty::User.where(roles: role).first unless role.nil?
      end
    end

    class NotAuthenticated < StandardError
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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