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

3
describe User do
4
  include ProjectForksHelper
5
  include TermsHelper
6

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

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

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

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    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
73 74 75 76

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

        expect(user.project_members).to be_empty
      end
    end
93 94 95
  end

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

108 109 110 111 112 113 114 115 116 117 118 119
      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

120 121 122 123 124 125 126 127 128 129
      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
130

131 132 133 134 135 136 137 138 139
      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'])
140 141
        end
      end
142 143
    end

144 145 146 147 148 149 150 151 152 153
    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

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

160
    it { is_expected.to validate_length_of(:bio).is_at_most(255) }
161

162 163 164
    it_behaves_like 'an object with email-formated attributes', :email do
      subject { build(:user) }
    end
165

166 167 168
    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
169

170
    describe 'email' do
171
      context 'when no signup domains whitelisted' do
172
        before do
173
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return([])
174
        end
175

176 177 178 179 180 181
        it 'accepts any email' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_valid
        end
      end

182
      context 'when a signup domain is whitelisted and subdomains are allowed' do
183
        before do
184
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com', '*.example.com'])
185
        end
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        it 'accepts [email protected]' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_valid
        end

        it 'accepts [email protected]' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_valid
        end

        it 'rejects [email protected]' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_invalid
        end
      end

203
      context 'when a signup domain is whitelisted and subdomains are not allowed' do
204
        before do
205
          allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com'])
206
        end
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

        it 'accepts [email protected]' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_valid
        end

        it 'rejects [email protected]' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_invalid
        end

        it 'rejects [email protected]' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_invalid
        end
222 223 224 225 226

        it 'accepts [email protected] when added by another user' do
          user = build(:user, email: "[email protected]", created_by_id: 1)
          expect(user).to be_valid
        end
227
      end
228

229 230 231 232 233 234
      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

235
        context 'when a signup domain is blacklisted' do
236 237 238 239 240 241 242 243 244
          it 'accepts [email protected]' do
            user = build(:user, email: '[email protected]')
            expect(user).to be_valid
          end

          it 'rejects [email protected]' do
            user = build(:user, email: '[email protected]')
            expect(user).not_to be_valid
          end
245 246 247 248 249

          it 'accepts [email protected] when added by another user' do
            user = build(:user, email: '[email protected]', created_by_id: 1)
            expect(user).to be_valid
          end
250 251
        end

252
        context 'when a signup domain is blacklisted but a wildcard subdomain is allowed' do
253 254
          before do
            allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist).and_return(['test.example.com'])
255
            allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['*.example.com'])
256 257
          end

258
          it 'gives priority to whitelist and allow [email protected]' do
259 260 261 262 263 264 265
            user = build(:user, email: '[email protected]')
            expect(user).to be_valid
          end
        end

        context 'with both lists containing a domain' do
          before do
266
            allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['test.com'])
267 268 269 270 271 272 273 274 275 276 277 278 279 280
          end

          it 'accepts [email protected]' do
            user = build(:user, email: '[email protected]')
            expect(user).to be_valid
          end

          it 'rejects [email protected]' do
            user = build(:user, email: '[email protected]')
            expect(user).not_to be_valid
          end
        end
      end

281 282 283 284 285 286
      context 'owns_notification_email' do
        it 'accepts temp_oauth_email emails' do
          user = build(:user, email: "[email protected]")
          expect(user).to be_valid
        end
      end
287
    end
288 289 290 291 292 293 294
  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)
295
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
296 297 298 299 300 301 302 303

        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)
304
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
305 306 307 308 309 310 311 312

        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)
313
        users_with_two_factor = described_class.with_two_factor.pluck(:id)
314 315 316 317

        expect(users_with_two_factor).to eq([user_with_2fa.id])
        expect(users_with_two_factor).not_to include(user_without_2fa.id)
      end
318 319 320 321 322 323 324 325

      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
326 327 328 329 330 331
    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)
332
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
333 334 335 336 337 338 339 340

        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)
341
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
342 343 344 345 346 347 348 349

        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)
350
        users_without_two_factor = described_class.without_two_factor.pluck(:id)
351 352 353 354 355

        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
356

357 358 359 360
    describe '.limit_to_todo_authors' do
      context 'when filtering by todo authors' do
        let(:user1) { create(:user) }
        let(:user2) { create(:user) }
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 394 395 396 397 398 399 400 401 402 403 404 405
        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
406 407
      end
    end
gitlabhq's avatar
gitlabhq committed
408 409 410
  end

  describe "Respond to" do
blackst0ne's avatar
blackst0ne committed
411
    it { is_expected.to respond_to(:admin?) }
412
    it { is_expected.to respond_to(:name) }
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426
    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
427

428 429
    describe '#check_for_verified_email' do
      let(:user)      { create(:user) }
430 431
      let(:secondary) { create(:email, :confirmed, email: '[email protected]', user: user) }

432
      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
433
        user.update!(email: secondary.email)
434 435 436 437 438 439
        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
440 441
  end

442
  describe 'after commit hook' do
443 444 445 446 447 448 449 450 451 452 453
    describe '#update_emails_with_primary_email' do
      before do
        @user = create(:user, email: '[email protected]').tap do |user|
          user.skip_reconfirmation!
        end
        @secondary = create :email, email: '[email protected]', user: @user
        @user.reload
      end

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

Lin Jen-Shin's avatar
Lin Jen-Shin committed
455
        @user.update!(email: '[email protected]')
456 457
      end

458
      it 'adds old primary to secondary emails when secondary is a new email ' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
459
        @user.update!(email: '[email protected]')
460
        @user.reload
461

462 463
        expect(@user.emails.count).to eq 2
        expect(@user.emails.pluck(:email)).to match_array([@secondary.email, '[email protected]'])
464 465 466
      end

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

470 471 472 473 474
        expect(@user.emails.count).to eq 1
        expect(@user.emails.first.email).to eq '[email protected]'
      end

      it 'transfers old confirmation values into new secondary' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
475
        @user.update!(email: @secondary.email)
476
        @user.reload
477

478 479 480 481
        expect(@user.emails.count).to eq 1
        expect(@user.emails.first.confirmed_at).not_to eq nil
      end
    end
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 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543

    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) { '[email protected]' }

        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: '[email protected]', 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: '[email protected]').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
544
        user.update!(name: 'Bette')
545 546 547 548
      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
549
        user.update!(email: '[email protected]')
550 551
      end
    end
552 553
  end

554
  describe '#update_tracked_fields!', :clean_gitlab_redis_shared_state do
555 556 557 558 559 560 561 562 563 564 565 566 567 568
    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)
569 570 571 572 573 574 575 576 577 578 579
      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 }
580
    end
581 582 583 584 585 586 587 588

    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
589 590
  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
  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

619
  describe '#confirm' do
620 621 622
    before do
      allow_any_instance_of(ApplicationSetting).to receive(:send_user_confirmation_email).and_return(true)
    end
623

624 625 626 627 628 629 630
    let(:user) { create(:user, confirmed_at: nil, unconfirmed_email: '[email protected]') }

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

    it 'confirms a user' do
631
      user.confirm
632 633 634 635
      expect(user.confirmed?).to be_truthy
    end
  end

636 637 638 639 640 641 642 643
  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

644
  describe '#generate_password' do
645
    it "does not generate password by default" do
646
      user = create(:user, password: 'abcdefghe')
647

648
      expect(user.password).to eq('abcdefghe')
649
    end
650 651
  end

652 653 654
  describe 'ensure incoming email token' do
    it 'has incoming email token' do
      user = create(:user)
655

656 657 658 659
      expect(user.incoming_email_token).not_to be_blank
    end
  end

660 661 662 663 664 665 666
  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
667
        user.update(external: false)
668 669 670
      end

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

Lin Jen-Shin's avatar
Lin Jen-Shin committed
673
        expect { user.update(external: false) }.to change { user.can_create_group }.to(true)
674
          .and change { user.projects_limit }.to(Gitlab::CurrentSettings.default_projects_limit)
675 676 677 678 679 680 681 682 683
      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
684
        user.update(external: true)
685 686 687
      end

      it 'ensures correct rights and limits for user' do
Lin Jen-Shin's avatar
Lin Jen-Shin committed
688
        expect { user.update(external: true) }.to change { user.can_create_group }.to(false)
689 690 691 692 693
          .and change { user.projects_limit }.to(0)
      end
    end
  end

694 695 696 697
  describe 'feed token' do
    it 'ensures a feed token on read' do
      user = create(:user, feed_token: nil)
      feed_token = user.feed_token
698

699 700
      expect(feed_token).not_to be_blank
      expect(user.reload.feed_token).to eq feed_token
701 702 703
    end
  end

704
  describe '#recently_sent_password_reset?' do
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    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

Robert Speicher's avatar
Robert Speicher committed
724 725 726 727 728 729 730
  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
731
      expect(user.otp_grace_period_started_at).not_to be_nil
Robert Speicher's avatar
Robert Speicher committed
732 733 734 735 736 737 738 739

      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
740
      expect(user.otp_grace_period_started_at).to be_nil
Robert Speicher's avatar
Robert Speicher committed
741 742 743
    end
  end

744 745
  describe 'projects' do
    before do
746
      @user = create(:user)
747

748 749
      @project = create(:project, namespace: @user.namespace)
      @project_2 = create(:project, group: create(:group)) do |project|
750
        project.add_maintainer(@user)
751
      end
752
      @project_3 = create(:project, group: create(:group)) do |project|
753 754
        project.add_developer(@user)
      end
755 756
    end

757 758 759 760 761 762 763 764 765
    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) }
766 767 768
  end

  describe 'groups' do
769 770 771
    let(:user) { create(:user) }
    let(:group) { create(:group) }

772
    before do
773
      group.add_owner(user)
774 775
    end

776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    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
803 804
  end

805 806 807 808
  describe 'group multiple owners' do
    before do
      @user = create :user
      @user2 = create :user
809 810
      @group = create :group
      @group.add_owner(@user)
811

812
      @group.add_user(@user2, GroupMember::OWNER)
813 814
    end

815
    it { expect(@user2.several_namespaces?).to be_truthy }
816 817
  end

818 819 820
  describe 'namespaced' do
    before do
      @user = create :user
821
      @project = create(:project, namespace: @user.namespace)
822 823
    end

824
    it { expect(@user.several_namespaces?).to be_falsey }
825
    it { expect(@user.namespaces).to eq([@user.namespace]) }
826 827 828 829 830
  end

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

831
    it "blocks user" do
832
      user.block
833

834
      expect(user.blocked?).to be_truthy
835 836 837
    end
  end

838 839 840 841
  describe '.filter' do
    let(:user) { double }

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

844
      expect(described_class.filter(nil)).to include user
845 846
    end

847
    it 'filters by admins' do
848
      expect(described_class).to receive(:admins).and_return([user])
849

850
      expect(described_class.filter('admins')).to include user
851 852
    end

853
    it 'filters by blocked' do
854
      expect(described_class).to receive(:blocked).and_return([user])
855

856
      expect(described_class.filter('blocked')).to include user
857 858 859
    end

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

862
      expect(described_class.filter('two_factor_disabled')).to include user
863 864 865
    end

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

868
      expect(described_class.filter('two_factor_enabled')).to include user
869 870 871
    end

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

874
      expect(described_class.filter('wop')).to include user
875
    end
876 877
  end

878
  describe '.without_projects' do
879
    let!(:project) { create(:project, :public, :access_requestable) }
880 881 882 883 884 885
    let!(:user) { create(:user) }
    let!(:user_without_project) { create(:user) }
    let!(:user_without_project2) { create(:user) }

    before do
      # add user to project
886
      project.add_maintainer(user)
887 888 889 890 891 892 893 894

      # create invite to projet
      create(:project_member, :developer, project: project, invite_token: '1234', invite_email: '[email protected]')

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

895 896 897
    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 }
898 899
  end

900 901 902
  describe 'user creation' do
    describe 'normal user' do
      let(:user) { create(:user, name: 'John Smith') }
Dmytro Zaporozhets's avatar
Dmytro Zaporozhets committed
903

blackst0ne's avatar
blackst0ne committed
904
      it { expect(user.admin?).to be_falsey }
905 906 907 908
      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') }
909
      it { expect(user.external).to be_falsey }
910
    end
911

Dmytro Zaporozhets's avatar
Dmytro Zaporozhets committed
912
    describe 'with defaults' do
913
      let(:user) { described_class.new }
Dmytro Zaporozhets's avatar
Dmytro Zaporozhets committed
914

915
      it "applies defaults to user" do
916 917
        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)
918
        expect(user.theme_id).to eq(Gitlab.config.gitlab.default_theme)
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
919
        expect(user.external).to be_falsey
920 921 922
      end
    end

Dmytro Zaporozhets's avatar
Dmytro Zaporozhets committed
923
    describe 'with default overrides' do
924
      let(:user) { described_class.new(projects_limit: 123, can_create_group: false, can_create_team: true) }
Dmytro Zaporozhets's avatar
Dmytro Zaporozhets committed
925

926
      it "applies defaults to user" do
927 928
        expect(user.projects_limit).to eq(123)
        expect(user.can_create_group).to be_falsey
929
        expect(user.theme_id).to eq(1)
930
      end
931 932 933 934 935 936 937

      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
938
    end
939

940
    context 'when Gitlab::CurrentSettings.user_default_external is true' do
941 942 943 944 945
      before do
        stub_application_setting(user_default_external: true)
      end

      it "creates external user by default" do
946
        user = create(:user)
947 948

        expect(user.external).to be_truthy
949 950
        expect(user.can_create_group).to be_falsey
        expect(user.projects_limit).to be 0
951 952 953 954
      end

      describe 'with default overrides' do
        it "creates a non-external user" do
955
          user = create(:user, external: false)
956 957 958 959 960

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

962
    describe '#require_ssh_key?', :use_clean_rails_memory_store_caching do
963 964 965
      protocol_and_expectation = {
        'http' => false,
        'ssh' => true,
966
        '' => true
967 968 969 970 971 972 973 974 975
      }

      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
976
      end
977 978 979 980 981 982

      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
983
    end
984
  end
985

986 987 988 989 990 991 992 993
  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

994
  describe '.find_by_any_email' do
995 996 997
    it 'finds by primary email' do
      user = create(:user, email: '[email protected]')

998
      expect(described_class.find_by_any_email(user.email)).to eq user
999
      expect(described_class.find_by_any_email(user.email, confirmed: true)).to eq user
1000 1001 1002 1003 1004 1005
    end

    it 'finds by secondary email' do
      email = create(:email, email: '[email protected]')
      user  = email.user

1006
      expect(described_class.find_by_any_email(email.email)).to eq user
1007
      expect(described_class.find_by_any_email(email.email, confirmed: true)).to eq user
1008 1009 1010
    end

    it 'returns nil when nothing found' do
1011
      expect(described_class.find_by_any_email('')).to be_nil
1012
    end
1013 1014 1015 1016 1017 1018 1019

    it 'returns nil when user is not confirmed' do
      user = create(:user, email: '[email protected]', 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
1020 1021
  end

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
  describe '.by_any_email' do
    it 'returns an ActiveRecord::Relation' do
      expect(described_class.by_any_email('[email protected]'))
        .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
1033 1034 1035 1036 1037 1038

    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
1039 1040
  end

1041
  describe '.search' do
1042 1043
    let!(:user) { create(:user, name: 'user', username: 'usern', email: '[email protected]') }
    let!(:user2) { create(:user, name: 'user name', username: 'username', email: '[email protected]') }
1044
    let!(:user3) { create(:user, name: 'us', username: 'se', email: '[email protected]') }
1045

1046 1047 1048 1049
    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
1050

1051
      it 'returns users with a partially matching name' do
1052
        expect(described_class.search(user.name[0..2])).to eq([user, user2])
1053
      end
1054

1055 1056 1057
      it 'returns users with a matching name regardless of the casing' do
        expect(described_class.search(user2.name.upcase)).to eq([user2])
      end
1058 1059 1060 1061 1062 1063 1064 1065

      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
1066 1067
    end

1068 1069
    describe 'email matching' do
      it 'returns users with a matching Email' do
1070
        expect(described_class.search(user.email)).to eq([user])
1071
      end
1072

1073 1074
      it 'does not return users with a partially matching Email' do
        expect(described_class.search(user.email[0..2])).not_to include(user, user2)
1075
      end
1076

1077 1078 1079
      it 'returns users with a matching Email regardless of the casing' do
        expect(described_class.search(user2.email.upcase)).to eq([user2])
      end
1080 1081
    end

1082 1083 1084 1085
    describe 'username matching' do
      it 'returns users with a matching username' do
        expect(described_class.search(user.username)).to eq([user, user2])
      end
1086

1087
      it 'returns users with a partially matching username' do
1088
        expect(described_class.search(user.username[0..2])).to eq([user, user2])
1089
      end
1090

1091 1092 1093
      it 'returns users with a matching username regardless of the casing' do
        expect(described_class.search(user2.username.upcase)).to eq([user2])
      end
1094 1095 1096 1097 1098 1099 1100 1101

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

    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
1111 1112 1113
  end

  describe '.search_with_secondary_emails' do
Douwe Maan's avatar
Douwe Maan committed
1114
    delegate :search_with_secondary_emails, to: :described_class
1115

1116 1117
    let!(:user) { create(:user, name: 'John Doe', username: 'john.doe', email: '[email protected]' ) }
    let!(:another_user) { create(:user, name: 'Albert Smith', username: 'albert.smith', email: '[email protected]' ) }
1118 1119 1120
    let!(:email) do
      create(:email, user: another_user, email: '[email protected]')
    end
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137

    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

1138 1139
    it 'does not return users with a partially matching email' do
      expect(search_with_secondary_emails(user.email[0..2])).not_to include([user])
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    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

1162 1163
    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])
1164
    end
1165 1166 1167 1168 1169 1170 1171 1172

    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
1173 1174
  end

Yorick Peterse's avatar
Yorick Peterse committed
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  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

1192 1193 1194 1195
  describe '.by_login' do
    let(:username) { 'John' }
    let!(:user) { create(:user, username: username) }

1196
    it 'gets the correct user' do
1197 1198 1199 1200 1201 1202
      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
1203 1204 1205
    end
  end

1206 1207 1208 1209 1210 1211 1212
  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')
1213

1214 1215 1216 1217
      expect(described_class.find_by_username('JOHNDOE')).to eq user
    end
  end

Robert Speicher's avatar
Robert Speicher committed
1218 1219
  describe '.find_by_username!' do
    it 'raises RecordNotFound' do
1220 1221
      expect { described_class.find_by_username!('JohnDoe') }
        .to raise_error(ActiveRecord::RecordNotFound)
Robert Speicher's avatar
Robert Speicher committed
1222 1223 1224 1225
    end

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

Robert Speicher's avatar
Robert Speicher committed
1227 1228 1229 1230
      expect(described_class.find_by_username!('JOHNDOE')).to eq user
    end
  end

1231 1232 1233 1234 1235 1236 1237
  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
1238
        expect(described_class.find_by_full_path(route.path)).to eq(user)
1239 1240 1241
      end

      it 'is case-insensitive' do
1242 1243
        expect(described_class.find_by_full_path(route.path.upcase)).to eq(user)