38 lines
1.2 KiB
Ruby
38 lines
1.2 KiB
Ruby
class User < ApplicationRecord
|
|
rolify
|
|
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable
|
|
has_many :access_periods, dependent: :destroy
|
|
accepts_nested_attributes_for :access_periods, allow_destroy: true
|
|
after_create :assign_default_role
|
|
|
|
validate :password_complexity
|
|
|
|
# Validation for date fields
|
|
validate :end_date_after_start_date, if: -> { access_revoked && access_end_date.present? }
|
|
|
|
# Override Devise method to consider access_revoked
|
|
def active_for_authentication?
|
|
super && !access_revoked
|
|
end
|
|
|
|
private
|
|
|
|
def assign_default_role
|
|
self.add_role(:user) unless self.has_any_role?
|
|
end
|
|
|
|
def password_complexity
|
|
return if password.blank? || password =~ /(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}/
|
|
errors.add :password, 'Complexity requirement not met. Length should be 8 characters and include: 1 uppercase, 1 lowercase, and 1 digit'
|
|
end
|
|
|
|
def end_date_after_start_date
|
|
if access_start_date.present?
|
|
errors.add(:access_end_date, 'must be provided when access is revoked') unless access_end_date.present?
|
|
if access_end_date && access_end_date < access_start_date
|
|
errors.add(:access_end_date, 'must be after the start date')
|
|
end
|
|
end
|
|
end
|
|
end
|