module Symphonia class User < ApplicationRecord self.table_name = 'users' include ModelAttributes register_query do add_attribute :login, :link add_attribute :name, :link, sort: %i(first_name last_name), default: true add_attribute :first_name add_attribute :last_name add_attribute :email, :mail, default: true add_attribute :status, :enum, filter: "select" add_attribute :role, :reference add_attribute :admin, :boolean add_attribute :login_count add_attribute :last_login_ip add_attribute :last_login_at end acts_as_authentic do |config| end validates :email, uniqueness: { case_sensitive: false } validates :password, confirmation: { if: :require_password? }, length: { minimum: 8, if: :require_password? } include UserManagement include ::Swagger::Blocks swagger_schema :User do key :required, %i[id login email] property :id do key :type, :integer key :format, :int64 end property :fist_name do key :type, :string end property :last_name do key :type, :string end property :email do key :type, :string key :format, :email end property :status do key :type, :string key :enum, Symphonia::User.statuses.keys end end attr_writer :password_confirmation has_and_belongs_to_many :preferences, foreign_key: 'user_id' belongs_to :edited_by, class_name: 'Symphonia::User', required: false belongs_to :role, required: false accepts_nested_attributes_for :preferences scope :recipients_for, ->(notification) { joins(:preferences).where(preferences: { name: notification, type: 'Symphonia::EmailPreference' }) } scope :like, ->(q) { t = arel_table; where(t[:email].matches("%#{q}%").or(t[:first_name].matches("%#{q}%").or(t[:last_name].matches("%#{q}%")))) } scope :admins, -> { where(admin: true) } alias_attribute :mail, :email before_save do |model| Rails.cache.delete_matched('user_allowed_to*') if model.role_id_changed? end before_validation do |model| model.login ||= model.email end def allowed_to?(action) return true if admin? Rails.cache.fetch([:user_allowed_to, self, action]) do role_id && role.allowed_to?(action) end end def authorize?(controller, action) return true if admin? if role_id role.authorize?(controller, action) else false end end # def form_path # 'symphonia/users/form' # end private def require_password? external_id.blank? && super end class Anonymous def id 0 end def name 'Anonymous' end def login 'anonymous' end def email 'anonym@nothing' end def allowed_to?(_action) false end def authorize?(_controller, _action) false end def save false end def create false end def admin false end alias_method :admin?, :admin def logged_in? false end def persistence_token nil end def language Symphonia.config.default_locale || I18n.default_locale end end end end