class Tilia::DavAcl::PrincipalBackend::Sequel

PDO principal backend

This backend assumes all principals are in a single collection. The default collection is 'principals/', but this can be overriden.

Attributes

field_map[RW]

A list of additional fields to support

@var array

group_members_table_name[RW]

PDO table name for 'group members'

@var string

sequel[RW]

pdo

@var PDO

table_name[RW]

PDO table name for 'principals'

@var string

Public Class Methods

new(sequel) click to toggle source

Sets up the backend.

@param PDO pdo

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 38
def initialize(sequel)
  @table_name = 'principals'
  @group_members_table_name = 'groupmembers'
  @field_map = {
    # This property can be used to display the users' real name.
    '{DAV:}displayname' => {
      'dbField' => 'displayname'
    },

    # This is the users' primary email-address.
    '{http://sabredav.org/ns}email-address' => {
      'dbField' => 'email'
    }
  }
  @sequel = sequel
end

Public Instance Methods

create_principal(path, mk_col) click to toggle source

Creates a new principal.

This method receives a full path for the new principal. The mkCol object contains any additional webdav properties specified during the creation of the principal.

@param string path @param MkCol mk_col @return void

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 348
def create_principal(path, mk_col)
  ds = @sequel["INSERT INTO #{@table_name} (uri) VALUES (?)", path]
  ds.insert

  update_principal(path, mk_col)
end
find_by_uri(uri, principal_prefix) click to toggle source

Finds a principal by its URI.

This method may receive any type of uri, but mailto: addresses will be the most common.

Implementation of this API is optional. It is currently used by the CalDAV system to find principals based on their email addresses. If this API is not implemented, some features may not work correctly.

This method must return a relative principal path, or null, if the principal was not found or you refuse to find it.

@param string uri @param string principal_prefix @return string, nil

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 250
def find_by_uri(uri, principal_prefix)
  value = nil
  scheme = nil
  (scheme, value) = uri.split(":", 2)
  return nil unless value

  uri = nil
  case scheme
  when "mailto"
    @sequel.fetch("SELECT uri FROM #{@table_name} WHERE lower(email)=lower(?)", [value]) do |row|
      # Checking if the principal is in the prefix
      row_prefix = Http::UrlUtil.split_path(row[:uri]).first
      next unless row_prefix == principal_prefix

      uri = row[:uri]
      break # Stop on first match
    end
  else
    #unsupported uri scheme
    return nil
  end

  uri
end
group_member_set(principal) click to toggle source

Returns the list of members for a group-principal

@param string principal @return array

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 279
def group_member_set(principal)
  principal = principal_by_path(principal)
  fail Dav::Exception, 'Principal not found' if principal.empty?

  result = []
  @sequel.fetch("SELECT principals.uri as uri FROM #{@group_members_table_name} AS groupmembers LEFT JOIN #{@table_name} AS principals ON groupmembers.member_id = principals.id WHERE groupmembers.principal_id = ?", principal['id']) do |row|
    result << row[:uri]
  end

  result
end
group_membership(principal) click to toggle source

Returns the list of groups a principal is a member of

@param string principal @return array

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 295
def group_membership(principal)
  principal = principal_by_path(principal)
  fail Dav::Exception, 'Principal not found' if principal.empty?

  result = []
  @sequel.fetch("SELECT principals.uri as uri FROM #{@group_members_table_name} AS groupmembers LEFT JOIN #{@table_name} AS principals ON groupmembers.principal_id = principals.id WHERE groupmembers.member_id = ?", principal['id']) do |row|
    result << row[:uri]
  end

  result
end
principal_by_path(path) click to toggle source

Returns a specific principal, specified by it's path. The returned structure should be the exact same as from getPrincipalsByPrefix.

@param string path @return array

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 104
def principal_by_path(path)
  fields = [
    'id',
    'uri'
  ]

  @field_map.each do |_key, value|
    fields << value['dbField']
  end

  ds = @sequel["SELECT #{fields.join(',')}  FROM #{@table_name} WHERE uri = ?", path]
  row = ds.all.first

  return unless row

  principal = {
    'id'  => row[:id],
    'uri' => row[:uri]
  }

  @field_map.each do |key, value|
    if row[value['dbField'].to_sym]
      principal[key] = row[value['dbField'].to_sym]
    end
  end

  principal
end
principals_by_prefix(prefix_path) click to toggle source

Returns a list of principals based on a prefix.

This prefix will often contain something like 'principals'. You are only expected to return principals that are in this base path.

You are expected to return at least a 'uri' for every user, you can return any additional properties if you wish so. Common properties are:

{DAV:}displayname
{http://sabredav.org/ns}email-address - This is a custom SabreDAV
  field that's actualy injected in a number of other properties. If
  you have an email address, use this property.

@param string prefix_path @return array

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 69
def principals_by_prefix(prefix_path)
  fields = ['uri']

  @field_map.each do |_key, value|
    fields << value['dbField']
  end

  principals = []
  @sequel.fetch("SELECT #{fields.join(',')} FROM #{@table_name}") do |row|
    # Checking if the principal is in the prefix
    row_prefix = Http::UrlUtil.split_path(row[:uri])[0]

    next unless row_prefix == prefix_path

    principal = {
      'uri' => row[:uri]
    }

    @field_map.each do |key, value|
      unless row[value['dbField'].to_sym].blank?
        principal[key] = row[value['dbField'].to_sym]
      end
    end
    principals << principal
  end

  principals
end
search_principals(prefix_path, search_properties, test = 'allof') click to toggle source

This method is used to search for principals matching a set of properties.

This search is specifically used by RFC3744's principal-property-search REPORT.

The actual search should be a unicode-non-case-sensitive search. The keys in searchProperties are the WebDAV property names, while the values are the property values to search on.

By default, if multiple properties are submitted to this method, the various properties should be combined with 'AND'. If test is set to 'anyof', it should be combined using 'OR'.

This method should simply return an array with full principal uri's.

If somebody attempted to search on a property the backend does not support, you should simply return 0 results.

You can also just return 0 results if you choose to not support searching at all, but keep in mind that this may stop certain features from working.

@param string prefix_path @param array search_properties @param string test @return array

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 201
def search_principals(prefix_path, search_properties, test = 'allof')
  return [] if search_properties.empty? # No criteria

  query = "SELECT uri FROM #{@table_name} WHERE "
  values = []

  search_properties.each do |property, value|
    case property
    when '{DAV:}displayname'
      column = 'displayname'
    when '{http://sabredav.org/ns}email-address'
      column = 'email'
    else
      # Unsupported property
      return []
    end

    query += test == 'anyof' ? ' OR ' : ' AND ' if values.any?
    query += "lower(#{column}) LIKE lower(?)"
    values << "%#{value}%"
  end

  principals = []
  @sequel.fetch(query, *values) do |row|
    # Checking if the principal is in the prefix
    row_prefix = Http::UrlUtil.split_path(row[:uri])[0]
    next unless row_prefix == prefix_path

    principals << row[:uri]
  end

  principals
end
update_group_member_set(principal, members) click to toggle source

Updates the list of group members for a group principal.

The principals should be passed as a list of uri's.

@param string principal @param array members @return void

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 314
def update_group_member_set(principal, members)
  # Grabbing the list of principal id's.
  member_ids = []
  principal_id = nil

  @sequel.fetch("SELECT id, uri FROM #{@table_name} WHERE uri IN (?#{', ?' * members.size})", principal, *members) do |row|
    if row[:uri] == principal
      principal_id = row[:id]
    else
      member_ids << row[:id]
    end
  end

  fail Dav::Exception, 'Principal not found' unless principal_id

  # Wiping out old members
  ds = @sequel["DELETE FROM #{@group_members_table_name} WHERE principal_id = ?", principal_id]
  ds.delete

  member_ids.each do |member_id|
    ds = @sequel["INSERT INTO #{@group_members_table_name} (principal_id, member_id) VALUES (?, ?)", principal_id, member_id]
    ds.insert
  end
end
update_principal(path, prop_patch) click to toggle source

Updates one ore more webdav properties on a principal.

The list of mutations is stored in a SabreDAVPropPatch object. To do the actual updates, you must tell this object which properties you're going to process with the handle method.

Calling the handle method is like telling the PropPatch object “I promise I can handle updating this property”.

Read the PropPatch documenation for more info and examples.

@param string path @param DAVPropPatch prop_patch

# File lib/tilia/dav_acl/principal_backend/sequel.rb, line 146
def update_principal(path, prop_patch)
  prop_patch.handle(
    @field_map.keys,
    lambda do |properties|
      query = "UPDATE #{@table_name} SET "

      first = true
      values = {}
      properties.each do |key, value|
        db_field = @field_map[key]['dbField']

        query << ', ' unless first
        first = false
        query << "#{db_field} = :#{db_field}"
        values[db_field.to_sym] = value
      end

      query << ' WHERE uri = :uri'
      values[:uri] = path

      ds = @sequel[query, values]
      ds.update

      true
    end
  )
end