Sha256: b576142a63ef7a167257722e1cfa1039657348e29a81f641807d3ce0cc7d4690

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

module Mks
  module Auth
    # A model class to represent users of the system
    class User < ApplicationRecord
      has_and_belongs_to_many :application_modules,
                              class_name: 'Mks::Auth::ApplicationModule',
                              join_table: 'mks_auth_users_application_modules'
      has_and_belongs_to_many :roles, class_name: 'Mks::Auth::UserRole',
                                      join_table: 'mks_auth_users_user_roles'
      has_secure_password

      before_save { email.downcase! }

      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      validates :first_name, presence: true, length: { maximum: 30 }
      validates :last_name, presence: true, length: { maximum: 30 }
      validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
      validates :password, length: { minimum: 6 }
      validates :active, presence: true

      def full_name
        "#{first_name} #{last_name}"
      end

      def role_names
        roles.map(&:name)
      end

      def to_token_payload
        { id: id, email: email, name: full_name, roles: role_names }
      end

      def has_module(code)
        app_module = ApplicationModule.find_by(code: code)
        roles = self.roles.select { |ur| ur.application_module == app_module }
        roles.count.positive?
      end

      def role?(role)
        roles.any? { |r| r.name.underscore.to_sym == role }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mks_auth-1.0.10 app/models/mks/auth/user.rb