Module: Maestrano::Rails::MaestranoAuthResource::LocalClassGenericMethods

Defined in:
lib/maestrano/rails/models/maestrano_auth_resource.rb

Overview

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

Instance Method Summary collapse

Instance Method Details

#find_or_create_for_maestrano(auth_hash, tenant = 'default') ⇒ Object

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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# 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) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# 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