Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

8.4 KB
Raw Blame
<?php

declare(strict_types=1);

namespace Tests\Feature\Auth;

use HiEvents\Models\Account;
use HiEvents\Models\AccountAttribution;
use HiEvents\Models\AccountConfiguration;
use HiEvents\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use Tests\TestCase;

class RegisterTest extends TestCase
{
    use RefreshDatabase;

    private const REGISTER_ROUTE = '/auth/register';

    protected function setUp(): void
    {
        parent::setUp();
        AccountConfiguration::firstOrCreate(['id' => 1], [
            'id' => 1,
            'name' => 'Default',
            'is_system_default' => true,
            'application_fees' => [
                'percentage' => 1.5,
                'fixed' => 0,
            ],
        ]);
    }

    public function test_register_user(): void
    {
        $password = fake()->password(16);
        $user = User::factory()->password($password)->make([
            'email' => fake()->unique()->safeEmail(),
        ]);
        $account = Account::factory()->make();

        Config::set('app.disable_registration', false);

        $response = $this->post(self::REGISTER_ROUTE, [
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'password' => $password,
            'password_confirmation' => $password,
            'timezone' => $user->timezone,
            'currency_code' => $account->currency_code,
            'locale' => $user->locale,
            'invite_token' => null,
        ]);

        $response->assertStatus(201);

        $userFromDB = User::where('email', $user->email)->first();
        $accountFromDB = Account::where('email', $user->email)->first();

        $this->assertNotNull($userFromDB);
        $this->assertNotNull($accountFromDB);

        $this->assertDatabaseHas('account_users', [
            'account_id' => $accountFromDB->id,
            'user_id' => $userFromDB->id,
        ]);

        // registered user got logged in
        $response->assertCookie('token');
        $response->assertHeader('X-Auth-Token');
    }

    public function test_registration_disabled(): void
    {
        $password = fake()->password(16);
        $user = User::factory()->make();
        $account = Account::factory()->make();

        Config::set('app.disable_registration', true);

        $response = $this->post(self::REGISTER_ROUTE, [
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'password' => $password,
            'password_confirmation' => $password,
            'timezone' => $user->timezone,
            'currency_code' => $account->currency_code,
            'locale' => $user->locale,
            'invite_token' => null,
        ]);

        $response->assertStatus(403);
    }

    public function test_register_user_with_duplicate_data(): void
    {
        $user = User::factory()->make();
        $account = Account::factory()->make();
        $password = fake()->password(16);
        $data = [
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'password' => $password,
            'password_confirmation' => $password,
            'timezone' => $user->timezone,
            'currency_code' => $account->currency_code,
            'locale' => $user->locale,
            'invite_token' => null,
        ];

        Config::set('app.disable_registration', false);

        $response = $this->post(self::REGISTER_ROUTE, $data);
        $response->assertStatus(201);

        Config::set('app.disable_registration', false);

        auth()->logout();

        $response2 = $this->post(self::REGISTER_ROUTE, $data, ['Accept' => 'application/json']);
        $response2->assertJsonValidationErrors(['email']);
    }

    public function test_register_user_with_invalid_data(): void
    {
        $user = User::factory()->make();
        $account = Account::factory()->make();
        $password = fake()->password(16);
        $data = [
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'password' => $password,
            'password_confirmation' => $password,
            'timezone' => $user->timezone,
            'currency_code' => $account->currency_code,
            'locale' => $user->locale,
        ];
        Config::set('app.disable_registration', false);

        // valid currency code but not supported by application (north corean won)
        $response = $this->post(
            self::REGISTER_ROUTE,
            [...$data, 'currency_code' => 'KPW'],
            ['Accept' => 'application/json']
        );
        $response->assertJsonValidationErrors(['currency_code']);

        // valid locale but not supported by application (tigriyna)
        $response = $this->post(
            self::REGISTER_ROUTE,
            [...$data, 'locale' => 'ti_ER'],
            ['Accept' => 'application/json']
        );
        $response->assertJsonValidationErrors(['locale']);

        // invalid invite_token
        $response = $this->post(
            self::REGISTER_ROUTE,
            [...$data, 'invite_token' => 'aaaaaa'],
            ['Accept' => 'application/json']
        );
        $response->assertJsonValidationErrors(['invite_token']);
    }

    public function test_rejects_scam_text_in_the_name(): void
    {
        Config::set('app.disable_registration', false);

        $response = $this->postJson(self::REGISTER_ROUTE, $this->registrationPayload([
            'first_name' => 'Your crypto purchase USD 364 success via PayPal. INV ID UTRX4 If unauthorized call +1(805)891-5965 xvc',
        ]));

        $response->assertJsonValidationErrors(['first_name']);
        $this->assertDatabaseMissing('users', ['email' => '[email protected]']);
    }

    public function test_oversized_tracking_parameters_never_block_registration(): void
    {
        Config::set('app.disable_registration', false);

        $utmRaw = [];
        foreach (range(1, 40) as $index) {
            $utmRaw['utm_param_'.$index] = str_repeat('x', 5000);
        }

        $response = $this->postJson(self::REGISTER_ROUTE, $this->registrationPayload([
            'utm_source' => 'google',
            'utm_raw' => $utmRaw,
        ]));

        $response->assertStatus(201);

        $storedRaw = AccountAttribution::query()
            ->where('account_id', Account::where('email', '[email protected]')->value('id'))
            ->value('utm_raw');

        $this->assertCount(20, $storedRaw);
        $this->assertSame(255, mb_strlen($storedRaw['utm_param_1']));
    }

    public function test_requires_a_turnstile_token_when_turnstile_is_configured(): void
    {
        Config::set('app.disable_registration', false);
        Config::set('services.turnstile.secret_key', 'secret');
        Http::fake(['challenges.cloudflare.com/*' => Http::response(['success' => false])]);

        $response = $this->postJson(self::REGISTER_ROUTE, $this->registrationPayload([
            'turnstile_token' => 'bad-token',
        ]));

        $response->assertJsonValidationErrors(['turnstile_token']);
        $this->assertDatabaseMissing('users', ['email' => '[email protected]']);
    }

    public function test_registration_is_throttled_per_ip(): void
    {
        Config::set('app.disable_registration', true);
        Config::set('app.register_rate_limit_per_hour', 3);
        RateLimiter::clear('');

        $statuses = [];

        foreach (range(1, 4) as $attempt) {
            $statuses[] = $this->postJson(self::REGISTER_ROUTE, $this->registrationPayload([
                'email' => 'attempt'.$attempt.'@example.com',
            ]))->status();
        }

        $this->assertNotContains(429, array_slice($statuses, 0, 3));
        $this->assertSame(429, $statuses[3]);
    }

    private function registrationPayload(array $overrides = []): array
    {
        return [
            'first_name' => 'Ana María',
            'last_name' => 'Nguyễn',
            'email' => '[email protected]',
            'password' => 'a-long-enough-password',
            'password_confirmation' => 'a-long-enough-password',
            'timezone' => 'UTC',
            'currency_code' => 'USD',
            'locale' => 'en',
            ...$overrides,
        ];
    }
}