From 1ab58b6aa580326f6841cd897fc1675bd2c5cb82 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Lang Date: Mon, 3 Apr 2017 06:49:06 +0000 Subject: [PATCH] Adds a User.admin scope (#25416). git-svn-id: http://svn.redmine.org/redmine/trunk@16449 e93f8b46-1217-0410-a6f0-8f06a7374b81 --- app/models/user.rb | 6 +++++- test/unit/user_test.rb | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 150cc27bb..815a6d343 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -129,6 +129,10 @@ class User < Principal after_save :update_notified_project_ids, :destroy_tokens, :deliver_security_notification after_destroy :deliver_security_notification + scope :admin, lambda {|*args| + admin = args.size > 0 ? !!args.first : true + where(:admin => admin) + } scope :in_group, lambda {|group| group_id = group.is_a?(Group) ? group.id : group.to_i where("#{User.table_name}.id IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id) @@ -707,7 +711,7 @@ class User < Principal # Returns true if the user is allowed to delete the user's own account def own_account_deletable? Setting.unsubscribe? && - (!admin? || User.active.where("admin = ? AND id <> ?", true, id).exists?) + (!admin? || User.active.admin.where("id <> ?", id).exists?) end safe_attributes 'firstname', diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 655a8affc..48c4cb3d4 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -36,6 +36,24 @@ class UserTest < ActiveSupport::TestCase @dlopper = User.find(3) end + def test_admin_scope_without_args_should_return_admin_users + users = User.admin.to_a + assert users.any? + assert users.all? {|u| u.admin == true} + end + + def test_admin_scope_with_true_should_return_admin_users + users = User.admin(true).to_a + assert users.any? + assert users.all? {|u| u.admin == true} + end + + def test_admin_scope_with_false_should_return_non_admin_users + users = User.admin(false).to_a + assert users.any? + assert users.all? {|u| u.admin == false} + end + def test_sorted_scope_should_sort_user_by_display_name # Use .active to ignore anonymous with localized display name assert_equal User.active.map(&:name).map(&:downcase).sort, @@ -1049,7 +1067,7 @@ class UserTest < ActiveSupport::TestCase end def test_own_account_deletable_should_be_false_for_a_single_admin - User.where(["admin = ? AND id <> ?", true, 1]).delete_all + User.admin.where("id <> ?", 1).delete_all with_settings :unsubscribe => '1' do assert_equal false, User.find(1).own_account_deletable?