Module: TenantLevelSecurity

Defined in:
lib/activerecord-tenant-level-security/sidekiq.rb,
lib/activerecord-tenant-level-security/version.rb,
lib/activerecord-tenant-level-security/schema_dumper.rb,
lib/activerecord-tenant-level-security/command_recorder.rb,
lib/activerecord-tenant-level-security/schema_statements.rb,
lib/activerecord-tenant-level-security/tenant_level_security.rb

Defined Under Namespace

Modules: CommandRecorder, SchemaDumper, SchemaStatements, Sidekiq

Constant Summary collapse

VERSION =
'0.3.0'
DEFAULT_PARTITION_KEY =
'tenant_id'.freeze

Class Method Summary collapse

Class Method Details

.current_session_tenant_idObject



42
43
44
45
46
47
# File 'lib/activerecord-tenant-level-security/tenant_level_security.rb', line 42

def current_session_tenant_id
  ActiveRecord::Base.connection.execute('SHOW tenant_level_security.tenant_id').getvalue(0, 0)
rescue ActiveRecord::StatementInvalid => e
  return nil if e.cause.kind_of? PG::UndefinedObject
  raise
end

.current_tenant_id(&block) ⇒ Object

The current_tenant_id sets the default tenant from the outside. Be sure to register in advance as ‘TenantLevelSecurity.current_tenant_id { id }` with initializers. This value is mainly used as the current value when reusing a connection. Therefore, keep in mind that you need to manage it differently from the session value in the database.



9
10
11
12
13
14
15
# File 'lib/activerecord-tenant-level-security/tenant_level_security.rb', line 9

def current_tenant_id(&block)
  if block_given?
    @@block = block
  else
    @@block.call
  end
end

.switch!(tenant_id) ⇒ Object



28
29
30
# File 'lib/activerecord-tenant-level-security/tenant_level_security.rb', line 28

def switch!(tenant_id)
  switch_with_connection!(ActiveRecord::Base.connection, tenant_id)
end

.switch_with_connection!(conn, tenant_id) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/activerecord-tenant-level-security/tenant_level_security.rb', line 32

def switch_with_connection!(conn, tenant_id)
  conn.clear_query_cache

  if tenant_id.present?
    conn.execute("SET tenant_level_security.tenant_id = '#{tenant_id}'")
  else
    conn.execute('SET tenant_level_security.tenant_id TO DEFAULT')
  end
end

.with(tenant_id) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/activerecord-tenant-level-security/tenant_level_security.rb', line 17

def with(tenant_id)
  old_tenant_id = current_session_tenant_id
  return yield if old_tenant_id == tenant_id
  begin
    switch! tenant_id
    yield
  ensure
    switch! old_tenant_id
  end
end