ability.rb 1.26 KB
Newer Older
gitlabhq's avatar
gitlabhq committed
1 2 3 4
class Ability
  def self.allowed(object, subject)
    case subject.class.name
    when "Project" then project_abilities(object, subject)
gitlabhq's avatar
gitlabhq committed
5 6 7
    when "Issue" then issue_abilities(object, subject)
    when "Note" then note_abilities(object, subject)
    when "Snippet" then snippet_abilities(object, subject)
gitlabhq's avatar
gitlabhq committed
8 9 10 11 12 13 14 15 16 17
    else []
    end
  end

  def self.project_abilities(user, project)
    rules = []

    rules << [
      :read_project,
      :read_issue,
gitlabhq's avatar
gitlabhq committed
18
      :read_snippet,
gitlabhq's avatar
gitlabhq committed
19
      :read_team_member,
Nihad Abbasov's avatar
Nihad Abbasov committed
20
      :read_note
gitlabhq's avatar
gitlabhq committed
21 22 23 24 25
    ] if project.readers.include?(user)

    rules << [
      :write_project,
      :write_issue,
gitlabhq's avatar
gitlabhq committed
26
      :write_snippet,
Nihad Abbasov's avatar
Nihad Abbasov committed
27
      :write_note
gitlabhq's avatar
gitlabhq committed
28 29 30 31 32
    ] if project.writers.include?(user)

    rules << [
      :admin_project,
      :admin_issue,
gitlabhq's avatar
gitlabhq committed
33
      :admin_snippet,
gitlabhq's avatar
gitlabhq committed
34
      :admin_team_member,
Nihad Abbasov's avatar
Nihad Abbasov committed
35
      :admin_note
gitlabhq's avatar
gitlabhq committed
36 37 38 39
    ] if project.admins.include?(user)

    rules.flatten
  end
gitlabhq's avatar
gitlabhq committed
40

Nihad Abbasov's avatar
Nihad Abbasov committed
41
  class << self
gitlabhq's avatar
gitlabhq committed
42 43 44 45 46 47 48 49 50
    [:issue, :note, :snippet].each do |name|
      define_method "#{name}_abilities" do |user, subject|
        if subject.author == user
          [
            :"read_#{name}",
            :"write_#{name}",
            :"admin_#{name}"
          ]
        else
Nihad Abbasov's avatar
Nihad Abbasov committed
51
          subject.respond_to?(:project) ?
gitlabhq's avatar
gitlabhq committed
52 53 54 55 56
            project_abilities(user, subject.project) : []
        end
      end
    end
  end
gitlabhq's avatar
gitlabhq committed
57
end