Redefine user roles with their role in a study group

This commit is contained in:
Sebastian Serth
2022-09-20 16:19:04 +02:00
committed by Sebastian Serth
parent 04ed45ea73
commit 9c9f45ff77
12 changed files with 90 additions and 44 deletions

View File

@@ -10,7 +10,6 @@ class InternalUser < User
validates :email, presence: true, uniqueness: true
validates :password, confirmation: true, if: -> { password_void? && validate_password? }, on: :update, presence: true
validate :password_strength, if: -> { password_void? && validate_password? }, on: :update
validates :role, inclusion: {in: ROLES}
def activated?
activation_state == 'active'
@@ -33,10 +32,6 @@ class InternalUser < User
errors.add(:password, :weak) if result.score < 4
end
def teacher?
role == 'teacher'
end
def displayname
name
end

View File

@@ -3,7 +3,7 @@
class User < ApplicationRecord
self.abstract_class = true
ROLES = %w[admin teacher learner].freeze
attr_reader :current_study_group_id
belongs_to :consumer
has_many :authentication_token, dependent: :destroy
@@ -26,9 +26,7 @@ class User < ApplicationRecord
joins(:study_group_memberships).where(study_group_memberships: {study_group_id: user.study_groups}) unless user.admin?
}
ROLES.each do |role|
define_method("#{role}?") { try(:role) == role }
end
validates :platform_admin, boolean_presence: true
def internal_user?
is_a?(InternalUser)
@@ -38,6 +36,30 @@ class User < ApplicationRecord
is_a?(ExternalUser)
end
def learner?
return true if current_study_group_id.nil?
@learner ||= current_study_group_membership.exists?(role: :learner) && !platform_admin?
end
def teacher?
@teacher ||= current_study_group_membership.exists?(role: :teacher) && !platform_admin?
end
def admin?
@admin ||= platform_admin?
end
def store_current_study_group_id(study_group_id)
@current_study_group_id = study_group_id
self
end
def current_study_group_membership
# We use `where(...).limit(1)` instead of `find_by(...)` to allow query chaining
study_group_memberships.where(study_group: current_study_group_id).limit(1)
end
def to_s
displayname
end