visibility_level.rb 2.23 KB
Newer Older
1 2 3 4 5 6 7
# Gitlab::VisibilityLevel module
#
# Define allowed public modes that can be used for
# GitLab projects to determine project public mode
#
module Gitlab
  module VisibilityLevel
8
    extend CurrentSettings
Felipe Artur's avatar
Felipe Artur committed
9 10 11
    extend ActiveSupport::Concern

    included do
12 13
      scope :public_only,               -> { where(visibility_level: PUBLIC) }
      scope :public_and_internal_only,  -> { where(visibility_level: [PUBLIC, INTERNAL] ) }
14
      scope :non_public_only,           -> { where.not(visibility_level: PUBLIC) }
15 16

      scope :public_to_user, -> (user) { user && !user.external ? public_and_internal_only : public_only }
Felipe Artur's avatar
Felipe Artur committed
17
    end
18

19 20 21
    PRIVATE  = 0 unless const_defined?(:PRIVATE)
    INTERNAL = 10 unless const_defined?(:INTERNAL)
    PUBLIC   = 20 unless const_defined?(:PUBLIC)
22 23 24 25 26 27 28 29 30 31 32 33 34

    class << self
      def values
        options.values
      end

      def options
        {
          'Private'  => PRIVATE,
          'Internal' => INTERNAL,
          'Public'   => PUBLIC
        }
      end
35

36 37 38 39 40 41 42
      def highest_allowed_level
        restricted_levels = current_application_settings.restricted_visibility_levels

        allowed_levels = self.values - restricted_levels
        allowed_levels.max || PRIVATE
      end

43
      def allowed_for?(user, level)
44
        user.is_admin? || allowed_level?(level.to_i)
45 46
      end

47 48
      # Return true if the specified level is allowed for the current user.
      # Level should be a numeric value, e.g. `20`.
49
      def allowed_level?(level)
50
        valid_level?(level) && non_restricted_level?(level)
51 52 53
      end

      def non_restricted_level?(level)
54 55 56
        restricted_levels = current_application_settings.restricted_visibility_levels

        if restricted_levels.nil?
57 58
          true
        else
59
          !restricted_levels.include?(level)
60
        end
61 62 63 64
      end

      def valid_level?(level)
        options.has_value?(level)
65
      end
Valery Sizov's avatar
Valery Sizov committed
66

67 68 69
      def level_name(level)
        level_name = 'Unknown'
        options.each do |name, lvl|
70
          level_name = name if lvl == level.to_i
71 72 73 74
        end

        level_name
      end
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    end

    def private?
      visibility_level_field == PRIVATE
    end

    def internal?
      visibility_level_field == INTERNAL
    end

    def public?
      visibility_level_field == PUBLIC
    end
  end
end