Sha256: 412f972c9d9dac1527db1cf53d764aef0e81c40daf3ec064e726bd3cf5ab1e77

Contents?: true

Size: 1.62 KB

Versions: 4

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

module Decidim
  module Initiatives
    module Abilities
      # Defines the abilities related to votes.
      # Intended to be used with `cancancan`.
      class VoteAbility
        include CanCan::Ability

        attr_reader :user, :context

        def initialize(user, context)
          return unless user

          @user = user
          @context = context

          can :vote, Initiative do |initiative|
            can_vote?(initiative)
          end

          can :unvote, Initiative do |initiative|
            can_unvote?(initiative)
          end
        end

        private

        def decidim_user_group_id
          context[:params]&.try(:[], "group_id")
        end

        def can_vote?(initiative)
          initiative.votes_enabled? &&
            initiative.organization&.id == user.organization&.id &&
            initiative.votes.where(decidim_author_id: user.id, decidim_user_group_id: decidim_user_group_id).empty? &&
            (can_user_support?(initiative) || user.user_groups.verified.any?)
        end

        def can_unvote?(initiative)
          initiative.votes_enabled? &&
            initiative.organization&.id == user.organization&.id &&
            initiative.votes.where(decidim_author_id: user.id, decidim_user_group_id: decidim_user_group_id).any? &&
            (can_user_support?(initiative) || user.user_groups.verified.any?)
        end

        def can_user_support?(initiative)
          !initiative.offline? && (
            Decidim::Initiatives.do_not_require_authorization ||
            UserAuthorizations.for(user).any?
          )
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
decidim-initiatives-0.11.2 app/models/decidim/initiatives/abilities/vote_ability.rb
decidim-initiatives-0.11.1 app/models/decidim/initiatives/abilities/vote_ability.rb
decidim-initiatives-0.11.0.pre1 app/models/decidim/initiatives/abilities/vote_ability.rb
decidim-initiatives-0.9.1 app/models/decidim/initiatives/abilities/vote_ability.rb