user_spec.rb 118.3 KB
Newer Older
1 2
# frozen_string_literal: true

G
gitlabhq 已提交
3 4
require 'spec_helper'

5
describe User do
B
Bob Van Landuyt 已提交
6
  include ProjectForksHelper
7
  include TermsHelper
8

S
Shinya Maeda 已提交
9
  it_behaves_like 'having unique enum values'
S
Shinya Maeda 已提交
10

11 12 13 14 15 16 17
  describe 'modules' do
    subject { described_class }

    it { is_expected.to include_module(Gitlab::ConfigHelper) }
    it { is_expected.to include_module(Referable) }
    it { is_expected.to include_module(Sortable) }
    it { is_expected.to include_module(TokenAuthenticatable) }
18
    it { is_expected.to include_module(BlocksJsonSerialization) }
19 20
  end

21 22 23 24
  describe 'delegations' do
    it { is_expected.to delegate_method(:path).to(:namespace).with_prefix }
  end

25
  describe 'associations' do
26
    it { is_expected.to have_one(:namespace) }
B
Bob Van Landuyt 已提交
27
    it { is_expected.to have_one(:status) }
28
    it { is_expected.to have_many(:snippets).dependent(:destroy) }
29 30 31
    it { is_expected.to have_many(:members) }
    it { is_expected.to have_many(:project_members) }
    it { is_expected.to have_many(:group_members) }
32 33
    it { is_expected.to have_many(:groups) }
    it { is_expected.to have_many(:keys).dependent(:destroy) }
34
    it { is_expected.to have_many(:deploy_keys).dependent(:nullify) }
35
    it { is_expected.to have_many(:events).dependent(:delete_all) }
36
    it { is_expected.to have_many(:issues).dependent(:destroy) }
37 38 39
    it { is_expected.to have_many(:notes).dependent(:destroy) }
    it { is_expected.to have_many(:merge_requests).dependent(:destroy) }
    it { is_expected.to have_many(:identities).dependent(:destroy) }
40
    it { is_expected.to have_many(:spam_logs).dependent(:destroy) }
41
    it { is_expected.to have_many(:todos) }
42
    it { is_expected.to have_many(:award_emoji).dependent(:destroy) }
K
Kamil Trzcinski 已提交
43
    it { is_expected.to have_many(:triggers).dependent(:destroy) }
44 45
    it { is_expected.to have_many(:builds).dependent(:nullify) }
    it { is_expected.to have_many(:pipelines).dependent(:nullify) }
K
Kamil Trzcinski 已提交
46
    it { is_expected.to have_many(:chat_names).dependent(:destroy) }
J
Jan Provaznik 已提交
47
    it { is_expected.to have_many(:uploads) }
48
    it { is_expected.to have_many(:reported_abuse_reports).dependent(:destroy).class_name('AbuseReport') }
49
    it { is_expected.to have_many(:custom_attributes).class_name('UserCustomAttribute') }
50
    it { is_expected.to have_many(:releases).dependent(:nullify) }
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
    describe "#abuse_report" do
      let(:current_user) { create(:user) }
      let(:other_user) { create(:user) }

      it { is_expected.to have_one(:abuse_report) }

      it "refers to the abuse report whose user_id is the current user" do
        abuse_report = create(:abuse_report, reporter: other_user, user: current_user)

        expect(current_user.abuse_report).to eq(abuse_report)
      end

      it "does not refer to the abuse report whose reporter_id is the current user" do
        create(:abuse_report, reporter: current_user, user: other_user)

        expect(current_user.abuse_report).to be_nil
      end

      it "does not update the user_id of an abuse report when the user is updated" do
        abuse_report = create(:abuse_report, reporter: current_user, user: other_user)

        current_user.block

        expect(abuse_report.reload.user).to eq(other_user)
      end
    end
78 79 80 81

    describe '#group_members' do
      it 'does not include group memberships for which user is a requester' do
        user = create(:user)
82
        group = create(:group, :public)
83 84 85 86 87 88 89 90 91
        group.request_access(user)

        expect(user.group_members).to be_empty
      end
    end

    describe '#project_members' do
      it 'does not include project memberships for which user is a requester' do
        user = create(:user)
92
        project = create(:project, :public)
93 94 95 96 97
        project.request_access(user)

        expect(user.project_members).to be_empty
      end
    end
98 99 100
  end

  describe 'validations' do
101 102 103 104 105
    describe 'name' do
      it { is_expected.to validate_presence_of(:name) }
      it { is_expected.to validate_length_of(:name).is_at_most(128) }
    end

106 107 108 109 110 111 112 113
    describe 'first name' do
      it { is_expected.to validate_length_of(:first_name).is_at_most(255) }
    end

    describe 'last name' do
      it { is_expected.to validate_length_of(:last_name).is_at_most(255) }
    end

R
Robert Speicher 已提交
114 115 116 117 118 119 120 121 122
    describe 'username' do
      it 'validates presence' do
        expect(subject).to validate_presence_of(:username)
      end

      it 'rejects blacklisted names' do
        user = build(:user, username: 'dashboard')

        expect(user).not_to be_valid
123
        expect(user.errors.messages[:username]).to eq ['dashboard is a reserved name']
R
Robert Speicher 已提交
124 125
      end

126 127 128 129 130 131 132 133 134 135 136 137
      it 'allows child names' do
        user = build(:user, username: 'avatar')

        expect(user).to be_valid
      end

      it 'allows wildcard names' do
        user = build(:user, username: 'blob')

        expect(user).to be_valid
      end

138 139 140 141 142 143 144 145 146 147
      context 'when username is changed' do
        let(:user) { build_stubbed(:user, username: 'old_path', namespace: build_stubbed(:namespace)) }

        it 'validates move_dir is allowed for the namespace' do
          expect(user.namespace).to receive(:any_project_has_container_registry_tags?).and_return(true)
          user.username = 'new_path'
          expect(user).to be_invalid
          expect(user.errors.messages[:username].first).to match('cannot be changed if a personal project has container registry tags')
        end
      end
148

149 150 151 152 153 154 155 156 157
      context 'when the username is in use by another user' do
        let(:username) { 'foo' }
        let!(:other_user) { create(:user, username: username) }

        it 'is invalid' do
          user = build(:user, username: username)

          expect(user).not_to be_valid
          expect(user.errors.full_messages).to eq(['Username has already been taken'])
158 159
        end
      end
R
Robert Speicher 已提交
160 161
    end

162 163 164 165 166 167 168 169 170 171
    it 'has a DB-level NOT NULL constraint on projects_limit' do
      user = create(:user)

      expect(user.persisted?).to eq(true)

      expect do
        user.update_columns(projects_limit: nil)
      end.to raise_error(ActiveRecord::StatementInvalid)
    end

172 173 174 175
    it { is_expected.to validate_presence_of(:projects_limit) }
    it { is_expected.to validate_numericality_of(:projects_limit) }
    it { is_expected.to allow_value(0).for(:projects_limit) }
    it { is_expected.not_to allow_value(-1).for(:projects_limit) }
176
    it { is_expected.not_to allow_value(Gitlab::Database::MAX_INT_VALUE + 1).for(:projects_limit) }
177

178
    it { is_expected.to validate_length_of(:bio).is_at_most(255) }
179

180 181 182
    it_behaves_like 'an object with email-formated attributes', :email do
      subject { build(:user) }
    end
183

184 185 186
    it_behaves_like 'an object with email-formated attributes', :public_email, :notification_email do
      subject { build(:user).tap { |user| user.emails << build(:email, email: email_value) } }
    end
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    describe '#commit_email' do
      subject(:user) { create(:user) }

      it 'defaults to the primary email' do
        expect(user.email).to be_present
        expect(user.commit_email).to eq(user.email)
      end

      it 'defaults to the primary email when the column in the database is null' do
        user.update_column(:commit_email, nil)

        found_user = described_class.find_by(id: user.id)

        expect(found_user.commit_email).to eq(user.email)
      end

204 205 206 207 208 209
      it 'returns the private commit email when commit_email has _private' do
        user.update_column(:commit_email, Gitlab::PrivateCommitEmail::TOKEN)

        expect(user.commit_email).to eq(user.private_commit_email)
      end

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      it 'can be set to a confirmed email' do
        confirmed = create(:email, :confirmed, user: user)
        user.commit_email = confirmed.email

        expect(user).to be_valid
        expect(user.commit_email).to eq(confirmed.email)
      end

      it 'can not be set to an unconfirmed email' do
        unconfirmed = create(:email, user: user)
        user.commit_email = unconfirmed.email

        # This should set the commit_email attribute to the primary email
        expect(user).to be_valid
        expect(user.commit_email).to eq(user.email)
      end

      it 'can not be set to a non-existent email' do
        user.commit_email = 'non-existent-email@nonexistent.nonexistent'

        # This should set the commit_email attribute to the primary email
        expect(user).to be_valid
        expect(user.commit_email).to eq(user.email)
      end

      it 'can not be set to an invalid email, even if confirmed' do
        confirmed = create(:email, :confirmed, :skip_validate, user: user, email: 'invalid')
        user.commit_email = confirmed.email

        expect(user).not_to be_valid
      end
    end

243
    describe 'email' do
244
      context 'when no signup domains whitelisted' do
245
        before do
246
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return([])
247
        end
248

249 250 251 252 253 254
        it 'accepts any email' do
          user = build(:user, email: "info@example.com")
          expect(user).to be_valid
        end
      end

255
      context 'when a signup domain is whitelisted and subdomains are allowed' do
256
        before do
257
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com', '*.example.com'])
258
        end
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        it 'accepts info@example.com' do
          user = build(:user, email: "info@example.com")
          expect(user).to be_valid
        end

        it 'accepts info@test.example.com' do
          user = build(:user, email: "info@test.example.com")
          expect(user).to be_valid
        end

        it 'rejects example@test.com' do
          user = build(:user, email: "example@test.com")
          expect(user).to be_invalid
        end
      end

276
      context 'when a signup domain is whitelisted and subdomains are not allowed' do
277
        before do
278
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com'])
279
        end
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

        it 'accepts info@example.com' do
          user = build(:user, email: "info@example.com")
          expect(user).to be_valid
        end

        it 'rejects info@test.example.com' do
          user = build(:user, email: "info@test.example.com")
          expect(user).to be_invalid
        end

        it 'rejects example@test.com' do
          user = build(:user, email: "example@test.com")
          expect(user).to be_invalid
        end
295 296 297 298 299

        it 'accepts example@test.com when added by another user' do
          user = build(:user, email: "example@test.com", created_by_id: 1)
          expect(user).to be_valid
        end
300
      end
301

302 303 304 305 306 307
      context 'domain blacklist' do
        before do
          allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist_enabled?).and_return(true)
          allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist).and_return(['example.com'])
        end

308
        context 'when a signup domain is blacklisted' do
309 310 311 312 313 314 315 316 317
          it 'accepts info@test.com' do
            user = build(:user, email: 'info@test.com')
            expect(user).to be_valid
          end

          it 'rejects info@example.com' do
            user = build(:user, email: 'info@example.com')
            expect(user).not_to be_valid
          end
318 319 320 321 322

          it 'accepts info@example.com when added by another user' do
            user = build(:user, email: 'info@example.com', created_by_id: 1)
            expect(user).to be_valid
          end
323 324
        end

325
        context 'when a signup domain is blacklisted but a wildcard subdomain is allowed' do
326 327
          before do
            allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist).and_return(['test.example.com'])
328
            allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['*.example.com'])
329 330
          end

331
          it 'gives priority to whitelist and allow info@test.example.com' do
332 333 334 335 336 337 338
            user = build(:user, email: 'info@test.example.com')
            expect(user).to be_valid
          end
        end

        context 'with both lists containing a domain' do
          before do
339
            allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['test.com'])
340 341 342 343 344 345 346 347 348 349 350 351 352 353
          end

          it 'accepts info@test.com' do
            user = build(:user, email: 'info@test.com')
            expect(user).to be_valid
          end

          it 'rejects info@example.com' do
            user = build(:user, email: 'info@example.com')
            expect(user).not_to be_valid
          end
        end
      end

354 355 356 357 358 359
      context 'owns_notification_email' do
        it 'accepts temp_oauth_email emails' do
          user = build(:user, email: "temp-email-for-oauth@example.com")
          expect(user).to be_valid
        end
      end
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

      context 'set_commit_email' do
        it 'keeps commit email when private commit email is being used' do
          user = create(:user, commit_email: Gitlab::PrivateCommitEmail::TOKEN)

          expect(user.read_attribute(:commit_email)).to eq(Gitlab::PrivateCommitEmail::TOKEN)
        end

        it 'keeps the commit email when nil' do
          user = create(:user, commit_email: nil)

          expect(user.read_attribute(:commit_email)).to be_nil
        end

        it 'reverts to nil when email is not verified' do
          user = create(:user, commit_email: "foo@bar.com")

          expect(user.read_attribute(:commit_email)).to be_nil
        end
      end

      context 'owns_commit_email' do
        it 'accepts private commit email' do
          user = build(:user, commit_email: Gitlab::PrivateCommitEmail::TOKEN)

          expect(user).to be_valid
        end

        it 'accepts nil commit email' do
          user = build(:user, commit_email: nil)

          expect(user).to be_valid
        end
      end
394
    end
395 396 397 398 399 400 401
  end

  describe "scopes" do
    describe ".with_two_factor" do
      it "returns users with 2fa enabled via OTP" do
        user_with_2fa = create(:user, :two_factor_via_otp)
        user_without_2fa = create(:user)
402
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
403 404 405 406 407 408 409 410

        expect(users_with_two_factor).to include(user_with_2fa.id)
        expect(users_with_two_factor).not_to include(user_without_2fa.id)
      end

      it "returns users with 2fa enabled via U2F" do
        user_with_2fa = create(:user, :two_factor_via_u2f)
        user_without_2fa = create(:user)
411
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
412 413 414 415 416 417 418 419

        expect(users_with_two_factor).to include(user_with_2fa.id)
        expect(users_with_two_factor).not_to include(user_without_2fa.id)
      end

      it "returns users with 2fa enabled via OTP and U2F" do
        user_with_2fa = create(:user, :two_factor_via_otp, :two_factor_via_u2f)
        user_without_2fa = create(:user)
420
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
421 422 423 424

        expect(users_with_two_factor).to eq([user_with_2fa.id])
        expect(users_with_two_factor).not_to include(user_without_2fa.id)
      end
425 426 427 428 429 430 431 432

      it 'works with ORDER BY' do
        user_with_2fa = create(:user, :two_factor_via_otp, :two_factor_via_u2f)

        expect(described_class
          .with_two_factor
          .reorder_by_name).to eq([user_with_2fa])
      end
433 434 435 436 437 438
    end

    describe ".without_two_factor" do
      it "excludes users with 2fa enabled via OTP" do
        user_with_2fa = create(:user, :two_factor_via_otp)
        user_without_2fa = create(:user)
439
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
440 441 442 443 444 445 446 447

        expect(users_without_two_factor).to include(user_without_2fa.id)
        expect(users_without_two_factor).not_to include(user_with_2fa.id)
      end

      it "excludes users with 2fa enabled via U2F" do
        user_with_2fa = create(:user, :two_factor_via_u2f)
        user_without_2fa = create(:user)
448
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
449 450 451 452 453 454 455 456

        expect(users_without_two_factor).to include(user_without_2fa.id)
        expect(users_without_two_factor).not_to include(user_with_2fa.id)
      end

      it "excludes users with 2fa enabled via OTP and U2F" do
        user_with_2fa = create(:user, :two_factor_via_otp, :two_factor_via_u2f)
        user_without_2fa = create(:user)
457
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
458 459 460 461 462

        expect(users_without_two_factor).to include(user_without_2fa.id)
        expect(users_without_two_factor).not_to include(user_with_2fa.id)
      end
    end
V
Valery Sizov 已提交
463

Y
Yorick Peterse 已提交
464 465 466 467
    describe '.limit_to_todo_authors' do
      context 'when filtering by todo authors' do
        let(:user1) { create(:user) }
        let(:user2) { create(:user) }
V
Valery Sizov 已提交
468

Y
Yorick Peterse 已提交
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        before do
          create(:todo, user: user1, author: user1, state: :done)
          create(:todo, user: user2, author: user2, state: :pending)
        end

        it 'only returns users that have authored todos' do
          users = described_class.limit_to_todo_authors(
            user: user2,
            with_todos: true,
            todo_state: :pending
          )

          expect(users).to eq([user2])
        end

        it 'ignores users that do not have a todo in the matching state' do
          users = described_class.limit_to_todo_authors(
            user: user1,
            with_todos: true,
            todo_state: :pending
          )

          expect(users).to be_empty
        end
      end

      context 'when not filtering by todo authors' do
        it 'returns the input relation' do
          user1 = create(:user)
          user2 = create(:user)
          rel = described_class.limit_to_todo_authors(user: user1)

          expect(rel).to include(user1, user2)
        end
      end

      context 'when no user is provided' do
        it 'returns the input relation' do
          user1 = create(:user)
          user2 = create(:user)
          rel = described_class.limit_to_todo_authors

          expect(rel).to include(user1, user2)
        end
V
Valery Sizov 已提交
513 514
      end
    end
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

    describe '.by_username' do
      it 'finds users regardless of the case passed' do
        user = create(:user, username: 'CaMeLcAsEd')
        user2 = create(:user, username: 'UPPERCASE')

        expect(described_class.by_username(%w(CAMELCASED uppercase)))
          .to contain_exactly(user, user2)
      end

      it 'finds a single user regardless of the case passed' do
        user = create(:user, username: 'CaMeLcAsEd')

        expect(described_class.by_username('CAMELCASED'))
          .to contain_exactly(user)
      end
    end
G
gitlabhq 已提交
532 533 534
  end

  describe "Respond to" do
B
blackst0ne 已提交
535
    it { is_expected.to respond_to(:admin?) }
536
    it { is_expected.to respond_to(:name) }
Z
Zeger-Jan van de Weg 已提交
537 538 539 540
    it { is_expected.to respond_to(:external?) }
  end

  describe 'before save hook' do
541 542 543 544 545 546 547 548 549 550 551
    context '#default_private_profile_to_false' do
      let(:user) { create(:user, private_profile: true) }

      it 'converts nil to false' do
        user.private_profile = nil
        user.save!

        expect(user.private_profile).to eq false
      end
    end

Z
Zeger-Jan van de Weg 已提交
552 553 554 555 556 557 558 559 560 561
    context 'when saving an external user' do
      let(:user)          { create(:user) }
      let(:external_user) { create(:user, external: true) }

      it "sets other properties aswell" do
        expect(external_user.can_create_team).to be_falsey
        expect(external_user.can_create_group).to be_falsey
        expect(external_user.projects_limit).to be 0
      end
    end
562

563 564
    describe '#check_for_verified_email' do
      let(:user)      { create(:user) }
565 566
      let(:secondary) { create(:email, :confirmed, email: 'secondary@example.com', user: user) }

567
      it 'allows a verfied secondary email to be used as the primary without needing reconfirmation' do
L
Lin Jen-Shin 已提交
568
        user.update!(email: secondary.email)
569 570 571 572 573 574
        user.reload
        expect(user.email).to eq secondary.email
        expect(user.unconfirmed_email).to eq nil
        expect(user.confirmed?).to be_truthy
      end
    end
G
gitlabhq 已提交
575 576
  end

577
  describe 'after commit hook' do
578 579 580 581 582 583 584 585 586 587 588
    describe '#update_emails_with_primary_email' do
      before do
        @user = create(:user, email: 'primary@example.com').tap do |user|
          user.skip_reconfirmation!
        end
        @secondary = create :email, email: 'secondary@example.com', user: @user
        @user.reload
      end

      it 'gets called when email updated' do
        expect(@user).to receive(:update_emails_with_primary_email)
589

L
Lin Jen-Shin 已提交
590
        @user.update!(email: 'new_primary@example.com')
591 592
      end

593
      it 'adds old primary to secondary emails when secondary is a new email ' do
L
Lin Jen-Shin 已提交
594
        @user.update!(email: 'new_primary@example.com')
595
        @user.reload
596

597 598
        expect(@user.emails.count).to eq 2
        expect(@user.emails.pluck(:email)).to match_array([@secondary.email, 'primary@example.com'])
599 600 601
      end

      it 'adds old primary to secondary emails if secondary is becoming a primary' do
L
Lin Jen-Shin 已提交
602
        @user.update!(email: @secondary.email)
603
        @user.reload
604

605 606 607 608 609
        expect(@user.emails.count).to eq 1
        expect(@user.emails.first.email).to eq 'primary@example.com'
      end

      it 'transfers old confirmation values into new secondary' do
L
Lin Jen-Shin 已提交
610
        @user.update!(email: @secondary.email)
611
        @user.reload
612

613 614 615 616
        expect(@user.emails.count).to eq 1
        expect(@user.emails.first.confirmed_at).not_to eq nil
      end
    end
617 618

    describe '#update_notification_email' do
619
      # Regression: https://gitlab.com/gitlab-org/gitlab-foss/issues/22846
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
      context 'when changing :email' do
        let(:user) { create(:user) }
        let(:new_email) { 'new-email@example.com' }

        it 'sets :unconfirmed_email' do
          expect do
            user.tap { |u| u.update!(email: new_email) }.reload
          end.to change(user, :unconfirmed_email).to(new_email)
        end

        it 'does not change :notification_email' do
          expect do
            user.tap { |u| u.update!(email: new_email) }.reload
          end.not_to change(user, :notification_email)
        end

        it 'updates :notification_email to the new email once confirmed' do
          user.update!(email: new_email)

          expect do
            user.tap(&:confirm).reload
          end.to change(user, :notification_email).to eq(new_email)
        end

        context 'and :notification_email is set to a secondary email' do
          let!(:email_attrs) { attributes_for(:email, :confirmed, user: user) }
          let(:secondary) { create(:email, :confirmed, email: 'secondary@example.com', user: user) }

          before do
            user.emails.create(email_attrs)
            user.tap { |u| u.update!(notification_email: email_attrs[:email]) }.reload
          end

          it 'does not change :notification_email to :email' do
            expect do
              user.tap { |u| u.update!(email: new_email) }.reload
            end.not_to change(user, :notification_email)
          end

          it 'does not change :notification_email to :email once confirmed' do
            user.update!(email: new_email)

            expect do
              user.tap(&:confirm).reload
            end.not_to change(user, :notification_email)
          end
        end
      end
    end

    describe '#update_invalid_gpg_signatures' do
      let(:user) do
        create(:user, email: 'tula.torphy@abshire.ca').tap do |user|
          user.skip_reconfirmation!
        end
      end

      it 'does nothing when the name is updated' do
        expect(user).not_to receive(:update_invalid_gpg_signatures)
L
Lin Jen-Shin 已提交
679
        user.update!(name: 'Bette')
680 681 682 683
      end

      it 'synchronizes the gpg keys when the email is updated' do
        expect(user).to receive(:update_invalid_gpg_signatures).at_most(:twice)
L
Lin Jen-Shin 已提交
684
        user.update!(email: 'shawnee.ritchie@denesik.com')
685 686
      end
    end
687 688
  end

689 690 691 692 693 694 695 696 697 698 699 700
  describe 'name getters' do
    let(:user) { create(:user, name: 'Kane Martin William') }

    it 'derives first name from full name, if not present' do
      expect(user.first_name).to eq('Kane')
    end

    it 'derives last name from full name, if not present' do
      expect(user.last_name).to eq('Martin William')
    end
  end

T
Thiago Presa 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
  describe '#highest_role' do
    let(:user) { create(:user) }

    let(:group) { create(:group) }

    it 'returns NO_ACCESS if none has been set' do
      expect(user.highest_role).to eq(Gitlab::Access::NO_ACCESS)
    end

    it 'returns MAINTAINER if user is maintainer of a project' do
      create(:project, group: group) do |project|
        project.add_maintainer(user)
      end

      expect(user.highest_role).to eq(Gitlab::Access::MAINTAINER)
    end

    it 'returns the highest role if user is member of multiple projects' do
      create(:project, group: group) do |project|
        project.add_maintainer(user)
      end

      create(:project, group: group) do |project|
        project.add_developer(user)
      end

      expect(user.highest_role).to eq(Gitlab::Access::MAINTAINER)
    end

    it 'returns MAINTAINER if user is maintainer of a group' do
      create(:group) do |group|
        group.add_user(user, GroupMember::MAINTAINER)
      end

      expect(user.highest_role).to eq(Gitlab::Access::MAINTAINER)
    end

    it 'returns the highest role if user is member of multiple groups' do
      create(:group) do |group|
        group.add_user(user, GroupMember::MAINTAINER)
      end

      create(:group) do |group|
        group.add_user(user, GroupMember::DEVELOPER)
      end

      expect(user.highest_role).to eq(Gitlab::Access::MAINTAINER)
    end

    it 'returns the highest role if user is member of multiple groups and projects' do
      create(:group) do |group|
        group.add_user(user, GroupMember::DEVELOPER)
      end

      create(:project, group: group) do |project|
        project.add_maintainer(user)
      end

      expect(user.highest_role).to eq(Gitlab::Access::MAINTAINER)
    end
  end

763
  describe '#update_tracked_fields!', :clean_gitlab_redis_shared_state do
764 765 766 767 768 769 770 771 772 773 774 775 776 777
    let(:request) { OpenStruct.new(remote_ip: "127.0.0.1") }
    let(:user) { create(:user) }

    it 'writes trackable attributes' do
      expect do
        user.update_tracked_fields!(request)
      end.to change { user.reload.current_sign_in_at }
    end

    it 'does not write trackable attributes when called a second time within the hour' do
      user.update_tracked_fields!(request)

      expect do
        user.update_tracked_fields!(request)
778 779 780 781 782 783 784 785 786 787 788
      end.not_to change { user.reload.current_sign_in_at }
    end

    it 'writes trackable attributes for a different user' do
      user2 = create(:user)

      user.update_tracked_fields!(request)

      expect do
        user2.update_tracked_fields!(request)
      end.to change { user2.reload.current_sign_in_at }
789
    end
790 791 792 793 794 795 796 797

    it 'does not write if the DB is in read-only mode' do
      expect(Gitlab::Database).to receive(:read_only?).and_return(true)

      expect do
        user.update_tracked_fields!(request)
      end.not_to change { user.reload.current_sign_in_at }
    end
798 799
  end

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
  shared_context 'user keys' do
    let(:user) { create(:user) }
    let!(:key) { create(:key, user: user) }
    let!(:deploy_key) { create(:deploy_key, user: user) }
  end

  describe '#keys' do
    include_context 'user keys'

    context 'with key and deploy key stored' do
      it 'returns stored key, but not deploy_key' do
        expect(user.keys).to include key
        expect(user.keys).not_to include deploy_key
      end
    end
  end

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
  describe '#accessible_deploy_keys' do
    let(:user) { create(:user) }
    let(:project) { create(:project) }
    let!(:private_deploy_keys_project) { create(:deploy_keys_project) }
    let!(:public_deploy_keys_project) { create(:deploy_keys_project) }
    let!(:accessible_deploy_keys_project) { create(:deploy_keys_project, project: project) }

    before do
      public_deploy_keys_project.deploy_key.update(public: true)
      project.add_developer(user)
    end

    it 'user can only see deploy keys accessible to right projects' do
      expect(user.accessible_deploy_keys).to match_array([public_deploy_keys_project.deploy_key,
                                                          accessible_deploy_keys_project.deploy_key])
    end
  end

835 836 837 838 839 840 841 842 843 844 845
  describe '#deploy_keys' do
    include_context 'user keys'

    context 'with key and deploy key stored' do
      it 'returns stored deploy key, but not normal key' do
        expect(user.deploy_keys).to include deploy_key
        expect(user.deploy_keys).not_to include key
      end
    end
  end

846
  describe '#confirm' do
847 848 849
    before do
      allow_any_instance_of(ApplicationSetting).to receive(:send_user_confirmation_email).and_return(true)
    end
850

851 852 853 854 855 856 857
    let(:user) { create(:user, confirmed_at: nil, unconfirmed_email: 'test@gitlab.com') }

    it 'returns unconfirmed' do
      expect(user.confirmed?).to be_falsey
    end

    it 'confirms a user' do
858
      user.confirm
859 860 861 862
      expect(user.confirmed?).to be_truthy
    end
  end

863 864 865 866 867 868 869 870
  describe '#to_reference' do
    let(:user) { create(:user) }

    it 'returns a String reference to the object' do
      expect(user.to_reference).to eq "@#{user.username}"
    end
  end

871
  describe '#generate_password' do
872
    it "does not generate password by default" do
873
      user = create(:user, password: 'abcdefghe')
874

875
      expect(user.password).to eq('abcdefghe')
876
    end
877 878
  end

879 880 881 882 883 884 885 886 887
  describe 'ensure user preference' do
    it 'has user preference upon user initialization' do
      user = build(:user)

      expect(user.user_preference).to be_present
      expect(user.user_preference).not_to be_persisted
    end
  end

888 889 890
  describe 'ensure incoming email token' do
    it 'has incoming email token' do
      user = create(:user)
891

892 893
      expect(user.incoming_email_token).not_to be_blank
    end
894 895 896 897 898 899 900 901

    it 'uses SecureRandom to generate the incoming email token' do
      expect(SecureRandom).to receive(:hex).and_return('3b8ca303')

      user = create(:user)

      expect(user.incoming_email_token).to eql('gitlab')
    end
902 903
  end

904 905 906 907 908 909 910
  describe '#ensure_user_rights_and_limits' do
    describe 'with external user' do
      let(:user) { create(:user, external: true) }

      it 'receives callback when external changes' do
        expect(user).to receive(:ensure_user_rights_and_limits)

L
Lin Jen-Shin 已提交
911
        user.update(external: false)
912 913 914
      end

      it 'ensures correct rights and limits for user' do
T
Tiago Botelho 已提交
915 916
        stub_config_setting(default_can_create_group: true)

L
Lin Jen-Shin 已提交
917
        expect { user.update(external: false) }.to change { user.can_create_group }.to(true)
918
          .and change { user.projects_limit }.to(Gitlab::CurrentSettings.default_projects_limit)
919 920 921 922 923 924 925 926 927
      end
    end

    describe 'without external user' do
      let(:user) { create(:user, external: false) }

      it 'receives callback when external changes' do
        expect(user).to receive(:ensure_user_rights_and_limits)

L
Lin Jen-Shin 已提交
928
        user.update(external: true)
929 930 931
      end

      it 'ensures correct rights and limits for user' do
L
Lin Jen-Shin 已提交
932
        expect { user.update(external: true) }.to change { user.can_create_group }.to(false)
933 934 935 936 937
          .and change { user.projects_limit }.to(0)
      end
    end
  end

938 939 940 941
  describe 'feed token' do
    it 'ensures a feed token on read' do
      user = create(:user, feed_token: nil)
      feed_token = user.feed_token
942

943 944
      expect(feed_token).not_to be_blank
      expect(user.reload.feed_token).to eq feed_token
945 946 947
    end
  end

948 949 950 951 952 953 954 955 956 957
  describe 'static object token' do
    it 'ensures a static object token on read' do
      user = create(:user, static_object_token: nil)
      static_object_token = user.static_object_token

      expect(static_object_token).not_to be_blank
      expect(user.reload.static_object_token).to eq static_object_token
    end
  end

958
  describe '#recently_sent_password_reset?' do
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    it 'is false when reset_password_sent_at is nil' do
      user = build_stubbed(:user, reset_password_sent_at: nil)

      expect(user.recently_sent_password_reset?).to eq false
    end

    it 'is false when sent more than one minute ago' do
      user = build_stubbed(:user, reset_password_sent_at: 5.minutes.ago)

      expect(user.recently_sent_password_reset?).to eq false
    end

    it 'is true when sent less than one minute ago' do
      user = build_stubbed(:user, reset_password_sent_at: Time.now)

      expect(user.recently_sent_password_reset?).to eq true
    end
  end

R
Robert Speicher 已提交
978 979 980 981 982 983 984
  describe '#disable_two_factor!' do
    it 'clears all 2FA-related fields' do
      user = create(:user, :two_factor)

      expect(user).to be_two_factor_enabled
      expect(user.encrypted_otp_secret).not_to be_nil
      expect(user.otp_backup_codes).not_to be_nil
985
      expect(user.otp_grace_period_started_at).not_to be_nil
R
Robert Speicher 已提交
986 987 988 989 990 991 992 993

      user.disable_two_factor!

      expect(user).not_to be_two_factor_enabled
      expect(user.encrypted_otp_secret).to be_nil
      expect(user.encrypted_otp_secret_iv).to be_nil
      expect(user.encrypted_otp_secret_salt).to be_nil
      expect(user.otp_backup_codes).to be_nil
994
      expect(user.otp_grace_period_started_at).to be_nil
R
Robert Speicher 已提交
995 996 997
    end
  end

998 999
  describe 'projects' do
    before do
1000
      @user = create(:user)
1001

1002 1003
      @project = create(:project, namespace: @user.namespace)
      @project_2 = create(:project, group: create(:group)) do |project|
1004
        project.add_maintainer(@user)
1005
      end
1006
      @project_3 = create(:project, group: create(:group)) do |project|
1007 1008
        project.add_developer(@user)
      end
1009 1010
    end

1011 1012 1013 1014 1015 1016 1017 1018 1019
    it { expect(@user.authorized_projects).to include(@project) }
    it { expect(@user.authorized_projects).to include(@project_2) }
    it { expect(@user.authorized_projects).to include(@project_3) }
    it { expect(@user.owned_projects).to include(@project) }
    it { expect(@user.owned_projects).not_to include(@project_2) }
    it { expect(@user.owned_projects).not_to include(@project_3) }
    it { expect(@user.personal_projects).to include(@project) }
    it { expect(@user.personal_projects).not_to include(@project_2) }
    it { expect(@user.personal_projects).not_to include(@project_3) }
1020 1021 1022
  end

  describe 'groups' do
1023 1024 1025
    let(:user) { create(:user) }
    let(:group) { create(:group) }

1026
    before do
1027
      group.add_owner(user)
1028 1029
    end

1030 1031 1032 1033 1034 1035
    it { expect(user.several_namespaces?).to be_truthy }
    it { expect(user.authorized_groups).to eq([group]) }
    it { expect(user.owned_groups).to eq([group]) }
    it { expect(user.namespaces).to contain_exactly(user.namespace, group) }
    it { expect(user.manageable_namespaces).to contain_exactly(user.namespace, group) }

1036
    context 'with child groups' do
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
      let!(:subgroup) { create(:group, parent: group) }

      describe '#manageable_namespaces' do
        it 'includes all the namespaces the user can manage' do
          expect(user.manageable_namespaces).to contain_exactly(user.namespace, group, subgroup)
        end
      end

      describe '#manageable_groups' do
        it 'includes all the namespaces the user can manage' do
          expect(user.manageable_groups).to contain_exactly(group, subgroup)
        end

        it 'does not include duplicates if a membership was added for the subgroup' do
          subgroup.add_owner(user)

          expect(user.manageable_groups).to contain_exactly(group, subgroup)
        end
      end
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

      describe '#manageable_groups_with_routes' do
        it 'eager loads routes from manageable groups' do
          control_count =
            ActiveRecord::QueryRecorder.new(skip_cached: false) do
              user.manageable_groups_with_routes.map(&:route)
            end.count

          create(:group, parent: subgroup)

          expect do
            user.manageable_groups_with_routes.map(&:route)
          end.not_to exceed_all_query_limit(control_count)
        end
      end
1071
    end
1072 1073
  end

1074 1075 1076 1077
  describe 'group multiple owners' do
    before do
      @user = create :user
      @user2 = create :user
1078 1079
      @group = create :group
      @group.add_owner(@user)
1080

1081
      @group.add_user(@user2, GroupMember::OWNER)
1082 1083
    end

1084
    it { expect(@user2.several_namespaces?).to be_truthy }
1085 1086
  end

1087 1088 1089
  describe 'namespaced' do
    before do
      @user = create :user
1090
      @project = create(:project, namespace: @user.namespace)
1091 1092
    end

1093
    it { expect(@user.several_namespaces?).to be_falsey }
1094
    it { expect(@user.namespaces).to eq([@user.namespace]) }
1095 1096 1097 1098 1099
  end

  describe 'blocking user' do
    let(:user) { create(:user, name: 'John Smith') }

1100
    it 'blocks user' do
1101
      user.block
1102

1103
      expect(user.blocked?).to be_truthy
1104
    end
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

    context 'when user has running CI pipelines' do
      let(:service) { double }

      before do
        pipeline = create(:ci_pipeline, :running, user: user)
        create(:ci_build, :running, pipeline: pipeline)
      end

      it 'cancels all running pipelines and related jobs' do
        expect(Ci::CancelUserPipelinesService).to receive(:new).and_return(service)
        expect(service).to receive(:execute).with(user)

        user.block
      end
    end
1121 1122
  end

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  describe 'deactivating a user' do
    let(:user) { create(:user, name: 'John Smith') }

    context "an active user" do
      it "can be deactivated" do
        user.deactivate

        expect(user.deactivated?).to be_truthy
      end
    end

    context "a user who is blocked" do
      before do
        user.block
      end

      it "cannot be deactivated" do
        user.deactivate

        expect(user.reload.deactivated?).to be_falsy
      end
    end
  end

1147
  describe '.filter_items' do
1148 1149 1150
    let(:user) { double }

    it 'filters by active users by default' do
1151
      expect(described_class).to receive(:active).and_return([user])
1152

1153
      expect(described_class.filter_items(nil)).to include user
1154 1155
    end

1156
    it 'filters by admins' do
1157
      expect(described_class).to receive(:admins).and_return([user])
1158

1159
      expect(described_class.filter_items('admins')).to include user
1160 1161
    end

1162
    it 'filters by blocked' do
1163
      expect(described_class).to receive(:blocked).and_return([user])
1164

1165
      expect(described_class.filter_items('blocked')).to include user
1166 1167
    end

1168 1169 1170 1171 1172 1173
    it 'filters by deactivated' do
      expect(described_class).to receive(:deactivated).and_return([user])

      expect(described_class.filter_items('deactivated')).to include user
    end

1174
    it 'filters by two_factor_disabled' do
1175
      expect(described_class).to receive(:without_two_factor).and_return([user])
1176

1177
      expect(described_class.filter_items('two_factor_disabled')).to include user
1178 1179 1180
    end

    it 'filters by two_factor_enabled' do
1181
      expect(described_class).to receive(:with_two_factor).and_return([user])
1182

1183
      expect(described_class.filter_items('two_factor_enabled')).to include user
1184 1185 1186
    end

    it 'filters by wop' do
1187
      expect(described_class).to receive(:without_projects).and_return([user])
1188

1189
      expect(described_class.filter_items('wop')).to include user
1190
    end
1191 1192
  end

B
Ben Bodenmiller 已提交
1193
  describe '.without_projects' do
1194
    let!(:project) { create(:project, :public) }
B
Ben Bodenmiller 已提交
1195 1196 1197 1198 1199 1200
    let!(:user) { create(:user) }
    let!(:user_without_project) { create(:user) }
    let!(:user_without_project2) { create(:user) }

    before do
      # add user to project
1201
      project.add_maintainer(user)
B
Ben Bodenmiller 已提交
1202 1203 1204 1205 1206 1207 1208 1209

      # create invite to projet
      create(:project_member, :developer, project: project, invite_token: '1234', invite_email: 'inviteduser1@example.com')

      # create request to join project
      project.request_access(user_without_project2)
    end

1210 1211 1212
    it { expect(described_class.without_projects).not_to include user }
    it { expect(described_class.without_projects).to include user_without_project }
    it { expect(described_class.without_projects).to include user_without_project2 }
B
Ben Bodenmiller 已提交
1213 1214
  end

1215 1216 1217
  describe 'user creation' do
    describe 'normal user' do
      let(:user) { create(:user, name: 'John Smith') }
D
Dmitriy Zaporozhets 已提交
1218

B
blackst0ne 已提交
1219
      it { expect(user.admin?).to be_falsey }
1220 1221 1222 1223
      it { expect(user.require_ssh_key?).to be_truthy }
      it { expect(user.can_create_group?).to be_truthy }
      it { expect(user.can_create_project?).to be_truthy }
      it { expect(user.first_name).to eq('John') }
1224
      it { expect(user.external).to be_falsey }
1225
    end
1226

D
Dmitriy Zaporozhets 已提交
1227
    describe 'with defaults' do
1228
      let(:user) { described_class.new }
D
Dmitriy Zaporozhets 已提交
1229

1230
      it "applies defaults to user" do
1231 1232
        expect(user.projects_limit).to eq(Gitlab.config.gitlab.default_projects_limit)
        expect(user.can_create_group).to eq(Gitlab.config.gitlab.default_can_create_group)
1233
        expect(user.theme_id).to eq(Gitlab.config.gitlab.default_theme)
Z
Zeger-Jan van de Weg 已提交
1234
        expect(user.external).to be_falsey
1235
        expect(user.private_profile).to eq(false)
1236 1237 1238
      end
    end

D
Dmitriy Zaporozhets 已提交
1239
    describe 'with default overrides' do
1240
      let(:user) { described_class.new(projects_limit: 123, can_create_group: false, can_create_team: true) }
D
Dmitriy Zaporozhets 已提交
1241

1242
      it "applies defaults to user" do
1243 1244
        expect(user.projects_limit).to eq(123)
        expect(user.can_create_group).to be_falsey
1245
        expect(user.theme_id).to eq(1)
1246
      end
1247 1248 1249 1250 1251 1252 1253

      it 'does not undo projects_limit setting if it matches old DB default of 10' do
        # If the real default project limit is 10 then this test is worthless
        expect(Gitlab.config.gitlab.default_projects_limit).not_to eq(10)
        user = described_class.new(projects_limit: 10)
        expect(user.projects_limit).to eq(10)
      end
1254
    end
1255

1256
    context 'when Gitlab::CurrentSettings.user_default_external is true' do
1257 1258 1259 1260 1261
      before do
        stub_application_setting(user_default_external: true)
      end

      it "creates external user by default" do
1262
        user = create(:user)
1263 1264

        expect(user.external).to be_truthy
1265 1266
        expect(user.can_create_group).to be_falsey
        expect(user.projects_limit).to be 0
1267 1268 1269 1270
      end

      describe 'with default overrides' do
        it "creates a non-external user" do
1271
          user = create(:user, external: false)
1272 1273 1274 1275 1276

          expect(user.external).to be_falsey
        end
      end
    end
1277

Y
Yorick Peterse 已提交
1278
    describe '#require_ssh_key?', :use_clean_rails_memory_store_caching do
1279 1280 1281
      protocol_and_expectation = {
        'http' => false,
        'ssh' => true,
1282
        '' => true
1283 1284 1285 1286 1287 1288 1289 1290 1291
      }

      protocol_and_expectation.each do |protocol, expected|
        it "has correct require_ssh_key?" do
          stub_application_setting(enabled_git_access_protocol: protocol)
          user = build(:user)

          expect(user.require_ssh_key?).to eq(expected)
        end
1292
      end
Y
Yorick Peterse 已提交
1293 1294 1295 1296 1297 1298

      it 'returns false when the user has 1 or more SSH keys' do
        key = create(:personal_key)

        expect(key.user.require_ssh_key?).to eq(false)
      end
1299
    end
1300
  end
1301

1302 1303 1304 1305 1306 1307 1308 1309
  describe '.find_for_database_authentication' do
    it 'strips whitespace from login' do
      user = create(:user)

      expect(described_class.find_for_database_authentication({ login: " #{user.username} " })).to eq user
    end
  end

1310
  describe '.find_by_any_email' do
1311 1312 1313 1314 1315 1316 1317 1318
    it 'finds user through private commit email' do
      user = create(:user)
      private_email = user.private_commit_email

      expect(described_class.find_by_any_email(private_email)).to eq(user)
      expect(described_class.find_by_any_email(private_email, confirmed: true)).to eq(user)
    end

1319 1320 1321
    it 'finds by primary email' do
      user = create(:user, email: 'foo@example.com')

1322
      expect(described_class.find_by_any_email(user.email)).to eq user
1323
      expect(described_class.find_by_any_email(user.email, confirmed: true)).to eq user
1324 1325
    end

1326 1327 1328 1329 1330 1331 1332
    it 'finds by uppercased email' do
      user = create(:user, email: 'foo@example.com')

      expect(described_class.find_by_any_email(user.email.upcase)).to eq user
      expect(described_class.find_by_any_email(user.email.upcase, confirmed: true)).to eq user
    end

1333 1334
    context 'finds by secondary email' do
      let(:user) { email.user }
1335

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
      context 'primary email confirmed' do
        context 'secondary email confirmed' do
          let!(:email) { create(:email, :confirmed, email: 'foo@example.com') }

          it 'finds user respecting the confirmed flag' do
            expect(described_class.find_by_any_email(email.email)).to eq user
            expect(described_class.find_by_any_email(email.email, confirmed: true)).to eq user
          end
        end

        context 'secondary email not confirmed' do
          let!(:email) { create(:email, email: 'foo@example.com') }

          it 'finds user respecting the confirmed flag' do
            expect(described_class.find_by_any_email(email.email)).to eq user
            expect(described_class.find_by_any_email(email.email, confirmed: true)).to be_nil
          end
        end
      end

      context 'primary email not confirmed' do
        let(:user) { create(:user, confirmed_at: nil) }
        let!(:email) { create(:email, :confirmed, user: user, email: 'foo@example.com') }

        it 'finds user respecting the confirmed flag' do
          expect(described_class.find_by_any_email(email.email)).to eq user
          expect(described_class.find_by_any_email(email.email, confirmed: true)).to be_nil
        end
      end
1365 1366 1367
    end

    it 'returns nil when nothing found' do
1368
      expect(described_class.find_by_any_email('')).to be_nil
1369
    end
1370 1371 1372 1373 1374 1375 1376

    it 'returns nil when user is not confirmed' do
      user = create(:user, email: 'foo@example.com', confirmed_at: nil)

      expect(described_class.find_by_any_email(user.email, confirmed: false)).to eq(user)
      expect(described_class.find_by_any_email(user.email, confirmed: true)).to be_nil
    end
1377 1378
  end

Y
Yorick Peterse 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  describe '.by_any_email' do
    it 'returns an ActiveRecord::Relation' do
      expect(described_class.by_any_email('foo@example.com'))
        .to be_a_kind_of(ActiveRecord::Relation)
    end

    it 'returns a relation of users' do
      user = create(:user)

      expect(described_class.by_any_email(user.email)).to eq([user])
    end
1390 1391 1392 1393 1394 1395

    it 'returns a relation of users for confirmed users' do
      user = create(:user)

      expect(described_class.by_any_email(user.email, confirmed: true)).to eq([user])
    end
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411

    it 'finds user through a private commit email' do
      user = create(:user)
      private_email = user.private_commit_email

      expect(described_class.by_any_email(private_email)).to eq([user])
      expect(described_class.by_any_email(private_email, confirmed: true)).to eq([user])
    end

    it 'finds user through a private commit email in an array' do
      user = create(:user)
      private_email = user.private_commit_email

      expect(described_class.by_any_email([private_email])).to eq([user])
      expect(described_class.by_any_email([private_email], confirmed: true)).to eq([user])
    end
Y
Yorick Peterse 已提交
1412 1413
  end

1414
  describe '.search' do
1415 1416
    let!(:user) { create(:user, name: 'user', username: 'usern', email: 'email@gmail.com') }
    let!(:user2) { create(:user, name: 'user name', username: 'username', email: 'someemail@gmail.com') }
1417
    let!(:user3) { create(:user, name: 'us', username: 'se', email: 'foo@gmail.com') }
1418

1419 1420 1421 1422
    describe 'name matching' do
      it 'returns users with a matching name with exact match first' do
        expect(described_class.search(user.name)).to eq([user, user2])
      end
1423

1424
      it 'returns users with a partially matching name' do
1425
        expect(described_class.search(user.name[0..2])).to eq([user, user2])
1426
      end
1427

1428 1429 1430
      it 'returns users with a matching name regardless of the casing' do
        expect(described_class.search(user2.name.upcase)).to eq([user2])
      end
1431 1432 1433 1434 1435 1436 1437 1438

      it 'returns users with a exact matching name shorter than 3 chars' do
        expect(described_class.search(user3.name)).to eq([user3])
      end

      it 'returns users with a exact matching name shorter than 3 chars regardless of the casing' do
        expect(described_class.search(user3.name.upcase)).to eq([user3])
      end
1439 1440
    end

1441 1442
    describe 'email matching' do
      it 'returns users with a matching Email' do
1443
        expect(described_class.search(user.email)).to eq([user])
1444
      end
1445

1446 1447
      it 'does not return users with a partially matching Email' do
        expect(described_class.search(user.email[0..2])).not_to include(user, user2)
1448
      end
1449

1450 1451 1452
      it 'returns users with a matching Email regardless of the casing' do
        expect(described_class.search(user2.email.upcase)).to eq([user2])
      end
1453 1454
    end

1455 1456 1457 1458
    describe 'username matching' do
      it 'returns users with a matching username' do
        expect(described_class.search(user.username)).to eq([user, user2])
      end
1459

1460 1461 1462 1463
      it 'returns users with a matching username starting with a @' do
        expect(described_class.search("@#{user.username}")).to eq([user, user2])
      end

1464
      it 'returns users with a partially matching username' do
1465
        expect(described_class.search(user.username[0..2])).to eq([user, user2])
1466
      end
1467

1468 1469 1470 1471
      it 'returns users with a partially matching username starting with @' do
        expect(described_class.search("@#{user.username[0..2]}")).to eq([user, user2])
      end

1472 1473 1474
      it 'returns users with a matching username regardless of the casing' do
        expect(described_class.search(user2.username.upcase)).to eq([user2])
      end
1475 1476 1477 1478 1479 1480 1481 1482

      it 'returns users with a exact matching username shorter than 3 chars' do
        expect(described_class.search(user3.username)).to eq([user3])
      end

      it 'returns users with a exact matching username shorter than 3 chars regardless of the casing' do
        expect(described_class.search(user3.username.upcase)).to eq([user3])
      end
M
Marin Jankovski 已提交
1483
    end
1484 1485 1486 1487 1488 1489 1490 1491

    it 'returns no matches for an empty string' do
      expect(described_class.search('')).to be_empty
    end

    it 'returns no matches for nil' do
      expect(described_class.search(nil)).to be_empty
    end
1492 1493 1494
  end

  describe '.search_with_secondary_emails' do
D
Douwe Maan 已提交
1495
    delegate :search_with_secondary_emails, to: :described_class
1496

1497 1498
    let!(:user) { create(:user, name: 'John Doe', username: 'john.doe', email: 'john.doe@example.com' ) }
    let!(:another_user) { create(:user, name: 'Albert Smith', username: 'albert.smith', email: 'albert.smith@example.com' ) }
1499 1500 1501
    let!(:email) do
      create(:email, user: another_user, email: 'alias@example.com')
    end
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518

    it 'returns users with a matching name' do
      expect(search_with_secondary_emails(user.name)).to eq([user])
    end

    it 'returns users with a partially matching name' do
      expect(search_with_secondary_emails(user.name[0..2])).to eq([user])
    end

    it 'returns users with a matching name regardless of the casing' do
      expect(search_with_secondary_emails(user.name.upcase)).to eq([user])
    end

    it 'returns users with a matching email' do
      expect(search_with_secondary_emails(user.email)).to eq([user])
    end

1519 1520
    it 'does not return users with a partially matching email' do
      expect(search_with_secondary_emails(user.email[0..2])).not_to include([user])
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
    end

    it 'returns users with a matching email regardless of the casing' do
      expect(search_with_secondary_emails(user.email.upcase)).to eq([user])
    end

    it 'returns users with a matching username' do
      expect(search_with_secondary_emails(user.username)).to eq([user])
    end

    it 'returns users with a partially matching username' do
      expect(search_with_secondary_emails(user.username[0..2])).to eq([user])
    end

    it 'returns users with a matching username regardless of the casing' do
      expect(search_with_secondary_emails(user.username.upcase)).to eq([user])
    end

    it 'returns users with a matching whole secondary email' do
      expect(search_with_secondary_emails(email.email)).to eq([email.user])
    end

1543 1544
    it 'does not return users with a matching part of secondary email' do
      expect(search_with_secondary_emails(email.email[1..4])).not_to include([email.user])
1545
    end
1546 1547 1548 1549 1550 1551 1552 1553

    it 'returns no matches for an empty string' do
      expect(search_with_secondary_emails('')).to be_empty
    end

    it 'returns no matches for nil' do
      expect(search_with_secondary_emails(nil)).to be_empty
    end
M
Marin Jankovski 已提交
1554 1555
  end

Y
Yorick Peterse 已提交
1556
  describe '.find_by_ssh_key_id' do
1557 1558
    let_it_be(:user) { create(:user) }
    let_it_be(:key) { create(:key, user: user) }
Y
Yorick Peterse 已提交
1559

1560
    context 'using an existing SSH key ID' do
Y
Yorick Peterse 已提交
1561 1562 1563 1564 1565
      it 'returns the corresponding User' do
        expect(described_class.find_by_ssh_key_id(key.id)).to eq(user)
      end
    end

1566 1567 1568 1569 1570 1571 1572
    it 'only performs a single query' do
      key # Don't count the queries for creating the key and user

      expect { described_class.find_by_ssh_key_id(key.id) }
        .not_to exceed_query_limit(1)
    end

Y
Yorick Peterse 已提交
1573 1574 1575 1576 1577 1578 1579
    context 'using an invalid SSH key ID' do
      it 'returns nil' do
        expect(described_class.find_by_ssh_key_id(-1)).to be_nil
      end
    end
  end

1580 1581 1582 1583
  describe '.by_login' do
    let(:username) { 'John' }
    let!(:user) { create(:user, username: username) }

1584
    it 'gets the correct user' do
1585 1586 1587 1588 1589 1590
      expect(described_class.by_login(user.email.upcase)).to eq user
      expect(described_class.by_login(user.email)).to eq user
      expect(described_class.by_login(username.downcase)).to eq user
      expect(described_class.by_login(username)).to eq user
      expect(described_class.by_login(nil)).to be_nil
      expect(described_class.by_login('')).to be_nil
1591 1592 1593
    end
  end

1594 1595 1596 1597 1598 1599 1600
  describe '.find_by_username' do
    it 'returns nil if not found' do
      expect(described_class.find_by_username('JohnDoe')).to be_nil
    end

    it 'is case-insensitive' do
      user = create(:user, username: 'JohnDoe')
1601

1602 1603 1604 1605
      expect(described_class.find_by_username('JOHNDOE')).to eq user
    end
  end

R
Robert Speicher 已提交
1606 1607
  describe '.find_by_username!' do
    it 'raises RecordNotFound' do
1608 1609
      expect { described_class.find_by_username!('JohnDoe') }
        .to raise_error(ActiveRecord::RecordNotFound)
R
Robert Speicher 已提交
1610 1611 1612 1613
    end

    it 'is case-insensitive' do
      user = create(:user, username: 'JohnDoe')
1614

R
Robert Speicher 已提交
1615 1616 1617 1618
      expect(described_class.find_by_username!('JOHNDOE')).to eq user
    end
  end

1619 1620 1621 1622 1623 1624 1625
  describe '.find_by_full_path' do
    let!(:user) { create(:user) }

    context 'with a route matching the given path' do
      let!(:route) { user.namespace.route }

      it 'returns the user' do
1626
        expect(described_class.find_by_full_path(route.path)).to eq(user)
1627 1628 1629
      end

      it 'is case-insensitive' do
1630 1631
        expect(described_class.find_by_full_path(route.path.upcase)).to eq(user)
        expect(described_class.find_by_full_path(route.path.downcase)).to eq(user)
1632 1633 1634 1635 1636 1637 1638 1639
      end
    end

    context 'with a redirect route matching the given path' do
      let!(:redirect_route) { user.namespace.redirect_routes.create(path: 'foo') }

      context 'without the follow_redirects option' do
        it 'returns nil' do
1640
          expect(described_class.find_by_full_path(redirect_route.path)).to eq(nil)
1641 1642 1643 1644 1645
        end
      end

      context 'with the follow_redirects option set to true' do
        it 'returns the user' do
1646
          expect(described_class.find_by_full_path(redirect_route.path, follow_redirects: true)).to eq(user)
1647 1648 1649
        end

        it 'is case-insensitive' do
1650 1651
          expect(described_class.find_by_full_path(redirect_route.path.upcase, follow_redirects: true)).to eq(user)
          expect(described_class.find_by_full_path(redirect_route.path.downcase, follow_redirects: true)).to eq(user)
1652 1653 1654 1655 1656 1657 1658
        end
      end
    end

    context 'without a route or a redirect route matching the given path' do
      context 'without the follow_redirects option' do
        it 'returns nil' do
1659
          expect(described_class.find_by_full_path('unknown')).to eq(nil)
1660 1661 1662 1663
        end
      end
      context 'with the follow_redirects option set to true' do
        it 'returns nil' do
1664
          expect(described_class.find_by_full_path('unknown', follow_redirects: true)).to eq(nil)
1665 1666 1667 1668 1669
        end
      end
    end

    context 'with a group route matching the given path' do
1670 1671
      let!(:group) { create(:group, path: 'group_path') }

M
Michael Kozono 已提交
1672
      context 'when the group namespace has an owner_id (legacy data)' do
1673 1674 1675
        before do
          group.update!(owner_id: user.id)
        end
1676

M
Michael Kozono 已提交
1677
        it 'returns nil' do
1678
          expect(described_class.find_by_full_path('group_path')).to eq(nil)
M
Michael Kozono 已提交
1679 1680 1681 1682 1683
        end
      end

      context 'when the group namespace does not have an owner_id' do
        it 'returns nil' do
1684
          expect(described_class.find_by_full_path('group_path')).to eq(nil)
M
Michael Kozono 已提交
1685
        end
1686 1687 1688 1689
      end
    end
  end

G
GitLab 已提交
1690
  describe 'all_ssh_keys' do
1691
    it { is_expected.to have_many(:keys).dependent(:destroy) }
G
GitLab 已提交
1692

1693
    it "has all ssh keys" do
G
GitLab 已提交
1694 1695 1696
      user = create :user
      key = create :key, key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD33bWLBxu48Sev9Fert1yzEO4WGcWglWF7K/AwblIUFselOt/QdOL9DSjpQGxLagO1s9wl53STIO8qGS4Ms0EJZyIXOEFMjFJ5xmjSy+S37By4sG7SsltQEHMxtbtFOaW5LV2wCrX+rUsRNqLMamZjgjcPO0/EgGCXIGMAYW4O7cwGZdXWYIhQ1Vwy+CsVMDdPkPgBXqK7nR/ey8KMs8ho5fMNgB5hBw/AL9fNGhRw3QTD6Q12Nkhl4VZES2EsZqlpNnJttnPdp847DUsT6yuLRlfiQfz5Cn9ysHFdXObMN5VYIiPFwHeYCZp1X2S4fDZooRE8uOLTfxWHPXwrhqSH", user_id: user.id

1697
      expect(user.all_ssh_keys).to include(a_string_starting_with(key.key))
G
GitLab 已提交
1698
    end
G
GitLab 已提交
1699
  end
1700

1701
  describe '#avatar_type' do
D
Dmitriy Zaporozhets 已提交
1702 1703
    let(:user) { create(:user) }

1704
    it 'is true if avatar is image' do
D
Dmitriy Zaporozhets 已提交
1705
      user.update_attribute(:avatar, 'uploads/avatar.png')
1706

1707
      expect(user.avatar_type).to be_truthy
D
Dmitriy Zaporozhets 已提交
1708 1709
    end

1710
    it 'is false if avatar is html page' do
D
Dmitriy Zaporozhets 已提交
1711
      user.update_attribute(:avatar, 'uploads/avatar.html')
1712

1713
      expect(user.avatar_type).to eq(['file format is not supported. Please try one of the following supported formats: png, jpg, jpeg, gif, bmp, tiff, ico'])
D
Dmitriy Zaporozhets 已提交
1714 1715
    end
  end
J
Jerome Dalbert 已提交
1716

1717 1718 1719 1720
  describe '#avatar_url' do
    let(:user) { create(:user, :with_avatar) }

    context 'when avatar file is uploaded' do
1721
      it 'shows correct avatar url' do
1722 1723
        expect(user.avatar_url).to eq(user.avatar.url)
        expect(user.avatar_url(only_path: false)).to eq([Gitlab.config.gitlab.url, user.avatar.url].join)
1724
      end
1725 1726 1727
    end
  end

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
  describe '#accept_pending_invitations!' do
    let(:user) { create(:user, email: 'user@email.com') }
    let!(:project_member_invite) { create(:project_member, :invited, invite_email: user.email) }
    let!(:group_member_invite) { create(:group_member, :invited, invite_email: user.email) }
    let!(:external_project_member_invite) { create(:project_member, :invited, invite_email: 'external@email.com') }
    let!(:external_group_member_invite) { create(:group_member, :invited, invite_email: 'external@email.com') }

    it 'accepts all the user members pending invitations and returns the accepted_members' do
      accepted_members = user.accept_pending_invitations!

      expect(accepted_members).to match_array([project_member_invite, group_member_invite])
      expect(group_member_invite.reload).not_to be_invite
      expect(project_member_invite.reload).not_to be_invite
      expect(external_project_member_invite.reload).to be_invite
      expect(external_group_member_invite.reload).to be_invite
    end
  end

1746 1747 1748 1749 1750 1751 1752
  describe '#all_emails' do
    let(:user) { create(:user) }

    it 'returns all emails' do
      email_confirmed   = create :email, user: user, confirmed_at: Time.now
      email_unconfirmed = create :email, user: user
      user.reload
1753

1754 1755 1756 1757 1758 1759
      expect(user.all_emails).to contain_exactly(
        user.email,
        user.private_commit_email,
        email_unconfirmed.email,
        email_confirmed.email
      )
1760 1761 1762
    end
  end

1763
  describe '#verified_emails' do
1764 1765 1766
    let(:user) { create(:user) }

    it 'returns only confirmed emails' do
B
Brett Walker 已提交
1767 1768
      email_confirmed = create :email, user: user, confirmed_at: Time.now
      create :email, user: user
1769

1770 1771 1772 1773 1774
      expect(user.verified_emails).to contain_exactly(
        user.email,
        user.private_commit_email,
        email_confirmed.email
      )
1775 1776 1777 1778 1779 1780 1781
    end
  end

  describe '#verified_email?' do
    let(:user) { create(:user) }

    it 'returns true when the email is verified/confirmed' do
B
Brett Walker 已提交
1782 1783
      email_confirmed = create :email, user: user, confirmed_at: Time.now
      create :email, user: user
1784 1785 1786
      user.reload

      expect(user.verified_email?(user.email)).to be_truthy
1787
      expect(user.verified_email?(email_confirmed.email.titlecase)).to be_truthy
1788 1789
    end

1790 1791 1792 1793
    it 'returns true when user is found through private commit email' do
      expect(user.verified_email?(user.private_commit_email)).to be_truthy
    end

1794 1795 1796 1797 1798 1799 1800 1801
    it 'returns true for an outdated private commit email' do
      old_email = user.private_commit_email

      user.update!(username: 'changed-username')

      expect(user.verified_email?(old_email)).to be_truthy
    end

1802 1803 1804 1805 1806 1807 1808 1809
    it 'returns false when the email is not verified/confirmed' do
      email_unconfirmed = create :email, user: user
      user.reload

      expect(user.verified_email?(email_unconfirmed.email)).to be_falsy
    end
  end

1810
  describe '#requires_ldap_check?' do
1811
    let(:user) { described_class.new }
1812

1813 1814
    it 'is false when LDAP is disabled' do
      # Create a condition which would otherwise cause 'true' to be returned
1815
      allow(user).to receive(:ldap_user?).and_return(true)
1816
      user.last_credential_check_at = nil
1817

1818
      expect(user.requires_ldap_check?).to be_falsey
1819 1820
    end

1821
    context 'when LDAP is enabled' do
1822 1823 1824
      before do
        allow(Gitlab.config.ldap).to receive(:enabled).and_return(true)
      end
1825

1826
      it 'is false for non-LDAP users' do
1827
        allow(user).to receive(:ldap_user?).and_return(false)
1828

1829
        expect(user.requires_ldap_check?).to be_falsey
1830 1831
      end

1832
      context 'and when the user is an LDAP user' do
1833 1834 1835
        before do
          allow(user).to receive(:ldap_user?).and_return(true)
        end
1836 1837 1838

        it 'is true when the user has never had an LDAP check before' do
          user.last_credential_check_at = nil
1839

1840
          expect(user.requires_ldap_check?).to be_truthy
1841 1842 1843 1844
        end

        it 'is true when the last LDAP check happened over 1 hour ago' do
          user.last_credential_check_at = 2.hours.ago
1845

1846
          expect(user.requires_ldap_check?).to be_truthy
1847
        end
1848 1849 1850 1851
      end
    end
  end

1852
  context 'ldap synchronized user' do
1853
    describe '#ldap_user?' do
1854 1855
      it 'is true if provider name starts with ldap' do
        user = create(:omniauth_user, provider: 'ldapmain')
1856

1857 1858
        expect(user.ldap_user?).to be_truthy
      end
1859

1860 1861
      it 'is false for other providers' do
        user = create(:omniauth_user, provider: 'other-provider')
1862

1863 1864 1865 1866 1867
        expect(user.ldap_user?).to be_falsey
      end

      it 'is false if no extern_uid is provided' do
        user = create(:omniauth_user, extern_uid: nil)
1868

1869 1870
        expect(user.ldap_user?).to be_falsey
      end
1871 1872
    end

1873
    describe '#ldap_identity' do
1874 1875
      it 'returns ldap identity' do
        user = create :omniauth_user
1876

1877 1878
        expect(user.ldap_identity.provider).not_to be_empty
      end
1879 1880
    end

1881 1882 1883 1884 1885
    describe '#ldap_block' do
      let(:user) { create(:omniauth_user, provider: 'ldapmain', name: 'John Smith') }

      it 'blocks user flaging the action caming from ldap' do
        user.ldap_block
1886

1887 1888 1889
        expect(user.blocked?).to be_truthy
        expect(user.ldap_blocked?).to be_truthy
      end
1890 1891 1892
    end
  end

1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
  describe '#ultraauth_user?' do
    it 'is true if provider is ultraauth' do
      user = create(:omniauth_user, provider: 'ultraauth')

      expect(user.ultraauth_user?).to be_truthy
    end

    it 'is false with othe provider' do
      user = create(:omniauth_user, provider: 'not-ultraauth')

      expect(user.ultraauth_user?).to be_falsey
    end

    it 'is false if no extern_uid is provided' do
      user = create(:omniauth_user, extern_uid: nil)

      expect(user.ldap_user?).to be_falsey
    end
  end

J
Jerome Dalbert 已提交
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
  describe '#full_website_url' do
    let(:user) { create(:user) }

    it 'begins with http if website url omits it' do
      user.website_url = 'test.com'

      expect(user.full_website_url).to eq 'http://test.com'
    end

    it 'begins with http if website url begins with http' do
      user.website_url = 'http://test.com'

      expect(user.full_website_url).to eq 'http://test.com'
    end

    it 'begins with https if website url begins with https' do
      user.website_url = 'https://test.com'

      expect(user.full_website_url).to eq 'https://test.com'
    end
  end

  describe '#short_website_url' do
    let(:user) { create(:user) }

    it 'does not begin with http if website url omits it' do
      user.website_url = 'test.com'

      expect(user.short_website_url).to eq 'test.com'
    end

    it 'does not begin with http if website url begins with http' do
      user.website_url = 'http://test.com'

      expect(user.short_website_url).to eq 'test.com'
    end

    it 'does not begin with https if website url begins with https' do
      user.website_url = 'https://test.com'
1952

J
Jerome Dalbert 已提交
1953 1954
      expect(user.short_website_url).to eq 'test.com'
    end
G
GitLab 已提交
1955
  end
C
Ciro Santilli 已提交
1956

1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
  describe '#sanitize_attrs' do
    let(:user) { build(:user, name: 'test & user', skype: 'test&user') }

    it 'encodes HTML entities in the Skype attribute' do
      expect { user.sanitize_attrs }.to change { user.skype }.to('test&amp;user')
    end

    it 'does not encode HTML entities in the name attribute' do
      expect { user.sanitize_attrs }.not_to change { user.name }
    end
  end

1969 1970
  describe '#starred?' do
    it 'determines if user starred a project' do
1971
      user = create :user
1972 1973
      project1 = create(:project, :public)
      project2 = create(:project, :public)
1974

1975 1976
      expect(user.starred?(project1)).to be_falsey
      expect(user.starred?(project2)).to be_falsey
1977 1978

      star1 = UsersStarProject.create!(project: project1, user: user)
1979

1980 1981
      expect(user.starred?(project1)).to be_truthy
      expect(user.starred?(project2)).to be_falsey
1982 1983

      star2 = UsersStarProject.create!(project: project2, user: user)
1984

1985 1986
      expect(user.starred?(project1)).to be_truthy
      expect(user.starred?(project2)).to be_truthy
1987 1988

      star1.destroy
1989

1990 1991
      expect(user.starred?(project1)).to be_falsey
      expect(user.starred?(project2)).to be_truthy
1992 1993

      star2.destroy
1994

1995 1996
      expect(user.starred?(project1)).to be_falsey
      expect(user.starred?(project2)).to be_falsey
1997 1998 1999
    end
  end

2000 2001
  describe '#toggle_star' do
    it 'toggles stars' do
C
Ciro Santilli 已提交
2002
      user = create :user
2003
      project = create(:project, :public)
C
Ciro Santilli 已提交
2004

2005
      expect(user.starred?(project)).to be_falsey
2006

C
Ciro Santilli 已提交
2007
      user.toggle_star(project)
2008

2009
      expect(user.starred?(project)).to be_truthy
2010

C
Ciro Santilli 已提交
2011
      user.toggle_star(project)
2012

2013
      expect(user.starred?(project)).to be_falsey
C
Ciro Santilli 已提交
2014 2015
    end
  end
V
Valery Sizov 已提交
2016

2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
  describe '.find_by_private_commit_email' do
    context 'with email' do
      set(:user) { create(:user) }

      it 'returns user through private commit email' do
        expect(described_class.find_by_private_commit_email(user.private_commit_email)).to eq(user)
      end

      it 'returns nil when email other than private_commit_email is used' do
        expect(described_class.find_by_private_commit_email(user.email)).to be_nil
      end
    end

    it 'returns nil when email is nil' do
      expect(described_class.find_by_private_commit_email(nil)).to be_nil
    end
  end

2035
  describe '#sort_by_attribute' do
V
Valery Sizov 已提交
2036
    before do
2037
      described_class.delete_all
2038 2039 2040
      @user = create :user, created_at: Date.today, current_sign_in_at: Date.today, name: 'Alpha'
      @user1 = create :user, created_at: Date.today - 1, current_sign_in_at: Date.today - 1, name: 'Omega'
      @user2 = create :user, created_at: Date.today - 2, name: 'Beta'
V
Valery Sizov 已提交
2041
    end
2042

2043
    context 'when sort by recent_sign_in' do
2044
      let(:users) { described_class.sort_by_attribute('recent_sign_in') }
2045 2046 2047 2048

      it 'sorts users by recent sign-in time' do
        expect(users.first).to eq(@user)
        expect(users.second).to eq(@user1)
2049 2050 2051
      end

      it 'pushes users who never signed in to the end' do
2052
        expect(users.third).to eq(@user2)
2053
      end
V
Valery Sizov 已提交
2054 2055
    end

2056
    context 'when sort by oldest_sign_in' do
2057
      let(:users) { described_class.sort_by_attribute('oldest_sign_in') }
2058

2059
      it 'sorts users by the oldest sign-in time' do
2060 2061
        expect(users.first).to eq(@user1)
        expect(users.second).to eq(@user)
2062 2063 2064
      end

      it 'pushes users who never signed in to the end' do
2065
        expect(users.third).to eq(@user2)
2066
      end
V
Valery Sizov 已提交
2067 2068
    end

2069
    it 'sorts users in descending order by their creation time' do
2070
      expect(described_class.sort_by_attribute('created_desc').first).to eq(@user)
V
Valery Sizov 已提交
2071 2072
    end

2073
    it 'sorts users in ascending order by their creation time' do
2074
      expect(described_class.sort_by_attribute('created_asc').first).to eq(@user2)
V
Valery Sizov 已提交
2075 2076
    end

2077
    it 'sorts users by id in descending order when nil is passed' do
2078
      expect(described_class.sort_by_attribute(nil).first).to eq(@user2)
V
Valery Sizov 已提交
2079 2080
    end
  end
2081

2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
  describe "#last_active_at" do
    let(:last_activity_on) { 5.days.ago.to_date }
    let(:current_sign_in_at) { 8.days.ago }

    context 'for a user that has `last_activity_on` set' do
      let(:user) { create(:user, last_activity_on: last_activity_on) }

      it 'returns `last_activity_on` with current time zone' do
        expect(user.last_active_at).to eq(last_activity_on.to_time.in_time_zone)
      end
    end

    context 'for a user that has `current_sign_in_at` set' do
      let(:user) { create(:user, current_sign_in_at: current_sign_in_at) }

      it 'returns `current_sign_in_at`' do
        expect(user.last_active_at).to eq(current_sign_in_at)
      end
    end

    context 'for a user that has both `current_sign_in_at` & ``last_activity_on`` set' do
      let(:user) { create(:user, current_sign_in_at: current_sign_in_at, last_activity_on: last_activity_on) }

      it 'returns the latest among `current_sign_in_at` & `last_activity_on`' do
        latest_event = [current_sign_in_at, last_activity_on.to_time.in_time_zone].max
        expect(user.last_active_at).to eq(latest_event)
      end
    end

    context 'for a user that does not have both `current_sign_in_at` & `last_activity_on` set' do
      let(:user) { create(:user, current_sign_in_at: nil, last_activity_on: nil) }

      it 'returns nil' do
        expect(user.last_active_at).to eq(nil)
      end
    end
  end

  describe "#can_be_deactivated?" do
    let(:activity) { {} }
    let(:user) { create(:user, name: 'John Smith', **activity) }
    let(:day_within_minium_inactive_days_threshold) { User::MINIMUM_INACTIVE_DAYS.pred.days.ago }
    let(:day_outside_minium_inactive_days_threshold) { User::MINIMUM_INACTIVE_DAYS.next.days.ago }

    shared_examples 'not eligible for deactivation' do
      it 'returns false' do
        expect(user.can_be_deactivated?).to be_falsey
      end
    end

    shared_examples 'eligible for deactivation' do
      it 'returns true' do
        expect(user.can_be_deactivated?).to be_truthy
      end
    end

    context "a user who is not active" do
      before do
        user.block
      end

      it_behaves_like 'not eligible for deactivation'
    end

    context 'a user who has activity within the specified minimum inactive days' do
      let(:activity) { { last_activity_on: day_within_minium_inactive_days_threshold } }

      it_behaves_like 'not eligible for deactivation'
    end

    context 'a user who has signed in within the specified minimum inactive days' do
      let(:activity) { { current_sign_in_at: day_within_minium_inactive_days_threshold } }

      it_behaves_like 'not eligible for deactivation'
    end

    context 'a user who has no activity within the specified minimum inactive days' do
      let(:activity) { { last_activity_on: day_outside_minium_inactive_days_threshold } }

      it_behaves_like 'eligible for deactivation'
    end

    context 'a user who has not signed in within the specified minimum inactive days' do
      let(:activity) { { current_sign_in_at: day_outside_minium_inactive_days_threshold } }

      it_behaves_like 'eligible for deactivation'
    end
  end

2171
  describe "#contributed_projects" do
2172
    subject { create(:user) }
2173
    let!(:project1) { create(:project) }
B
Bob Van Landuyt 已提交
2174
    let!(:project2) { fork_project(project3) }
2175
    let!(:project3) { create(:project) }
2176
    let!(:merge_request) { create(:merge_request, source_project: project2, target_project: project3, author: subject) }
2177
    let!(:push_event) { create(:push_event, project: project1, author: subject) }
2178
    let!(:merge_event) { create(:event, :created, project: project3, target: merge_request, author: subject) }
2179 2180

    before do
2181 2182
      project1.add_maintainer(subject)
      project2.add_maintainer(subject)
2183 2184 2185
    end

    it "includes IDs for projects the user has pushed to" do
2186
      expect(subject.contributed_projects).to include(project1)
2187 2188 2189
    end

    it "includes IDs for projects the user has had merge requests merged into" do
2190
      expect(subject.contributed_projects).to include(project3)
2191 2192 2193
    end

    it "doesn't include IDs for unrelated projects" do
2194
      expect(subject.contributed_projects).not_to include(project2)
2195 2196
    end
  end
2197

2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
  describe '#fork_of' do
    let(:user) { create(:user) }

    it "returns a user's fork of a project" do
      project = create(:project, :public)
      user_fork = fork_project(project, user, namespace: user.namespace)

      expect(user.fork_of(project)).to eq(user_fork)
    end

    it 'returns nil if the project does not have a fork network' do
      project = create(:project)

      expect(user.fork_of(project)).to be_nil
    end
  end

2215
  describe '#can_be_removed?' do
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
    subject { create(:user) }

    context 'no owned groups' do
      it { expect(subject.can_be_removed?).to be_truthy }
    end

    context 'has owned groups' do
      before do
        group = create(:group)
        group.add_owner(subject)
      end

      it { expect(subject.can_be_removed?).to be_falsey }
    end
  end
2231 2232

  describe "#recent_push" do
2233 2234 2235
    let(:user) { build(:user) }
    let(:project) { build(:project) }
    let(:event) { build(:push_event) }
2236

2237 2238 2239 2240
    it 'returns the last push event for the user' do
      expect_any_instance_of(Users::LastPushEventService)
        .to receive(:last_event_for_user)
        .and_return(event)
2241

2242
      expect(user.recent_push).to eq(event)
2243 2244
    end

2245 2246 2247 2248
    it 'returns the last push event for a project when one is given' do
      expect_any_instance_of(Users::LastPushEventService)
        .to receive(:last_event_for_project)
        .and_return(event)
2249

2250
      expect(user.recent_push(project)).to eq(event)
2251
    end
2252
  end
2253 2254 2255 2256

  describe '#authorized_groups' do
    let!(:user) { create(:user) }
    let!(:private_group) { create(:group) }
2257 2258 2259 2260
    let!(:child_group) { create(:group, parent: private_group) }

    let!(:project_group) { create(:group) }
    let!(:project) { create(:project, group: project_group) }
2261 2262

    before do
2263 2264
      private_group.add_user(user, Gitlab::Access::MAINTAINER)
      project.add_maintainer(user)
2265 2266
    end

2267
    subject { user.authorized_groups }
2268

2269 2270 2271 2272 2273 2274 2275 2276 2277
    it { is_expected.to contain_exactly private_group, project_group }
  end

  describe '#membership_groups' do
    let!(:user) { create(:user) }
    let!(:parent_group) { create(:group) }
    let!(:child_group) { create(:group, parent: parent_group) }

    before do
2278
      parent_group.add_user(user, Gitlab::Access::MAINTAINER)
2279 2280 2281 2282
    end

    subject { user.membership_groups }

2283
    it { is_expected.to contain_exactly parent_group, child_group }
2284 2285
  end

2286 2287 2288 2289 2290 2291
  describe '#authorizations_for_projects' do
    let!(:user) { create(:user) }
    subject { Project.where("EXISTS (?)", user.authorizations_for_projects) }

    it 'includes projects that belong to a user, but no other projects' do
      owned = create(:project, :private, namespace: user.namespace)
2292
      member = create(:project, :private).tap { |p| p.add_maintainer(user) }
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
      other = create(:project)

      expect(subject).to include(owned)
      expect(subject).to include(member)
      expect(subject).not_to include(other)
    end

    it 'includes projects a user has access to, but no other projects' do
      other_user = create(:user)
      accessible = create(:project, :private, namespace: other_user.namespace) do |project|
        project.add_developer(user)
      end
      other = create(:project)

      expect(subject).to include(accessible)
      expect(subject).not_to include(other)
    end
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336

    context 'with min_access_level' do
      let!(:user) { create(:user) }
      let!(:project) { create(:project, :private, namespace: user.namespace) }

      before do
        project.add_developer(user)
      end

      subject { Project.where("EXISTS (?)", user.authorizations_for_projects(min_access_level: min_access_level)) }

      context 'when developer access' do
        let(:min_access_level) { Gitlab::Access::DEVELOPER }

        it 'includes projects a user has access to' do
          expect(subject).to include(project)
        end
      end

      context 'when owner access' do
        let(:min_access_level) { Gitlab::Access::OWNER }

        it 'does not include projects with higher access level' do
          expect(subject).not_to include(project)
        end
      end
    end
2337 2338
  end

2339
  describe '#authorized_projects', :delete do
2340 2341 2342
    context 'with a minimum access level' do
      it 'includes projects for which the user is an owner' do
        user = create(:user)
2343
        project = create(:project, :private, namespace: user.namespace)
2344

D
Douwe Maan 已提交
2345 2346
        expect(user.authorized_projects(Gitlab::Access::REPORTER))
          .to contain_exactly(project)
2347
      end
2348

2349
      it 'includes projects for which the user is a maintainer' do
2350
        user = create(:user)
2351
        project = create(:project, :private)
2352

2353
        project.add_maintainer(user)
2354

D
Douwe Maan 已提交
2355 2356
        expect(user.authorized_projects(Gitlab::Access::REPORTER))
          .to contain_exactly(project)
2357 2358
      end
    end
2359 2360 2361

    it "includes user's personal projects" do
      user    = create(:user)
2362
      project = create(:project, :private, namespace: user.namespace)
2363 2364 2365 2366 2367 2368 2369

      expect(user.authorized_projects).to include(project)
    end

    it "includes personal projects user has been given access to" do
      user1   = create(:user)
      user2   = create(:user)
2370
      project = create(:project, :private, namespace: user1.namespace)
2371

2372
      project.add_developer(user2)
2373 2374 2375 2376 2377 2378

      expect(user2.authorized_projects).to include(project)
    end

    it "includes projects of groups user has been added to" do
      group   = create(:group)
2379
      project = create(:project, group: group)
2380 2381 2382 2383 2384 2385 2386 2387 2388
      user    = create(:user)

      group.add_developer(user)

      expect(user.authorized_projects).to include(project)
    end

    it "does not include projects of groups user has been removed from" do
      group   = create(:group)
2389
      project = create(:project, group: group)
2390 2391 2392
      user    = create(:user)

      member = group.add_developer(user)
2393

2394 2395 2396
      expect(user.authorized_projects).to include(project)

      member.destroy
2397

2398 2399 2400 2401 2402
      expect(user.authorized_projects).not_to include(project)
    end

    it "includes projects shared with user's group" do
      user    = create(:user)
2403
      project = create(:project, :private)
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
      group   = create(:group)

      group.add_reporter(user)
      project.project_group_links.create(group: group)

      expect(user.authorized_projects).to include(project)
    end

    it "does not include destroyed projects user had access to" do
      user1   = create(:user)
      user2   = create(:user)
2415
      project = create(:project, :private, namespace: user1.namespace)
2416

2417
      project.add_developer(user2)
2418

2419 2420 2421
      expect(user2.authorized_projects).to include(project)

      project.destroy
2422

2423 2424 2425 2426 2427
      expect(user2.authorized_projects).not_to include(project)
    end

    it "does not include projects of destroyed groups user had access to" do
      group   = create(:group)
2428
      project = create(:project, namespace: group)
2429 2430 2431
      user    = create(:user)

      group.add_developer(user)
2432

2433 2434 2435
      expect(user.authorized_projects).to include(project)

      group.destroy
2436

2437 2438
      expect(user.authorized_projects).not_to include(project)
    end
2439
  end
2440

2441 2442 2443 2444
  describe '#projects_where_can_admin_issues' do
    let(:user) { create(:user) }

    it 'includes projects for which the user access level is above or equal to reporter' do
2445 2446
      reporter_project  = create(:project) { |p| p.add_reporter(user) }
      developer_project = create(:project) { |p| p.add_developer(user) }
2447
      maintainer_project = create(:project) { |p| p.add_maintainer(user) }
2448

2449 2450
      expect(user.projects_where_can_admin_issues.to_a).to match_array([maintainer_project, developer_project, reporter_project])
      expect(user.can?(:admin_issue, maintainer_project)).to eq(true)
2451 2452 2453 2454 2455
      expect(user.can?(:admin_issue, developer_project)).to eq(true)
      expect(user.can?(:admin_issue, reporter_project)).to eq(true)
    end

    it 'does not include for which the user access level is below reporter' do
2456 2457
      project = create(:project)
      guest_project = create(:project) { |p| p.add_guest(user) }
2458 2459 2460 2461 2462 2463 2464

      expect(user.projects_where_can_admin_issues.to_a).to be_empty
      expect(user.can?(:admin_issue, guest_project)).to eq(false)
      expect(user.can?(:admin_issue, project)).to eq(false)
    end

    it 'does not include archived projects' do
2465
      project = create(:project, :archived)
2466 2467 2468 2469 2470 2471

      expect(user.projects_where_can_admin_issues.to_a).to be_empty
      expect(user.can?(:admin_issue, project)).to eq(false)
    end

    it 'does not include projects for which issues are disabled' do
2472
      project = create(:project, :issues_disabled)
2473 2474 2475 2476 2477 2478

      expect(user.projects_where_can_admin_issues.to_a).to be_empty
      expect(user.can?(:admin_issue, project)).to eq(false)
    end
  end

2479
  describe '#ci_owned_runners' do
2480
    let(:user) { create(:user) }
2481
    let!(:project) { create(:project) }
2482
    let(:runner) { create(:ci_runner, :project, projects: [project]) }
2483

2484
    context 'without any projects nor groups' do
2485
      it 'does not load' do
2486
        expect(user.ci_owned_runners).to be_empty
2487 2488 2489 2490 2491
      end
    end

    context 'with personal projects runners' do
      let(:namespace) { create(:namespace, owner: user) }
2492
      let!(:project) { create(:project, namespace: namespace) }
2493 2494

      it 'loads' do
2495
        expect(user.ci_owned_runners).to contain_exactly(runner)
2496 2497 2498 2499
      end
    end

    context 'with personal group runner' do
2500 2501
      let!(:project) { create(:project) }
      let(:group_runner) { create(:ci_runner, :group, groups: [group]) }
2502
      let!(:group) do
2503
        create(:group).tap do |group|
2504 2505 2506 2507 2508
          group.add_owner(user)
        end
      end

      it 'loads' do
2509
        expect(user.ci_owned_runners).to contain_exactly(group_runner)
2510 2511 2512 2513 2514
      end
    end

    context 'with personal project and group runner' do
      let(:namespace) { create(:namespace, owner: user) }
2515 2516
      let!(:project) { create(:project, namespace: namespace) }
      let!(:group_runner) { create(:ci_runner, :group, groups: [group]) }
2517 2518

      let!(:group) do
2519
        create(:group).tap do |group|
2520 2521 2522 2523 2524
          group.add_owner(user)
        end
      end

      it 'loads' do
2525
        expect(user.ci_owned_runners).to contain_exactly(runner, group_runner)
2526 2527 2528 2529
      end
    end

    shared_examples :member do
2530
      context 'when the user is a maintainer' do
2531
        before do
2532
          add_user(:maintainer)
2533
        end
2534

2535
        it 'loads' do
2536
          expect(user.ci_owned_runners).to contain_exactly(runner)
2537
        end
2538 2539
      end

2540
      context 'when the user is a developer' do
2541
        before do
2542
          add_user(:developer)
2543
        end
2544

2545
        it 'does not load' do
2546
          expect(user.ci_owned_runners).to be_empty
2547
        end
2548 2549 2550 2551 2552
      end
    end

    context 'with groups projects runners' do
      let(:group) { create(:group) }
2553
      let!(:project) { create(:project, group: group) }
2554 2555 2556 2557 2558 2559 2560 2561 2562

      def add_user(access)
        group.add_user(user, access)
      end

      it_behaves_like :member
    end

    context 'with groups runners' do
2563 2564
      let!(:runner) { create(:ci_runner, :group, groups: [group]) }
      let!(:group) { create(:group) }
2565

L
Lin Jen-Shin 已提交
2566
      def add_user(access)
2567 2568 2569 2570 2571 2572 2573
        group.add_user(user, access)
      end

      it_behaves_like :member
    end

    context 'with other projects runners' do
2574
      let!(:project) { create(:project) }
2575

L
Lin Jen-Shin 已提交
2576
      def add_user(access)
2577
        project.add_role(user, access)
2578 2579 2580 2581
      end

      it_behaves_like :member
    end
2582

2583
    context 'with subgroup with different owner for project runner' do
2584 2585 2586
      let(:group) { create(:group) }
      let(:another_user) { create(:user) }
      let(:subgroup) { create(:group, parent: group) }
2587
      let!(:project) { create(:project, group: subgroup) }
2588 2589 2590 2591 2592 2593 2594 2595 2596

      def add_user(access)
        group.add_user(user, access)
        group.add_user(another_user, :owner)
        subgroup.add_user(another_user, :owner)
      end

      it_behaves_like :member
    end
2597 2598
  end

2599
  describe '#projects_with_reporter_access_limited_to' do
2600 2601
    let(:project1) { create(:project) }
    let(:project2) { create(:project) }
2602 2603 2604
    let(:user) { create(:user) }

    before do
2605 2606
      project1.add_reporter(user)
      project2.add_guest(user)
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
    end

    it 'returns the projects when using a single project ID' do
      projects = user.projects_with_reporter_access_limited_to(project1.id)

      expect(projects).to eq([project1])
    end

    it 'returns the projects when using an Array of project IDs' do
      projects = user.projects_with_reporter_access_limited_to([project1.id])

      expect(projects).to eq([project1])
    end

    it 'returns the projects when using an ActiveRecord relation' do
2622 2623
      projects = user
        .projects_with_reporter_access_limited_to(Project.select(:id))
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633

      expect(projects).to eq([project1])
    end

    it 'does not return projects you do not have reporter access to' do
      projects = user.projects_with_reporter_access_limited_to(project2.id)

      expect(projects).to be_empty
    end
  end
2634

2635 2636
  describe '#all_expanded_groups' do
    # foo/bar would also match foo/barbaz instead of just foo/bar and foo/bar/baz
2637 2638
    let!(:user) { create(:user) }

2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
    #                group
    #        _______ (foo) _______
    #       |                     |
    #       |                     |
    # nested_group_1        nested_group_2
    # (bar)                 (barbaz)
    #       |                     |
    #       |                     |
    # nested_group_1_1      nested_group_2_1
    # (baz)                 (baz)
    #
    let!(:group) { create :group }
    let!(:nested_group_1) { create :group, parent: group, name: 'bar' }
    let!(:nested_group_1_1) { create :group, parent: nested_group_1, name: 'baz' }
    let!(:nested_group_2) { create :group, parent: group, name: 'barbaz' }
    let!(:nested_group_2_1) { create :group, parent: nested_group_2, name: 'baz' }
2655

2656 2657 2658 2659 2660 2661
    subject { user.all_expanded_groups }

    context 'user is not a member of any group' do
      it 'returns an empty array' do
        is_expected.to eq([])
      end
2662 2663
    end

2664 2665
    context 'user is member of all groups' do
      before do
2666 2667 2668 2669 2670
        group.add_reporter(user)
        nested_group_1.add_developer(user)
        nested_group_1_1.add_maintainer(user)
        nested_group_2.add_developer(user)
        nested_group_2_1.add_maintainer(user)
2671
      end
2672

2673 2674 2675 2676 2677 2678 2679 2680
      it 'returns all groups' do
        is_expected.to match_array [
          group,
          nested_group_1, nested_group_1_1,
          nested_group_2, nested_group_2_1
        ]
      end
    end
2681

2682
    context 'user is member of the top group' do
2683 2684 2685
      before do
        group.add_owner(user)
      end
2686

2687 2688 2689 2690 2691 2692
      it 'returns all groups' do
        is_expected.to match_array [
          group,
          nested_group_1, nested_group_1_1,
          nested_group_2, nested_group_2_1
        ]
2693 2694
      end
    end
2695

2696
    context 'user is member of the first child (internal node), branch 1' do
2697 2698 2699
      before do
        nested_group_1.add_owner(user)
      end
2700

2701 2702 2703 2704 2705 2706 2707 2708
      it 'returns the groups in the hierarchy' do
        is_expected.to match_array [
          group,
          nested_group_1, nested_group_1_1
        ]
      end
    end

2709
    context 'user is member of the first child (internal node), branch 2' do
2710 2711 2712
      before do
        nested_group_2.add_owner(user)
      end
2713

2714 2715 2716 2717 2718 2719
      it 'returns the groups in the hierarchy' do
        is_expected.to match_array [
          group,
          nested_group_2, nested_group_2_1
        ]
      end
2720 2721
    end

2722
    context 'user is member of the last child (leaf node)' do
2723 2724 2725
      before do
        nested_group_1_1.add_owner(user)
      end
2726 2727 2728 2729 2730 2731 2732 2733

      it 'returns the groups in the hierarchy' do
        is_expected.to match_array [
          group,
          nested_group_1, nested_group_1_1
        ]
      end
    end
2734 2735
  end

2736
  describe '#refresh_authorized_projects', :clean_gitlab_redis_shared_state do
2737 2738
    let(:project1) { create(:project) }
    let(:project2) { create(:project) }
2739 2740 2741
    let(:user) { create(:user) }

    before do
2742 2743
      project1.add_reporter(user)
      project2.add_guest(user)
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757

      user.project_authorizations.delete_all
      user.refresh_authorized_projects
    end

    it 'refreshes the list of authorized projects' do
      expect(user.project_authorizations.count).to eq(2)
    end

    it 'stores the correct access levels' do
      expect(user.project_authorizations.where(access_level: Gitlab::Access::GUEST).exists?).to eq(true)
      expect(user.project_authorizations.where(access_level: Gitlab::Access::REPORTER).exists?).to eq(true)
    end
  end
D
Douwe Maan 已提交
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790

  describe '#access_level=' do
    let(:user) { build(:user) }

    it 'does nothing for an invalid access level' do
      user.access_level = :invalid_access_level

      expect(user.access_level).to eq(:regular)
      expect(user.admin).to be false
    end

    it "assigns the 'admin' access level" do
      user.access_level = :admin

      expect(user.access_level).to eq(:admin)
      expect(user.admin).to be true
    end

    it "doesn't clear existing access levels when an invalid access level is passed in" do
      user.access_level = :admin
      user.access_level = :invalid_access_level

      expect(user.access_level).to eq(:admin)
      expect(user.admin).to be true
    end

    it "accepts string values in addition to symbols" do
      user.access_level = 'admin'

      expect(user.access_level).to eq(:admin)
      expect(user.admin).to be true
    end
  end
2791

2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
  describe '#full_private_access?' do
    it 'returns false for regular user' do
      user = build(:user)

      expect(user.full_private_access?).to be_falsy
    end

    it 'returns true for admin user' do
      user = build(:user, :admin)

      expect(user.full_private_access?).to be_truthy
    end
  end

2806 2807
  describe '.ghost' do
    it "creates a ghost user if one isn't already present" do
2808
      ghost = described_class.ghost
2809 2810 2811

      expect(ghost).to be_ghost
      expect(ghost).to be_persisted
2812 2813
      expect(ghost.namespace).not_to be_nil
      expect(ghost.namespace).to be_persisted
2814 2815 2816 2817
    end

    it "does not create a second ghost user if one is already present" do
      expect do
2818 2819 2820 2821
        described_class.ghost
        described_class.ghost
      end.to change { described_class.count }.by(1)
      expect(described_class.ghost).to eq(described_class.ghost)
2822 2823 2824 2825 2826
    end

    context "when a regular user exists with the username 'ghost'" do
      it "creates a ghost user with a non-conflicting username" do
        create(:user, username: 'ghost')
2827
        ghost = described_class.ghost
2828 2829

        expect(ghost).to be_persisted
2830
        expect(ghost.username).to eq('ghost1')
2831 2832 2833 2834 2835 2836
      end
    end

    context "when a regular user exists with the email 'ghost@example.com'" do
      it "creates a ghost user with a non-conflicting email" do
        create(:user, email: 'ghost@example.com')
2837
        ghost = described_class.ghost
2838 2839

        expect(ghost).to be_persisted
2840
        expect(ghost.email).to eq('ghost1@example.com')
2841 2842
      end
    end
2843 2844 2845 2846 2847 2848 2849

    context 'when a domain whitelist is in place' do
      before do
        stub_application_setting(domain_whitelist: ['gitlab.com'])
      end

      it 'creates a ghost user' do
2850
        expect(described_class.ghost).to be_persisted
2851 2852
      end
    end
2853
  end
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869

  describe '#update_two_factor_requirement' do
    let(:user) { create :user }

    context 'with 2FA requirement on groups' do
      let(:group1) { create :group, require_two_factor_authentication: true, two_factor_grace_period: 23 }
      let(:group2) { create :group, require_two_factor_authentication: true, two_factor_grace_period: 32 }

      before do
        group1.add_user(user, GroupMember::OWNER)
        group2.add_user(user, GroupMember::OWNER)

        user.update_two_factor_requirement
      end

      it 'requires 2FA' do
2870
        expect(user.require_two_factor_authentication_from_group).to be true
2871 2872 2873 2874 2875 2876 2877
      end

      it 'uses the shortest grace period' do
        expect(user.two_factor_grace_period).to be 23
      end
    end

2878
    context 'with 2FA requirement from expanded groups' do
2879
      let!(:group1) { create :group, require_two_factor_authentication: true }
2880
      let!(:group1a) { create :group, parent: group1 }
2881 2882 2883 2884 2885 2886 2887 2888

      before do
        group1a.add_user(user, GroupMember::OWNER)

        user.update_two_factor_requirement
      end

      it 'requires 2FA' do
2889
        expect(user.require_two_factor_authentication_from_group).to be true
2890 2891 2892
      end
    end

2893
    context 'with 2FA requirement on nested child group' do
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
      let!(:group1) { create :group, require_two_factor_authentication: false }
      let!(:group1a) { create :group, require_two_factor_authentication: true, parent: group1 }

      before do
        group1.add_user(user, GroupMember::OWNER)

        user.update_two_factor_requirement
      end

      it 'requires 2FA' do
2904
        expect(user.require_two_factor_authentication_from_group).to be true
2905 2906 2907
      end
    end

2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
    context "with 2FA requirement from shared project's group" do
      let!(:group1) { create :group, require_two_factor_authentication: true }
      let!(:group2) { create :group }
      let(:shared_project) { create(:project, namespace: group1) }

      before do
        shared_project.project_group_links.create!(
          group: group2,
          group_access: ProjectGroupLink.default_access
        )

        group2.add_user(user, GroupMember::OWNER)
      end

      it 'does not require 2FA' do
        user.update_two_factor_requirement

        expect(user.require_two_factor_authentication_from_group).to be false
      end
    end

2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
    context 'without 2FA requirement on groups' do
      let(:group) { create :group }

      before do
        group.add_user(user, GroupMember::OWNER)

        user.update_two_factor_requirement
      end

      it 'does not require 2FA' do
2939
        expect(user.require_two_factor_authentication_from_group).to be false
2940 2941 2942 2943 2944 2945 2946
      end

      it 'falls back to the default grace period' do
        expect(user.two_factor_grace_period).to be 48
      end
    end
  end
J
James Lopez 已提交
2947 2948 2949

  context '.active' do
    before do
2950
      described_class.ghost
J
James Lopez 已提交
2951 2952 2953 2954 2955
      create(:user, name: 'user', state: 'active')
      create(:user, name: 'user', state: 'blocked')
    end

    it 'only counts active and non internal users' do
2956
      expect(described_class.active.count).to eq(1)
J
James Lopez 已提交
2957 2958
    end
  end
2959 2960 2961 2962 2963 2964 2965 2966

  describe 'preferred language' do
    it 'is English by default' do
      user = create(:user)

      expect(user.preferred_language).to eq('en')
    end
  end
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994

  context '#invalidate_issue_cache_counts' do
    let(:user) { build_stubbed(:user) }

    it 'invalidates cache for issue counter' do
      cache_mock = double

      expect(cache_mock).to receive(:delete).with(['users', user.id, 'assigned_open_issues_count'])

      allow(Rails).to receive(:cache).and_return(cache_mock)

      user.invalidate_issue_cache_counts
    end
  end

  context '#invalidate_merge_request_cache_counts' do
    let(:user) { build_stubbed(:user) }

    it 'invalidates cache for Merge Request counter' do
      cache_mock = double

      expect(cache_mock).to receive(:delete).with(['users', user.id, 'assigned_open_merge_requests_count'])

      allow(Rails).to receive(:cache).and_return(cache_mock)

      user.invalidate_merge_request_cache_counts
    end
  end
2995

A
Andreas Brandl 已提交
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
  context '#invalidate_personal_projects_count' do
    let(:user) { build_stubbed(:user) }

    it 'invalidates cache for personal projects counter' do
      cache_mock = double

      expect(cache_mock).to receive(:delete).with(['users', user.id, 'personal_projects_count'])

      allow(Rails).to receive(:cache).and_return(cache_mock)

      user.invalidate_personal_projects_count
    end
  end

3010
  describe '#allow_password_authentication_for_web?' do
3011 3012 3013
    context 'regular user' do
      let(:user) { build(:user) }

3014 3015
      it 'returns true when password authentication is enabled for the web interface' do
        expect(user.allow_password_authentication_for_web?).to be_truthy
3016 3017
      end

3018 3019
      it 'returns false when password authentication is disabled for the web interface' do
        stub_application_setting(password_authentication_enabled_for_web: false)
3020

3021
        expect(user.allow_password_authentication_for_web?).to be_falsey
3022 3023 3024 3025 3026 3027
      end
    end

    it 'returns false for ldap user' do
      user = create(:omniauth_user, provider: 'ldapmain')

3028 3029
      expect(user.allow_password_authentication_for_web?).to be_falsey
    end
3030 3031 3032 3033 3034 3035

    it 'returns false for ultraauth user' do
      user = create(:omniauth_user, provider: 'ultraauth')

      expect(user.allow_password_authentication_for_web?).to be_falsey
    end
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
  end

  describe '#allow_password_authentication_for_git?' do
    context 'regular user' do
      let(:user) { build(:user) }

      it 'returns true when password authentication is enabled for Git' do
        expect(user.allow_password_authentication_for_git?).to be_truthy
      end

      it 'returns false when password authentication is disabled Git' do
        stub_application_setting(password_authentication_enabled_for_git: false)

        expect(user.allow_password_authentication_for_git?).to be_falsey
      end
    end

    it 'returns false for ldap user' do
      user = create(:omniauth_user, provider: 'ldapmain')

      expect(user.allow_password_authentication_for_git?).to be_falsey
3057
    end
3058 3059 3060 3061 3062 3063

    it 'returns false for ultraauth user' do
      user = create(:omniauth_user, provider: 'ultraauth')

      expect(user.allow_password_authentication_for_git?).to be_falsey
    end
3064
  end
3065

3066 3067 3068 3069 3070 3071
  describe '#assigned_open_merge_requests_count' do
    it 'returns number of open merge requests from non-archived projects' do
      user    = create(:user)
      project = create(:project, :public)
      archived_project = create(:project, :public, :archived)

3072 3073 3074
      create(:merge_request, source_project: project, author: user, assignees: [user])
      create(:merge_request, :closed, source_project: project, author: user, assignees: [user])
      create(:merge_request, source_project: archived_project, author: user, assignees: [user])
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093

      expect(user.assigned_open_merge_requests_count(force: true)).to eq 1
    end
  end

  describe '#assigned_open_issues_count' do
    it 'returns number of open issues from non-archived projects' do
      user    = create(:user)
      project = create(:project, :public)
      archived_project = create(:project, :public, :archived)

      create(:issue, project: project, author: user, assignees: [user])
      create(:issue, :closed, project: project, author: user, assignees: [user])
      create(:issue, project: archived_project, author: user, assignees: [user])

      expect(user.assigned_open_issues_count(force: true)).to eq 1
    end
  end

3094 3095 3096 3097 3098
  describe '#personal_projects_count' do
    it 'returns the number of personal projects using a single query' do
      user = build(:user)
      projects = double(:projects, count: 1)

A
Andreas Brandl 已提交
3099
      expect(user).to receive(:personal_projects).and_return(projects)
3100

A
Andreas Brandl 已提交
3101
      expect(user.personal_projects_count).to eq(1)
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
    end
  end

  describe '#projects_limit_left' do
    it 'returns the number of projects that can be created by the user' do
      user = build(:user)

      allow(user).to receive(:projects_limit).and_return(10)
      allow(user).to receive(:personal_projects_count).and_return(5)

      expect(user.projects_limit_left).to eq(5)
    end
  end
3115 3116 3117 3118 3119 3120 3121

  describe '#ensure_namespace_correct' do
    context 'for a new user' do
      let(:user) { build(:user) }

      it 'creates the namespace' do
        expect(user.namespace).to be_nil
3122

3123
        user.save!
3124

3125 3126 3127 3128 3129 3130 3131 3132 3133
        expect(user.namespace).not_to be_nil
      end
    end

    context 'for an existing user' do
      let(:username) { 'foo' }
      let(:user) { create(:user, username: username) }

      context 'when the user is updated' do
3134
        context 'when the username or name is changed' do
3135 3136 3137 3138
          let(:new_username) { 'bar' }

          it 'changes the namespace (just to compare to when username is not changed)' do
            expect do
3139
              Timecop.freeze(1.second.from_now) do
S
Sean McGivern 已提交
3140
                user.update!(username: new_username)
3141
              end
3142 3143 3144
            end.to change { user.namespace.updated_at }
          end

3145
          it 'updates the namespace path when the username was changed' do
L
Lin Jen-Shin 已提交
3146
            user.update!(username: new_username)
3147

3148
            expect(user.namespace.path).to eq(new_username)
3149 3150
          end

3151 3152
          it 'updates the namespace name if the name was changed' do
            user.update!(name: 'New name')
3153

3154 3155 3156 3157 3158 3159 3160 3161 3162
            expect(user.namespace.name).to eq('New name')
          end

          it 'updates nested routes for the namespace if the name was changed' do
            project = create(:project, namespace: user.namespace)

            user.update!(name: 'New name')

            expect(project.route.reload.name).to include('New name')
3163 3164 3165
          end

          context 'when there is a validation error (namespace name taken) while updating namespace' do
3166
            let!(:conflicting_namespace) { create(:group, path: new_username) }
3167

3168
            it 'causes the user save to fail' do
L
Lin Jen-Shin 已提交
3169
              expect(user.update(username: new_username)).to be_falsey
3170
              expect(user.namespace.errors.messages[:path].first).to eq('has already been taken')
3171
            end
3172 3173

            it 'adds the namespace errors to the user' do
L
Lin Jen-Shin 已提交
3174
              user.update(username: new_username)
3175

3176
              expect(user.errors.full_messages.first).to eq('Username has already been taken')
3177
            end
3178 3179 3180 3181 3182 3183
          end
        end

        context 'when the username is not changed' do
          it 'does not change the namespace' do
            expect do
L
Lin Jen-Shin 已提交
3184
              user.update!(email: 'asdf@asdf.com')
3185 3186 3187 3188 3189 3190
            end.not_to change { user.namespace.updated_at }
          end
        end
      end
    end
  end
A
Alexis Reigel 已提交
3191

3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
  describe '#username_changed_hook' do
    context 'for a new user' do
      let(:user) { build(:user) }

      it 'does not trigger system hook' do
        expect(user).not_to receive(:system_hook_service)

        user.save!
      end
    end

    context 'for an existing user' do
      let(:user) { create(:user, username: 'old-username') }

      context 'when the username is changed' do
        let(:new_username) { 'very-new-name' }

        it 'triggers the rename system hook' do
          system_hook_service = SystemHooksService.new
          expect(system_hook_service).to receive(:execute_hooks_for).with(user, :rename)
          expect(user).to receive(:system_hook_service).and_return(system_hook_service)

L
Lin Jen-Shin 已提交
3214
          user.update!(username: new_username)
3215 3216 3217 3218 3219 3220 3221
        end
      end

      context 'when the username is not changed' do
        it 'does not trigger system hook' do
          expect(user).not_to receive(:system_hook_service)

L
Lin Jen-Shin 已提交
3222
          user.update!(email: 'asdf@asdf.com')
3223 3224 3225 3226 3227
        end
      end
    end
  end

3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
  describe '#will_save_change_to_login?' do
    let(:user) { create(:user, username: 'old-username', email: 'old-email@example.org') }
    let(:new_username) { 'new-name' }
    let(:new_email) { 'new-email@example.org' }

    subject { user.will_save_change_to_login? }

    context 'when the username is changed' do
      before do
        user.username = new_username
      end

      it { is_expected.to be true }
    end

    context 'when the email is changed' do
      before do
        user.email = new_email
      end

      it { is_expected.to be true }
    end

    context 'when both email and username are changed' do
      before do
        user.username = new_username
        user.email = new_email
      end

      it { is_expected.to be true }
    end

    context 'when email and username aren\'t changed' do
      before do
        user.name = 'new_name'
      end

      it { is_expected.to be_falsy }
    end
  end

3269 3270 3271 3272 3273 3274
  describe '#sync_attribute?' do
    let(:user) { described_class.new }

    context 'oauth user' do
      it 'returns true if name can be synced' do
        stub_omniauth_setting(sync_profile_attributes: %w(name location))
3275

3276 3277 3278 3279 3280
        expect(user.sync_attribute?(:name)).to be_truthy
      end

      it 'returns true if email can be synced' do
        stub_omniauth_setting(sync_profile_attributes: %w(name email))
3281

3282 3283 3284 3285 3286
        expect(user.sync_attribute?(:email)).to be_truthy
      end

      it 'returns true if location can be synced' do
        stub_omniauth_setting(sync_profile_attributes: %w(location email))
3287

3288 3289 3290 3291 3292
        expect(user.sync_attribute?(:email)).to be_truthy
      end

      it 'returns false if name can not be synced' do
        stub_omniauth_setting(sync_profile_attributes: %w(location email))
3293

3294 3295 3296 3297 3298
        expect(user.sync_attribute?(:name)).to be_falsey
      end

      it 'returns false if email can not be synced' do
        stub_omniauth_setting(sync_profile_attributes: %w(location email))
3299

3300 3301 3302 3303 3304
        expect(user.sync_attribute?(:name)).to be_falsey
      end

      it 'returns false if location can not be synced' do
        stub_omniauth_setting(sync_profile_attributes: %w(location email))
3305

3306 3307 3308 3309 3310
        expect(user.sync_attribute?(:name)).to be_falsey
      end

      it 'returns true for all syncable attributes if all syncable attributes can be synced' do
        stub_omniauth_setting(sync_profile_attributes: true)
3311

3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326
        expect(user.sync_attribute?(:name)).to be_truthy
        expect(user.sync_attribute?(:email)).to be_truthy
        expect(user.sync_attribute?(:location)).to be_truthy
      end

      it 'returns false for all syncable attributes but email if no syncable attributes are declared' do
        expect(user.sync_attribute?(:name)).to be_falsey
        expect(user.sync_attribute?(:email)).to be_truthy
        expect(user.sync_attribute?(:location)).to be_falsey
      end
    end

    context 'ldap user' do
      it 'returns true for email if ldap user' do
        allow(user).to receive(:ldap_user?).and_return(true)
3327

3328 3329 3330 3331 3332 3333 3334 3335
        expect(user.sync_attribute?(:name)).to be_falsey
        expect(user.sync_attribute?(:email)).to be_truthy
        expect(user.sync_attribute?(:location)).to be_falsey
      end

      it 'returns true for email and location if ldap user and location declared as syncable' do
        allow(user).to receive(:ldap_user?).and_return(true)
        stub_omniauth_setting(sync_profile_attributes: %w(location))
3336

3337 3338 3339 3340 3341 3342
        expect(user.sync_attribute?(:name)).to be_falsey
        expect(user.sync_attribute?(:email)).to be_truthy
        expect(user.sync_attribute?(:location)).to be_truthy
      end
    end
  end
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358

  describe '#confirm_deletion_with_password?' do
    where(
      password_automatically_set: [true, false],
      ldap_user: [true, false],
      password_authentication_disabled: [true, false]
    )

    with_them do
      let!(:user) { create(:user, password_automatically_set: password_automatically_set) }
      let!(:identity) { create(:identity, user: user) if ldap_user }

      # Only confirm deletion with password if all inputs are false
      let(:expected) { !(password_automatically_set || ldap_user || password_authentication_disabled) }

      before do
3359 3360
        stub_application_setting(password_authentication_enabled_for_web: !password_authentication_disabled)
        stub_application_setting(password_authentication_enabled_for_git: !password_authentication_disabled)
3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
      end

      it 'returns false unless all inputs are true' do
        expect(user.confirm_deletion_with_password?).to eq(expected)
      end
    end
  end

  describe '#delete_async' do
    let(:user) { create(:user) }
    let(:deleted_by) { create(:user) }

    it 'blocks the user then schedules them for deletion if a hard delete is specified' do
      expect(DeleteUserWorker).to receive(:perform_async).with(deleted_by.id, user.id, hard_delete: true)

      user.delete_async(deleted_by: deleted_by, params: { hard_delete: true })

      expect(user).to be_blocked
    end

    it 'schedules user for deletion without blocking them' do
      expect(DeleteUserWorker).to receive(:perform_async).with(deleted_by.id, user.id, {})

      user.delete_async(deleted_by: deleted_by)

      expect(user).not_to be_blocked
    end
  end
3389 3390 3391 3392 3393 3394

  describe '#max_member_access_for_project_ids' do
    shared_examples 'max member access for projects' do
      let(:user) { create(:user) }
      let(:group) { create(:group) }
      let(:owner_project) { create(:project, group: group) }
3395
      let(:maintainer_project) { create(:project) }
3396 3397 3398 3399 3400 3401
      let(:reporter_project) { create(:project) }
      let(:developer_project) { create(:project) }
      let(:guest_project) { create(:project) }
      let(:no_access_project) { create(:project) }

      let(:projects) do
3402
        [owner_project, maintainer_project, reporter_project, developer_project, guest_project, no_access_project].map(&:id)
3403 3404 3405 3406 3407
      end

      let(:expected) do
        {
          owner_project.id => Gitlab::Access::OWNER,
3408
          maintainer_project.id => Gitlab::Access::MAINTAINER,
3409 3410 3411 3412 3413 3414 3415 3416 3417
          reporter_project.id => Gitlab::Access::REPORTER,
          developer_project.id => Gitlab::Access::DEVELOPER,
          guest_project.id => Gitlab::Access::GUEST,
          no_access_project.id => Gitlab::Access::NO_ACCESS
        }
      end

      before do
        create(:group_member, user: user, group: group)
3418
        maintainer_project.add_maintainer(user)
3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
        reporter_project.add_reporter(user)
        developer_project.add_developer(user)
        guest_project.add_guest(user)
      end

      it 'returns correct roles for different projects' do
        expect(user.max_member_access_for_project_ids(projects)).to eq(expected)
      end
    end

    context 'with RequestStore enabled', :request_store do
      include_examples 'max member access for projects'

      def access_levels(projects)
        user.max_member_access_for_project_ids(projects)
      end

      it 'does not perform extra queries when asked for projects who have already been found' do
        access_levels(projects)

        expect { access_levels(projects) }.not_to exceed_query_limit(0)

        expect(access_levels(projects)).to eq(expected)
      end

      it 'only requests the extra projects when uncached projects are passed' do
3445
        second_maintainer_project = create(:project)
3446
        second_developer_project = create(:project)
3447
        second_maintainer_project.add_maintainer(user)
3448 3449
        second_developer_project.add_developer(user)

3450
        all_projects = projects + [second_maintainer_project.id, second_developer_project.id]
3451

3452
        expected_all = expected.merge(second_maintainer_project.id => Gitlab::Access::MAINTAINER,
3453 3454 3455 3456 3457 3458 3459
                                      second_developer_project.id => Gitlab::Access::DEVELOPER)

        access_levels(projects)

        queries = ActiveRecord::QueryRecorder.new { access_levels(all_projects) }

        expect(queries.count).to eq(1)
3460
        expect(queries.log_message).to match(/\W(#{second_maintainer_project.id}, #{second_developer_project.id})\W/)
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473
        expect(access_levels(all_projects)).to eq(expected_all)
      end
    end

    context 'with RequestStore disabled' do
      include_examples 'max member access for projects'
    end
  end

  describe '#max_member_access_for_group_ids' do
    shared_examples 'max member access for groups' do
      let(:user) { create(:user) }
      let(:owner_group) { create(:group) }
3474
      let(:maintainer_group) { create(:group) }
3475 3476 3477 3478 3479 3480
      let(:reporter_group) { create(:group) }
      let(:developer_group) { create(:group) }
      let(:guest_group) { create(:group) }
      let(:no_access_group) { create(:group) }

      let(:groups) do
3481
        [owner_group, maintainer_group, reporter_group, developer_group, guest_group, no_access_group].map(&:id)
3482 3483 3484 3485 3486
      end

      let(:expected) do
        {
          owner_group.id => Gitlab::Access::OWNER,
3487
          maintainer_group.id => Gitlab::Access::MAINTAINER,
3488 3489 3490 3491 3492 3493 3494 3495 3496
          reporter_group.id => Gitlab::Access::REPORTER,
          developer_group.id => Gitlab::Access::DEVELOPER,
          guest_group.id => Gitlab::Access::GUEST,
          no_access_group.id => Gitlab::Access::NO_ACCESS
        }
      end

      before do
        owner_group.add_owner(user)
3497
        maintainer_group.add_maintainer(user)
3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523
        reporter_group.add_reporter(user)
        developer_group.add_developer(user)
        guest_group.add_guest(user)
      end

      it 'returns correct roles for different groups' do
        expect(user.max_member_access_for_group_ids(groups)).to eq(expected)
      end
    end

    context 'with RequestStore enabled', :request_store do
      include_examples 'max member access for groups'

      def access_levels(groups)
        user.max_member_access_for_group_ids(groups)
      end

      it 'does not perform extra queries when asked for groups who have already been found' do
        access_levels(groups)

        expect { access_levels(groups) }.not_to exceed_query_limit(0)

        expect(access_levels(groups)).to eq(expected)
      end

      it 'only requests the extra groups when uncached groups are passed' do
3524
        second_maintainer_group = create(:group)
3525
        second_developer_group = create(:group)
3526
        second_maintainer_group.add_maintainer(user)
3527 3528
        second_developer_group.add_developer(user)

3529
        all_groups = groups + [second_maintainer_group.id, second_developer_group.id]
3530

3531
        expected_all = expected.merge(second_maintainer_group.id => Gitlab::Access::MAINTAINER,
3532 3533 3534 3535 3536 3537 3538
                                      second_developer_group.id => Gitlab::Access::DEVELOPER)

        access_levels(groups)

        queries = ActiveRecord::QueryRecorder.new { access_levels(all_groups) }

        expect(queries.count).to eq(1)
3539
        expect(queries.log_message).to match(/\W(#{second_maintainer_group.id}, #{second_developer_group.id})\W/)
3540 3541 3542 3543 3544 3545 3546 3547
        expect(access_levels(all_groups)).to eq(expected_all)
      end
    end

    context 'with RequestStore disabled' do
      include_examples 'max member access for groups'
    end
  end
3548

B
Bob Van Landuyt 已提交
3549 3550
  context 'changing a username' do
    let(:user) { create(:user, username: 'foo') }
3551

B
Bob Van Landuyt 已提交
3552 3553 3554
    it 'creates a redirect route' do
      expect { user.update!(username: 'bar') }
        .to change { RedirectRoute.where(path: 'foo').count }.by(1)
3555 3556
    end

B
Bob Van Landuyt 已提交
3557 3558 3559 3560 3561
    it 'deletes the redirect when a user with the old username was created' do
      user.update!(username: 'bar')

      expect { create(:user, username: 'foo') }
        .to change { RedirectRoute.where(path: 'foo').count }.by(-1)
3562 3563
    end
  end
3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589

  describe '#required_terms_not_accepted?' do
    let(:user) { build(:user) }
    subject { user.required_terms_not_accepted? }

    context "when terms are not enforced" do
      it { is_expected.to be_falsy }
    end

    context "when terms are enforced and accepted by the user" do
      before do
        enforce_terms
        accept_terms(user)
      end

      it { is_expected.to be_falsy }
    end

    context "when terms are enforced but the user has not accepted" do
      before do
        enforce_terms
      end

      it { is_expected.to be_truthy }
    end
  end
3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603

  describe '#increment_failed_attempts!' do
    subject(:user) { create(:user, failed_attempts: 0) }

    it 'logs failed sign-in attempts' do
      expect { user.increment_failed_attempts! }.to change(user, :failed_attempts).from(0).to(1)
    end

    it 'does not log failed sign-in attempts when in a GitLab read-only instance' do
      allow(Gitlab::Database).to receive(:read_only?) { true }

      expect { user.increment_failed_attempts! }.not_to change(user, :failed_attempts)
    end
  end
J
Jan Provaznik 已提交
3604

3605
  describe '#requires_usage_stats_consent?' do
3606
    let(:user) { create(:user, :admin, created_at: 8.days.ago) }
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629

    before do
      allow(user).to receive(:has_current_license?).and_return false
    end

    context 'in single-user environment' do
      it 'requires user consent after one week' do
        create(:user, ghost: true)

        expect(user.requires_usage_stats_consent?).to be true
      end

      it 'requires user consent after one week if there is another ghost user' do
        expect(user.requires_usage_stats_consent?).to be true
      end

      it 'does not require consent in the first week' do
        user.created_at = 6.days.ago

        expect(user.requires_usage_stats_consent?).to be false
      end

      it 'does not require consent if usage stats were set by this user' do
S
Stan Hu 已提交
3630
        create(:application_setting, usage_stats_set_by_user_id: user.id)
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646

        expect(user.requires_usage_stats_consent?).to be false
      end
    end

    context 'in multi-user environment' do
      before do
        create(:user)
      end

      it 'does not require consent' do
        expect(user.requires_usage_stats_consent?).to be false
      end
    end
  end

J
Jan Provaznik 已提交
3647
  context 'with uploads' do
3648
    it_behaves_like 'model with uploads', false do
J
Jan Provaznik 已提交
3649 3650 3651 3652 3653
      let(:model_object) { create(:user, :with_avatar) }
      let(:upload_attribute) { :avatar }
      let(:uploader_class) { AttachmentUploader }
    end
  end
Y
Yorick Peterse 已提交
3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735

  describe '.union_with_user' do
    context 'when no user ID is provided' do
      it 'returns the input relation' do
        user = create(:user)

        expect(described_class.union_with_user).to eq([user])
      end
    end

    context 'when a user ID is provided' do
      it 'includes the user object in the returned relation' do
        user1 = create(:user)
        user2 = create(:user)
        users = described_class.where(id: user1.id).union_with_user(user2.id)

        expect(users).to include(user1)
        expect(users).to include(user2)
      end

      it 'does not re-apply any WHERE conditions on the outer query' do
        relation = described_class.where(id: 1).union_with_user(2)

        expect(relation.arel.where_sql).to be_nil
      end
    end
  end

  describe '.optionally_search' do
    context 'using nil as the argument' do
      it 'returns the current relation' do
        user = create(:user)

        expect(described_class.optionally_search).to eq([user])
      end
    end

    context 'using an empty String as the argument' do
      it 'returns the current relation' do
        user = create(:user)

        expect(described_class.optionally_search('')).to eq([user])
      end
    end

    context 'using a non-empty String' do
      it 'returns users matching the search query' do
        user1 = create(:user)
        create(:user)

        expect(described_class.optionally_search(user1.name)).to eq([user1])
      end
    end
  end

  describe '.where_not_in' do
    context 'without an argument' do
      it 'returns the current relation' do
        user = create(:user)

        expect(described_class.where_not_in).to eq([user])
      end
    end

    context 'using a list of user IDs' do
      it 'excludes the users from the returned relation' do
        user1 = create(:user)
        user2 = create(:user)

        expect(described_class.where_not_in([user2.id])).to eq([user1])
      end
    end
  end

  describe '.reorder_by_name' do
    it 'reorders the input relation' do
      user1 = create(:user, name: 'A')
      user2 = create(:user, name: 'B')

      expect(described_class.reorder_by_name).to eq([user1, user2])
    end
  end
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768

  describe '#notification_email_for' do
    let(:user) { create(:user) }
    let(:group) { create(:group) }

    subject { user.notification_email_for(group) }

    context 'when group is nil' do
      let(:group) { nil }

      it 'returns global notification email' do
        is_expected.to eq(user.notification_email)
      end
    end

    context 'when group has no notification email set' do
      it 'returns global notification email' do
        create(:notification_setting, user: user, source: group, notification_email: '')

        is_expected.to eq(user.notification_email)
      end
    end

    context 'when group has notification email set' do
      it 'returns group notification email' do
        group_notification_email = 'user+group@example.com'

        create(:notification_setting, user: user, source: group, notification_email: group_notification_email)

        is_expected.to eq(group_notification_email)
      end
    end
  end
3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798

  describe '#password_expired?' do
    let(:user) { build(:user, password_expires_at: password_expires_at) }

    subject { user.password_expired? }

    context 'when password_expires_at is not set' do
      let(:password_expires_at) {}

      it 'returns false' do
        is_expected.to be_falsey
      end
    end

    context 'when password_expires_at is in the past' do
      let(:password_expires_at) { 1.minute.ago }

      it 'returns true' do
        is_expected.to be_truthy
      end
    end

    context 'when password_expires_at is in the future' do
      let(:password_expires_at) { 1.minute.from_now }

      it 'returns false' do
        is_expected.to be_falsey
      end
    end
  end
G
gitlabhq 已提交
3799
end