user_spec.rb 105 KB
Newer Older
gitlabhq's avatar
gitlabhq committed
1 2
require 'spec_helper'

3
describe User do
4
  include ProjectForksHelper
5
  include TermsHelper
6

Shinya Maeda's avatar
Shinya Maeda committed
7
  it_behaves_like 'having unique enum values'
Shinya Maeda's avatar
Shinya Maeda committed
8

9 10 11 12 13 14 15
  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) }
16
    it { is_expected.to include_module(BlocksJsonSerialization) }
17 18
  end

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

23
  describe 'associations' do
24
    it { is_expected.to have_one(:namespace) }
25
    it { is_expected.to have_one(:status) }
26
    it { is_expected.to have_many(:snippets).dependent(:destroy) }
27 28 29
    it { is_expected.to have_many(:members) }
    it { is_expected.to have_many(:project_members) }
    it { is_expected.to have_many(:group_members) }
30 31
    it { is_expected.to have_many(:groups) }
    it { is_expected.to have_many(:keys).dependent(:destroy) }
32
    it { is_expected.to have_many(:deploy_keys).dependent(:nullify) }
33
    it { is_expected.to have_many(:events).dependent(:destroy) }
34
    it { is_expected.to have_many(:issues).dependent(:destroy) }
35 36 37
    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) }
38
    it { is_expected.to have_many(:spam_logs).dependent(:destroy) }
39
    it { is_expected.to have_many(:todos) }
40
    it { is_expected.to have_many(:award_emoji).dependent(:destroy) }
41
    it { is_expected.to have_many(:triggers).dependent(:destroy) }
42 43
    it { is_expected.to have_many(:builds).dependent(:nullify) }
    it { is_expected.to have_many(:pipelines).dependent(:nullify) }
44
    it { is_expected.to have_many(:chat_names).dependent(:destroy) }
Jan Provaznik's avatar
Jan Provaznik committed
45
    it { is_expected.to have_many(:uploads) }
46
    it { is_expected.to have_many(:reported_abuse_reports).dependent(:destroy).class_name('AbuseReport') }
47
    it { is_expected.to have_many(:custom_attributes).class_name('UserCustomAttribute') }
48
    it { is_expected.to have_many(:releases).dependent(:nullify) }
49

50 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
    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
76 77 78 79

    describe '#group_members' do
      it 'does not include group memberships for which user is a requester' do
        user = create(:user)
80
        group = create(:group, :public, :access_requestable)
81 82 83 84 85 86 87 88 89
        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)
90
        project = create(:project, :public, :access_requestable)
91 92 93 94 95
        project.request_access(user)

        expect(user.project_members).to be_empty
      end
    end
96 97 98
  end

  describe 'validations' do
99 100 101 102 103 104 105 106 107
    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
108
        expect(user.errors.messages[:username]).to eq ['dashboard is a reserved name']
109 110
      end

111 112 113 114 115 116 117 118 119 120 121 122
      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

123 124 125 126 127 128 129 130 131 132
      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
133

134 135 136 137 138 139 140 141 142
      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'])
143 144
        end
      end
145 146
    end

147 148 149 150 151 152 153 154 155 156
    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

157 158 159 160
    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) }
161
    it { is_expected.not_to allow_value(Gitlab::Database::MAX_INT_VALUE + 1).for(:projects_limit) }
162

163
    it { is_expected.to validate_length_of(:bio).is_at_most(255) }
164

165 166 167
    it_behaves_like 'an object with email-formated attributes', :email do
      subject { build(:user) }
    end
168

169 170 171
    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
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    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

189 190 191 192 193 194
      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

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
      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

228
    describe 'email' do
229
      context 'when no signup domains whitelisted' do
230
        before do
231
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return([])
232
        end
233

234 235 236 237 238 239
        it 'accepts any email' do
          user = build(:user, email: "info@example.com")
          expect(user).to be_valid
        end
      end

240
      context 'when a signup domain is whitelisted and subdomains are allowed' do
241
        before do
242
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com', '*.example.com'])
243
        end
244

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        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

261
      context 'when a signup domain is whitelisted and subdomains are not allowed' do
262
        before do
263
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com'])
264
        end
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

        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
280 281 282 283 284

        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
285
      end
286

287 288 289 290 291 292
      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

293
        context 'when a signup domain is blacklisted' do
294 295 296 297 298 299 300 301 302
          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
303 304 305 306 307

          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
308 309
        end

310
        context 'when a signup domain is blacklisted but a wildcard subdomain is allowed' do
311 312
          before do
            allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist).and_return(['test.example.com'])
313
            allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['*.example.com'])
314 315
          end

316
          it 'gives priority to whitelist and allow info@test.example.com' do
317 318 319 320 321 322 323
            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
324
            allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['test.com'])
325 326 327 328 329 330 331 332 333 334 335 336 337 338
          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

339 340 341 342 343 344
      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
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

      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
379
    end
380 381 382 383 384 385 386
  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)
387
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
388 389 390 391 392 393 394 395

        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)
396
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
397 398 399 400 401 402 403 404

        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)
405
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
406 407 408 409

        expect(users_with_two_factor).to eq([user_with_2fa.id])
        expect(users_with_two_factor).not_to include(user_without_2fa.id)
      end
410 411 412 413 414 415 416 417

      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
418 419 420 421 422 423
    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)
424
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
425 426 427 428 429 430 431 432

        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)
433
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
434 435 436 437 438 439 440 441

        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)
442
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
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
    end
448

449 450 451 452
    describe '.limit_to_todo_authors' do
      context 'when filtering by todo authors' do
        let(:user1) { create(:user) }
        let(:user2) { create(:user) }
453

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 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
        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
498 499
      end
    end
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

    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
gitlabhq's avatar
gitlabhq committed
517 518 519
  end

  describe "Respond to" do
520
    it { is_expected.to respond_to(:admin?) }
521
    it { is_expected.to respond_to(:name) }
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535
    it { is_expected.to respond_to(:external?) }
  end

  describe 'before save hook' do
    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
536

537 538
    describe '#check_for_verified_email' do
      let(:user)      { create(:user) }
539 540
      let(:secondary) { create(:email, :confirmed, email: 'secondary@example.com', user: user) }

541
      it 'allows a verfied secondary email to be used as the primary without needing reconfirmation' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
542
        user.update!(email: secondary.email)
543 544 545 546 547 548
        user.reload
        expect(user.email).to eq secondary.email
        expect(user.unconfirmed_email).to eq nil
        expect(user.confirmed?).to be_truthy
      end
    end
gitlabhq's avatar
gitlabhq committed
549 550
  end

551
  describe 'after commit hook' do
552 553 554 555 556 557 558 559 560 561 562
    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)
563

Lin Jen-Shin's avatar
Lin Jen-Shin committed
564
        @user.update!(email: 'new_primary@example.com')
565 566
      end

567
      it 'adds old primary to secondary emails when secondary is a new email ' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
568
        @user.update!(email: 'new_primary@example.com')
569
        @user.reload
570

571 572
        expect(@user.emails.count).to eq 2
        expect(@user.emails.pluck(:email)).to match_array([@secondary.email, 'primary@example.com'])
573 574 575
      end

      it 'adds old primary to secondary emails if secondary is becoming a primary' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
576
        @user.update!(email: @secondary.email)
577
        @user.reload
578

579 580 581 582 583
        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
Lin Jen-Shin's avatar
Lin Jen-Shin committed
584
        @user.update!(email: @secondary.email)
585
        @user.reload
586

587 588 589 590
        expect(@user.emails.count).to eq 1
        expect(@user.emails.first.confirmed_at).not_to eq nil
      end
    end
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 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

    describe '#update_notification_email' do
      # Regression: https://gitlab.com/gitlab-org/gitlab-ce/issues/22846
      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)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
653
        user.update!(name: 'Bette')
654 655 656 657
      end

      it 'synchronizes the gpg keys when the email is updated' do
        expect(user).to receive(:update_invalid_gpg_signatures).at_most(:twice)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
658
        user.update!(email: 'shawnee.ritchie@denesik.com')
659 660
      end
    end
661 662
  end

663
  describe '#update_tracked_fields!', :clean_gitlab_redis_shared_state do
664 665 666 667 668 669 670 671 672 673 674 675 676 677
    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)
678 679 680 681 682 683 684 685 686 687 688
      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 }
689
    end
690 691 692 693 694 695 696 697

    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
698 699
  end

700 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
  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

  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

728
  describe '#confirm' do
729 730 731
    before do
      allow_any_instance_of(ApplicationSetting).to receive(:send_user_confirmation_email).and_return(true)
    end
732

733 734 735 736 737 738 739
    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
740
      user.confirm
741 742 743 744
      expect(user.confirmed?).to be_truthy
    end
  end

745 746 747 748 749 750 751 752
  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

753
  describe '#generate_password' do
754
    it "does not generate password by default" do
755
      user = create(:user, password: 'abcdefghe')
756

757
      expect(user.password).to eq('abcdefghe')
758
    end
759 760
  end

761 762 763 764 765 766 767 768 769
  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

770 771 772
  describe 'ensure incoming email token' do
    it 'has incoming email token' do
      user = create(:user)
773

774 775
      expect(user.incoming_email_token).not_to be_blank
    end
776 777 778 779 780 781 782 783

    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
784 785
  end

786 787 788 789 790 791 792
  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)

Lin Jen-Shin's avatar
Lin Jen-Shin committed
793
        user.update(external: false)
794 795 796
      end

      it 'ensures correct rights and limits for user' do
797 798
        stub_config_setting(default_can_create_group: true)

Lin Jen-Shin's avatar
Lin Jen-Shin committed
799
        expect { user.update(external: false) }.to change { user.can_create_group }.to(true)
800
          .and change { user.projects_limit }.to(Gitlab::CurrentSettings.default_projects_limit)
801 802 803 804 805 806 807 808 809
      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)

Lin Jen-Shin's avatar
Lin Jen-Shin committed
810
        user.update(external: true)
811 812 813
      end

      it 'ensures correct rights and limits for user' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
814
        expect { user.update(external: true) }.to change { user.can_create_group }.to(false)
815 816 817 818 819
          .and change { user.projects_limit }.to(0)
      end
    end
  end

820 821 822 823
  describe 'feed token' do
    it 'ensures a feed token on read' do
      user = create(:user, feed_token: nil)
      feed_token = user.feed_token
824

825 826
      expect(feed_token).not_to be_blank
      expect(user.reload.feed_token).to eq feed_token
827 828 829
    end
  end

830
  describe '#recently_sent_password_reset?' do
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
    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

850 851 852 853 854 855 856
  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
857
      expect(user.otp_grace_period_started_at).not_to be_nil
858 859 860 861 862 863 864 865

      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
866
      expect(user.otp_grace_period_started_at).to be_nil
867 868 869
    end
  end

870 871
  describe 'projects' do
    before do
872
      @user = create(:user)
873

874 875
      @project = create(:project, namespace: @user.namespace)
      @project_2 = create(:project, group: create(:group)) do |project|
876
        project.add_maintainer(@user)
877
      end
878
      @project_3 = create(:project, group: create(:group)) do |project|
879 880
        project.add_developer(@user)
      end
881 882
    end

883 884 885 886 887 888 889 890 891
    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) }
892 893 894
  end

  describe 'groups' do
895 896 897
    let(:user) { create(:user) }
    let(:group) { create(:group) }

898
    before do
899
      group.add_owner(user)
900 901
    end

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    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) }

    context 'with child groups', :nested_groups do
      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
    end
929 930
  end

931 932 933 934
  describe 'group multiple owners' do
    before do
      @user = create :user
      @user2 = create :user
935 936
      @group = create :group
      @group.add_owner(@user)
937

938
      @group.add_user(@user2, GroupMember::OWNER)
939 940
    end

941
    it { expect(@user2.several_namespaces?).to be_truthy }
942 943
  end

944 945 946
  describe 'namespaced' do
    before do
      @user = create :user
947
      @project = create(:project, namespace: @user.namespace)
948 949
    end

950
    it { expect(@user.several_namespaces?).to be_falsey }
951
    it { expect(@user.namespaces).to eq([@user.namespace]) }
952 953 954 955 956
  end

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

957
    it "blocks user" do
958
      user.block
959

960
      expect(user.blocked?).to be_truthy
961 962 963
    end
  end

964 965 966 967
  describe '.filter' do
    let(:user) { double }

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

970
      expect(described_class.filter(nil)).to include user
971 972
    end

973
    it 'filters by admins' do
974
      expect(described_class).to receive(:admins).and_return([user])
975

976
      expect(described_class.filter('admins')).to include user
977 978
    end

979
    it 'filters by blocked' do
980
      expect(described_class).to receive(:blocked).and_return([user])
981

982
      expect(described_class.filter('blocked')).to include user
983 984 985
    end

    it 'filters by two_factor_disabled' do
986
      expect(described_class).to receive(:without_two_factor).and_return([user])
987

988
      expect(described_class.filter('two_factor_disabled')).to include user
989 990 991
    end

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

994
      expect(described_class.filter('two_factor_enabled')).to include user
995 996 997
    end

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

1000
      expect(described_class.filter('wop')).to include user
1001
    end
1002 1003
  end

1004
  describe '.without_projects' do
1005
    let!(:project) { create(:project, :public, :access_requestable) }
1006 1007 1008 1009 1010 1011
    let!(:user) { create(:user) }
    let!(:user_without_project) { create(:user) }
    let!(:user_without_project2) { create(:user) }

    before do
      # add user to project
1012
      project.add_maintainer(user)
1013 1014 1015 1016 1017 1018 1019 1020

      # 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

1021 1022 1023
    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 }
1024 1025
  end

1026 1027 1028
  describe 'user creation' do
    describe 'normal user' do
      let(:user) { create(:user, name: 'John Smith') }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
1029

1030
      it { expect(user.admin?).to be_falsey }
1031 1032 1033 1034
      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') }
1035
      it { expect(user.external).to be_falsey }
1036
    end
1037

1038
    describe 'with defaults' do
1039
      let(:user) { described_class.new }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
1040

1041
      it "applies defaults to user" do
1042 1043
        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)
1044
        expect(user.theme_id).to eq(Gitlab.config.gitlab.default_theme)
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
1045
        expect(user.external).to be_falsey
1046 1047 1048
      end
    end

1049
    describe 'with default overrides' do
1050
      let(:user) { described_class.new(projects_limit: 123, can_create_group: false, can_create_team: true) }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
1051

1052
      it "applies defaults to user" do
1053 1054
        expect(user.projects_limit).to eq(123)
        expect(user.can_create_group).to be_falsey
1055
        expect(user.theme_id).to eq(1)
1056
      end
1057 1058 1059 1060 1061 1062 1063

      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
1064
    end
1065

1066
    context 'when Gitlab::CurrentSettings.user_default_external is true' do
1067 1068 1069 1070 1071
      before do
        stub_application_setting(user_default_external: true)
      end

      it "creates external user by default" do
1072
        user = create(:user)
1073 1074

        expect(user.external).to be_truthy
1075 1076
        expect(user.can_create_group).to be_falsey
        expect(user.projects_limit).to be 0
1077 1078 1079 1080
      end

      describe 'with default overrides' do
        it "creates a non-external user" do
1081
          user = create(:user, external: false)
1082 1083 1084 1085 1086

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

1088
    describe '#require_ssh_key?', :use_clean_rails_memory_store_caching do
1089 1090 1091
      protocol_and_expectation = {
        'http' => false,
        'ssh' => true,
1092
        '' => true
1093 1094 1095 1096 1097 1098 1099 1100 1101
      }

      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
1102
      end
1103 1104 1105 1106 1107 1108

      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
1109
    end
1110
  end
1111

1112 1113 1114 1115 1116 1117 1118 1119
  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

1120
  describe '.find_by_any_email' do
1121 1122 1123 1124 1125 1126 1127 1128
    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

1129 1130 1131
    it 'finds by primary email' do
      user = create(:user, email: 'foo@example.com')

1132
      expect(described_class.find_by_any_email(user.email)).to eq user
1133
      expect(described_class.find_by_any_email(user.email, confirmed: true)).to eq user
1134 1135
    end

1136 1137 1138 1139 1140 1141 1142
    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

1143 1144
    context 'finds by secondary email' do
      let(:user) { email.user }
1145

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
      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
1175 1176 1177
    end

    it 'returns nil when nothing found' do
1178
      expect(described_class.find_by_any_email('')).to be_nil
1179
    end
1180 1181 1182 1183 1184 1185 1186

    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
1187 1188
  end

1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  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
1200 1201 1202 1203 1204 1205

    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
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221

    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
1222 1223
  end

1224
  describe '.search' do
1225 1226
    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') }
1227
    let!(:user3) { create(:user, name: 'us', username: 'se', email: 'foo@gmail.com') }
1228

1229 1230 1231 1232
    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
1233

1234
      it 'returns users with a partially matching name' do
1235
        expect(described_class.search(user.name[0..2])).to eq([user, user2])
1236
      end
1237

1238 1239 1240
      it 'returns users with a matching name regardless of the casing' do
        expect(described_class.search(user2.name.upcase)).to eq([user2])
      end
1241 1242 1243 1244 1245 1246 1247 1248

      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
1249 1250
    end

1251 1252
    describe 'email matching' do
      it 'returns users with a matching Email' do
1253
        expect(described_class.search(user.email)).to eq([user])
1254
      end
1255

1256 1257
      it 'does not return users with a partially matching Email' do
        expect(described_class.search(user.email[0..2])).not_to include(user, user2)
1258
      end
1259

1260 1261 1262
      it 'returns users with a matching Email regardless of the casing' do
        expect(described_class.search(user2.email.upcase)).to eq([user2])
      end
1263 1264
    end

1265 1266 1267 1268
    describe 'username matching' do
      it 'returns users with a matching username' do
        expect(described_class.search(user.username)).to eq([user, user2])
      end
1269

1270
      it 'returns users with a partially matching username' do
1271
        expect(described_class.search(user.username[0..2])).to eq([user, user2])
1272
      end
1273

1274 1275 1276
      it 'returns users with a matching username regardless of the casing' do
        expect(described_class.search(user2.username.upcase)).to eq([user2])
      end
1277 1278 1279 1280 1281 1282 1283 1284

      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
1285
    end
1286 1287 1288 1289 1290 1291 1292 1293

    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
1294 1295 1296
  end

  describe '.search_with_secondary_emails' do
Douwe Maan's avatar
Douwe Maan committed
1297
    delegate :search_with_secondary_emails, to: :described_class
1298

1299 1300
    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' ) }
1301 1302 1303
    let!(:email) do
      create(:email, user: another_user, email: 'alias@example.com')
    end
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

    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

1321 1322
    it 'does not return users with a partially matching email' do
      expect(search_with_secondary_emails(user.email[0..2])).not_to include([user])
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    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

1345 1346
    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])
1347
    end
1348 1349 1350 1351 1352 1353 1354 1355

    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
1356 1357
  end

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  describe '.find_by_ssh_key_id' do
    context 'using an existing SSH key ID' do
      let(:user) { create(:user) }
      let(:key) { create(:key, user: user) }

      it 'returns the corresponding User' do
        expect(described_class.find_by_ssh_key_id(key.id)).to eq(user)
      end
    end

    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

1375 1376 1377 1378
  describe '.by_login' do
    let(:username) { 'John' }
    let!(:user) { create(:user, username: username) }

1379
    it 'gets the correct user' do
1380 1381 1382 1383 1384 1385
      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
1386 1387 1388
    end
  end

1389 1390 1391 1392 1393 1394 1395
  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')
1396

1397 1398 1399 1400
      expect(described_class.find_by_username('JOHNDOE')).to eq user
    end
  end

1401 1402
  describe '.find_by_username!' do
    it 'raises RecordNotFound' do
1403 1404
      expect { described_class.find_by_username!('JohnDoe') }
        .to raise_error(ActiveRecord::RecordNotFound)
1405 1406 1407 1408
    end

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

1410 1411 1412 1413
      expect(described_class.find_by_username!('JOHNDOE')).to eq user
    end
  end

1414 1415 1416 1417 1418 1419 1420
  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
1421
        expect(described_class.find_by_full_path(route.path)).to eq(user)
1422 1423 1424
      end

      it 'is case-insensitive' do
1425 1426
        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)
1427 1428 1429 1430 1431 1432 1433 1434
      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
1435
          expect(described_class.find_by_full_path(redirect_route.path)).to eq(nil)
1436 1437 1438 1439 1440
        end
      end

      context 'with the follow_redirects option set to true' do
        it 'returns the user' do
1441
          expect(described_class.find_by_full_path(redirect_route.path, follow_redirects: true)).to eq(user)
1442 1443 1444
        end

        it 'is case-insensitive' do
1445 1446
          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)
1447 1448 1449 1450 1451 1452 1453
        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
1454
          expect(described_class.find_by_full_path('unknown')).to eq(nil)
1455 1456 1457 1458
        end
      end
      context 'with the follow_redirects option set to true' do
        it 'returns nil' do
1459
          expect(described_class.find_by_full_path('unknown', follow_redirects: true)).to eq(nil)
1460 1461 1462 1463 1464
        end
      end
    end

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

Michael Kozono's avatar
Michael Kozono committed
1467
      context 'when the group namespace has an owner_id (legacy data)' do
1468 1469 1470
        before do
          group.update!(owner_id: user.id)
        end
1471

Michael Kozono's avatar
Michael Kozono committed
1472
        it 'returns nil' do
1473
          expect(described_class.find_by_full_path('group_path')).to eq(nil)
Michael Kozono's avatar
Michael Kozono committed
1474 1475 1476 1477 1478
        end
      end

      context 'when the group namespace does not have an owner_id' do
        it 'returns nil' do
1479
          expect(described_class.find_by_full_path('group_path')).to eq(nil)
Michael Kozono's avatar
Michael Kozono committed
1480
        end
1481 1482 1483 1484
      end
    end
  end

1485
  describe 'all_ssh_keys' do
1486
    it { is_expected.to have_many(:keys).dependent(:destroy) }
1487

1488
    it "has all ssh keys" do
1489 1490 1491
      user = create :user
      key = create :key, key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD33bWLBxu48Sev9Fert1yzEO4WGcWglWF7K/AwblIUFselOt/QdOL9DSjpQGxLagO1s9wl53STIO8qGS4Ms0EJZyIXOEFMjFJ5xmjSy+S37By4sG7SsltQEHMxtbtFOaW5LV2wCrX+rUsRNqLMamZjgjcPO0/EgGCXIGMAYW4O7cwGZdXWYIhQ1Vwy+CsVMDdPkPgBXqK7nR/ey8KMs8ho5fMNgB5hBw/AL9fNGhRw3QTD6Q12Nkhl4VZES2EsZqlpNnJttnPdp847DUsT6yuLRlfiQfz5Cn9ysHFdXObMN5VYIiPFwHeYCZp1X2S4fDZooRE8uOLTfxWHPXwrhqSH", user_id: user.id

1492
      expect(user.all_ssh_keys).to include(a_string_starting_with(key.key))
1493
    end
1494
  end
1495

1496
  describe '#avatar_type' do
1497 1498
    let(:user) { create(:user) }

1499
    it 'is true if avatar is image' do
1500
      user.update_attribute(:avatar, 'uploads/avatar.png')
Douwe Maan's avatar