aboutsummaryrefslogtreecommitdiff
path: root/app/jobs/agency_watcher_job.rb
blob: 23266e8ed62462164e1fc417adc13013548a2961 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# SPDX-FileCopyrightText: 2020 IN COMMON Collective <collective@incommon.cc>
#
# SPDX-License-Identifier: AGPL-3.0-or-later

# frozen_string_literal: true

# = AgencyWatcherJob
#
# This job performs checks on existing records for the given user and group
# names and updates Agencies accordingly.
#
# @param user (User) currently logged in user
# @param groups (Array) a list of group names
#
class AgencyWatcherJob < ApplicationJob
  queue_as :default

  def perform(user, groups)
    # Check groups against user agents
    existing_agents = Agent.where(name: groups)
    existing_agent_names = existing_agents.map(&:name)

    groups.each do |g|
      # Only work with existing agents
      next unless existing_agent_names.include?(g)

      a = existing_agents.select { |a| a.name = g }.first

      Rails.logger.debug("AgencyWatcher checking roles for %s in %s" % [user.username, g])
      # Check if user is a group owner
      r = a.agencies.find_or_create_by(user: user)
      if !r.leader? && is_group_owner?(g, user.username)
        Rails.logger.debug("AgencyWatcher: grant leader to %s in %s" % [user.username, g])
        # Grant leader
        r.grant(:leader)
        # Grant maintainer
        r.grant(:maintainer)
      elsif r.roles == 0
        # No role: grant editor
        Rails.logger.debug("AgencyWatcher: grant editor to %s in %s" % [user.username, g])
        r.grant(:observer)
      else
        # No change
        Rails.logger.debug("AgencyWatcher: %s's roles in %s are %s" % [user.username, g, r.bitfield_values(:roles)])
      end
    end
  end

  private

  # Connect to Discourse and check whether current user is a group owner
  def is_group_owner?(group, username)
    c = ::DiscourseApi::Client.new('https://talk.incommon.cc')
    c.api_key = Rails.application.credentials.talk_api_key
    c.api_username = username

    group = c.group(group)
    group['group']['is_group_owner'] == true
  end
end