Skip to content
Snippets Groups Projects
Commit 8d4ad703 authored by pabois's avatar pabois
Browse files

roles

parent 853ebb85
No related branches found
No related tags found
No related merge requests found
......@@ -54,8 +54,7 @@
#
class User < ApplicationRecord
include WithAuthentication
enum role: { visitor: 0, admin: 20, superadmin: 30 }
include WithRoles
belongs_to :university
belongs_to :language
......
......@@ -3,15 +3,24 @@ module User::WithAuthentication
included do
devise :database_authenticatable, :registerable, :recoverable, :rememberable,
:timeoutable, :validatable, :confirmable, :trackable, :lockable, :two_factor_authenticatable
:timeoutable, :confirmable, :trackable, :lockable, :two_factor_authenticatable
# note : i do not use :validatable because of the non-uniqueness of the email. :validatable is replaced by the validation sequences below
has_one_time_password(encrypted: true)
validates_presence_of :first_name, :last_name, :email
validates :role, presence: true
validates_presence_of :first_name, :last_name, :email
validates_uniqueness_of :email, scope: :university_id, allow_blank: true, if: :will_save_change_to_email?
validates_format_of :email, with: Devise::email_regexp, allow_blank: true, if: :will_save_change_to_email?
validates_presence_of :password, if: :password_required?
validates_confirmation_of :password, if: :password_required?
validate :password_complexity
validates :mobile_phone, format: { with: /\A\+[0-9]+\z/ }, allow_blank: true
before_validation :adjust_mobile_phone, :sanitize_fields
def self.find_for_authentication(warden_conditions)
......@@ -64,6 +73,10 @@ module User::WithAuthentication
self.mobile_phone = full_sanitizer.sanitize(self.mobile_phone)&.gsub('=', '')
end
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
def password_complexity
# Regexp extracted from https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a
return if password.blank? || password =~ /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#{Rails.application.config.allowed_special_chars}]).{#{Devise.password_length.first},#{Devise.password_length.last}}$/
......
module User::WithRoles
extend ActiveSupport::Concern
included do
attr_accessor :modified_by
enum role: { visitor: 0, admin: 20, superadmin: 30 }
scope :for_role, -> (role) { where(role: role) }
before_validation :check_modifier_role
def roles_managed
User.roles.map do |role_name, role_id|
next if role_id > User.roles[role]
role_name
end.compact
end
protected
def check_modifier_role
errors.add(:role, 'cannot be set to this role') if modified_by && !modified_by.roles_managed.include?(self.role)
end
end
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment