require 'playhouse/context'

# Constructs a client for the Google Apps privileged APIs
# The +:user+ actor is tested to be a Google Apps admin of the domain
class GetGoogleAppsDomain < Playhouse::Context
  actor :user
  actor :domain_name

  def perform
    # Initialize the Google API client
    client = ApiWrappers::Google.new(user)
    client.fetch_access_token!

    # Fetch a list of the users in this domain
    response = client.directory_users_list

    if response.success?
      domain = Domain.find_or_create_by(:domain => domain_name) do |d|
        d.importing = true
      end

      # The user is an admin of the domain we're fetching
      user.update_attributes(:admin => true, :domain_id => domain.id, :active => true)
      user.domain_admin_roles.find_or_create_by(:domain => domain)

      Workers::SyncDomain.enqueue(domain_name, user.id, :first_run) unless domain.imported?

      domain
    else
      false
    end
  end
end

require 'playhouse/context'

# Constructs a client for the Google Apps privileged APIs
# The +:user+ actor is tested to be a Google Apps admin of the domain
class GetGoogleAppsDomain < Playhouse::Context
  actor :user
  actor :domain_name

  def perform
    # Initialize the Google API client
    client = ApiWrappers::Google.new(user)
    client.fetch_access_token!

    # Fetch a list of the users in this domain
    response = client.directory_users_list(:domain => domain_name)

    if response.success?
      domain = Domain.find_or_create_by(:domain => domain_name) do |d|
        d.importing = true
      end

      # The user is an admin of the domain we're fetching
      user.update_attributes(:admin => true, :domain_id => domain.id, :active => true)
      user.domain_admin_roles.find_or_create_by(:domain => domain)

      Workers::SyncDomain.enqueue(domain_name, user.id, :first_run) unless domain.imported?

      domain
    else
      false
    end
  end
end

Verify ownership of specific domain
Verify ownership of specific domain

Models would erroneously be created before if an arbitrary domain was
specified as the URL parameter.
