module Maestrano::Rails::MaestranoAuthResource::LocalClassGenericMethods

Actual class methods - injected after behaviour has been added (don't polute the model scope)

Public Instance Methods

find_or_create_for_maestrano(auth_hash, tenant='default') click to toggle source

Find the resource based on provider and uid fields or create it using the mapping block defined at the model level

# File lib/maestrano/rails/models/maestrano_auth_resource.rb, line 55
def find_or_create_for_maestrano(auth_hash, tenant='default')
  # Look for the entity first
  entity = self.where(
    self.maestrano_options[:provider].to_sym => auth_hash[:provider],
    self.maestrano_options[:uid].to_sym => auth_hash[:uid],
    self.maestrano_options[:tenant].to_sym => tenant
  ).first
  
  # Create it otherwise
  unless entity
    # Extract maestrano information into proper objects
    info = OpenStruct.new(auth_hash[:info])
    extra = OpenStruct.new(auth_hash[:extra])
    
    # Create entity
    entity = self.new
    
    # Set password on entity in case this is required
    # This is done before the mapping block in case
    # password has been taken care of by the developer
    password = Digest::SHA1.hexdigest("#{Time.now.utc}-#{rand(100)}")[0..20]
    begin
      entity.password = password if entity.respond_to?(:password)
      entity.password_confirmation = password if entity.respond_to?(:password_confirmation)
    rescue Exception => e
    end
    
    # Call mapping block
    self.maestrano_options[:mapping].call(entity, info, extra)
    
    # Finally set provider, uid and tenant then save
    entity.send("#{self.maestrano_options[:provider]}=", auth_hash[:provider])
    entity.send("#{self.maestrano_options[:uid]}=", auth_hash[:uid])
    entity.send("#{self.maestrano_options[:tenant]}=", tenant)
    entity.save!
  end
  
  return entity
end
maestrano_generic_configurator(provider_field, uid_field, tenant_field, &block) click to toggle source
# File lib/maestrano/rails/models/maestrano_auth_resource.rb, line 41
def maestrano_generic_configurator(provider_field, uid_field, tenant_field, &block)
  cattr_accessor :maestrano_options
  self.maestrano_options = {
    provider: provider_field.to_s,
    uid: uid_field.to_s,
    tenant: tenant_field.to_s,
    mapping: block
  }
  
  include Maestrano::Rails::MaestranoAuthResource::LocalInstanceGenericMethods
end