aboutsummaryrefslogtreecommitdiffstats
path: root/app/policies/application_policy.rb
blob: e2c0acd8e1aa8d462e18eafad8d4e61105f2d6f4 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class ApplicationPolicy
  attr_reader :current_referential, :record, :user

  def initialize(user_context, record)
    @user                = user_context.user
    @current_referential = user_context.context[:referential]
    @record              = record
  end

  def archived?
    return @is_archived if instance_variable_defined?(:@is_archived)
    @is_archived = is_archived
  end

  def referential
    @referential ||=  current_referential || record_referential
  end

  def record_referential
    record.referential if record.respond_to?(:referential)
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  def boiv_read_offer?
    organisation_match? && !(user.permissions || []).grep(%r{\Aboiv:.}).empty?
  end

  def organisation_match?
    user.organisation == organisation
  end

  def organisation
    # When sending permission to react UI, we don't have access to record object for edit & destroy.. actions
    organisation = record.is_a?(Symbol) ? nil : record.try(:organisation)
    organisation or referential.try :organisation
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end

  private
  def is_archived
    !!case referential
    when Referential
      referential.archived_at
    else
      current_referential.try(:archived_at)
    end
  end
end