module Ddr module Auth module Roles # # The assignment of a role to an agent within a scope. # class Role < Valkyrie::Resource DEFAULT_SCOPE = Roles::RESOURCE_SCOPE ValidScope = Valkyrie::Types::Strict::String.enum(*(Roles::SCOPES)) ValidRoleType = Valkyrie::Types::Strict::String.enum(*(Roles::role_types.map(&:title))) attribute :agent, Valkyrie::Types::Strict::String.constrained(min_size: 1) attribute :role_type, ValidRoleType attribute :scope, ValidScope class << self # Build a Role instance from hash attributes # @param args [Hash] the attributes # @return [Role] the role # @example # Role.build type: "Curator", agent: "bob", scope: "resource" def build(args={}) new.tap do |role| args[:role_type] ||= args.delete(:type) args[:agent] ||= nil # Triggers a constraint error args[:agent] = args[:agent].to_s # Coerce Ddr::Auth:Group to string args.each do |attr, val| role.set_value(attr, val) end role.scope ||= DEFAULT_SCOPE end end ############### # FIXME or remove serialization/deserialization ############### # # # Deserialize a Role from JSON # # @param json [String] the JSON string # # @return [Role] the role # def from_json(json) # build JSON.parse(json) # end # alias_method :deserialize, :from_json private # # DELETEME # # def build_attributes(args={}) # # symbolize keys and stringify values # attrs = args.each_with_object({}) do |(k, v), memo| # memo[k.to_sym] = Array(v).first.to_s # end # # set default scope if necessary # attrs[:scope] ||= DEFAULT_SCOPE # # accept :type key for role_type attribute # if attrs.key?(:type) # attrs[:role_type] = attrs.delete(:type) # end # attrs # end end # class << self # Roles are considered equal (==) if they # are of the same type and have the same agent and scope. # @param other [Object] the object of comparison # @return [Boolean] the result def ==(other) self.class == other.class && role_type == other.role_type && scope == other.scope && agent == other.agent end alias_method :eql?, :== def in_resource_scope? scope == Roles::RESOURCE_SCOPE end def in_policy_scope? scope == Roles::POLICY_SCOPE end def inspect "#<#{self.class.name} role_type=#{role_type.inspect}, " \ "agent=#{agent.inspect}, scope=#{scope.inspect}>" end # TODO refactor up? def proper_attributes attributes.slice(self.class.fields - self.class.reserved_attributes) end ############### # FIXME or remove serialization/deserialization ############### # # delegate :to_json, to: :proper_attributes # # alias_method :serialize, :to_json # Returns the permissions associated with the role # @return [Array] the permissions def permissions Roles.type_map[role_type].permissions end end end end end