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_name)

    if response.success?
      domain = Domain.find_or_create_by(:domain => domain_name)

      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_name)

    if response.success?
      domain = Domain.find_or_create_by(:domain => domain_name)

      # The user is an admin of the domain we're fetching
      user.update_attributes(:admin => true, :domain_id => domain.id)
      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

Set attributes on admins for new domains
Set attributes on admins for new domains

This is to avoid the situation where a worker has not yet had a chance
to execute and set the admin flags or domain relation on that user
model. We have verified that the user is an admin of that domain
already.
