Sha256: 2e9f21c9fac28c7a8c4042f960323823e5ab3890f162199d8a8d39608528eb2f

Contents?: true

Size: 1.36 KB

Versions: 13

Compression:

Stored size: 1.36 KB

Contents

# frozen_string_literal: true

module Shieldify
  module Models
    # This module provides email authentication functionality for users. It includes methods to authenticate
    # users by their email and password, and uses `has_secure_password` for secure password handling.
    #
    # @example Including the module in a User model
    #   class User < ApplicationRecord
    #     include Shieldify::Models::EmailAuthenticatable
    #   end
    #
    # @see .authenticate_by_email
    module EmailAuthenticatable
      extend ActiveSupport::Concern

      included do
        # Adds methods to set and authenticate against a BCrypt password. This mechanism requires you to have a
        # password_digest attribute.
        has_secure_password(validations: false)
      end

      class_methods do
        # Authenticates a user by their email and password.
        #
        # @param email [String] The email of the user.
        # @param password [String] The password of the user.
        # @return [User] The authenticated user if the credentials are correct, or a new user object with errors if not.
        def authenticate_by_email(email:, password:)
          user = find_by(email: email)

          return user if user&.authenticate(password)

          user ||= new
          user.errors.add(:email, "invalid email or password")
          user
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
shieldify-0.2.9.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.8.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.7.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.6.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.5.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.4.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.3.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.2.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.1.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.2.0.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.1.2.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.1.1.pre.alpha lib/shieldify/models/email_authenticatable.rb
shieldify-0.1.0.pre.alpha lib/shieldify/models/email_authenticatable.rb