├── .github └── workflows │ ├── app-tests.yml │ ├── dependabot-auto-merge.yml │ ├── fix-styling.yml │ ├── larastan.yml │ ├── package-tests.yml │ ├── split.yml │ ├── update-changelog.yml │ └── validate-generator-styling.yml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── packages ├── bladebones │ ├── .github │ │ └── workflows │ │ │ └── close-pull-request.yml │ ├── .gitignore │ ├── LICENSE.md │ ├── composer.json │ ├── phpunit.xml.dist │ ├── src │ │ ├── Console │ │ │ └── GenerateCommand.php │ │ ├── LaravelAuthBladebonesServiceProvider.php │ │ └── Testing │ │ │ ├── BladeViewTests.php │ │ │ └── Partials │ │ │ ├── AccountRecoveryChallengeViewTests.php │ │ │ ├── AccountRecoveryRequestViewTests.php │ │ │ ├── CredentialsOverviewViewTests.php │ │ │ ├── LoginViewTests.php │ │ │ ├── MultiFactorChallengeViewTests.php │ │ │ ├── RegisterPublicKeyCredentialViewTests.php │ │ │ ├── RegisterTotpCredentialViewTests.php │ │ │ ├── RegisterViewTests.php │ │ │ └── SudoModeChallengeViewTests.php │ ├── stubs │ │ ├── defaults │ │ │ ├── routes │ │ │ │ └── web.stub │ │ │ └── views │ │ │ │ ├── challenges │ │ │ │ ├── multi_factor.blade.stub │ │ │ │ ├── recovery.blade.stub │ │ │ │ └── sudo_mode.blade.stub │ │ │ │ ├── home.blade.stub │ │ │ │ ├── login.blade.stub │ │ │ │ ├── recover-account.blade.stub │ │ │ │ ├── register.blade.stub │ │ │ │ └── settings │ │ │ │ ├── confirm_public_key.blade.stub │ │ │ │ ├── confirm_recovery_codes.blade.stub │ │ │ │ ├── confirm_totp.blade.stub │ │ │ │ ├── credentials.blade.stub │ │ │ │ └── recovery_codes.blade.stub │ │ └── username-based │ │ │ └── views │ │ │ ├── login.blade.stub │ │ │ └── register.blade.stub │ ├── templates │ │ ├── Controllers │ │ │ ├── AccountRecoveryRequestController.bladetmpl │ │ │ ├── Challenges │ │ │ │ ├── AccountRecoveryChallengeController.bladetmpl │ │ │ │ ├── MultiFactorChallengeController.bladetmpl │ │ │ │ └── SudoModeChallengeController.bladetmpl │ │ │ ├── LoginController.bladetmpl │ │ │ ├── RegisterController.bladetmpl │ │ │ ├── Settings │ │ │ │ ├── ChangePasswordController.bladetmpl │ │ │ │ ├── CredentialsController.bladetmpl │ │ │ │ ├── GenerateRecoveryCodesController.bladetmpl │ │ │ │ ├── RegisterPublicKeyCredentialController.bladetmpl │ │ │ │ └── RegisterTotpCredentialController.bladetmpl │ │ │ └── VerifyEmailController.bladetmpl │ │ └── Tests │ │ │ └── AuthenticationTest.bladetmpl │ └── tests │ │ ├── Feature │ │ └── Console │ │ │ └── GenerateCommandTest.php │ │ └── TestCase.php └── core │ ├── .github │ └── workflows │ │ └── close-pull-request.yml │ ├── .gitignore │ ├── LICENSE.md │ ├── composer.json │ ├── config │ └── laravel-auth.php │ ├── database │ ├── factories │ │ └── MultiFactorCredentialFactory.php │ └── migrations │ │ └── 2022_02_08_000002_create_multi_factor_credentials_table.php │ ├── lang │ └── en │ │ └── auth.php │ ├── phpunit.xml.dist │ ├── src │ ├── Console │ │ └── GenerateCommand.php │ ├── CredentialType.php │ ├── Events │ │ ├── AccountRecovered.php │ │ ├── AccountRecoveryFailed.php │ │ ├── Authenticated.php │ │ ├── AuthenticationFailed.php │ │ ├── Mixins │ │ │ ├── EmitsAuthenticatedEvent.php │ │ │ └── EmitsLockoutEvent.php │ │ ├── MultiFactorChallengeFailed.php │ │ ├── MultiFactorChallenged.php │ │ ├── PasswordChanged.php │ │ ├── RecoveryCodesGenerated.php │ │ ├── SudoModeChallenged.php │ │ └── SudoModeEnabled.php │ ├── Http │ │ ├── Concerns │ │ │ ├── HandlesLogouts.php │ │ │ ├── InteractsWithRateLimiting.php │ │ │ ├── Login │ │ │ │ ├── PasskeyBasedAuthentication.php │ │ │ │ └── PasswordBasedAuthentication.php │ │ │ └── Registration │ │ │ │ ├── PasskeyBasedRegistration.php │ │ │ │ └── PasswordBasedRegistration.php │ │ ├── Controllers │ │ │ ├── AccountRecoveryRequestController.php │ │ │ ├── Challenges │ │ │ │ ├── AccountRecoveryChallengeController.php │ │ │ │ ├── MultiFactorChallengeController.php │ │ │ │ └── SudoModeChallengeController.php │ │ │ ├── LoginController.php │ │ │ ├── RegisterController.php │ │ │ ├── Settings │ │ │ │ ├── ChangePasswordController.php │ │ │ │ ├── CredentialsController.php │ │ │ │ ├── GenerateRecoveryCodesController.php │ │ │ │ ├── RegisterPublicKeyCredentialController.php │ │ │ │ └── RegisterTotpCredentialController.php │ │ │ └── VerifyEmailController.php │ │ ├── Middleware │ │ │ ├── EnsurePasswordBasedUser.php │ │ │ ├── EnsurePreAuthenticated.php │ │ │ └── EnsureSudoMode.php │ │ ├── Mixins │ │ │ ├── Challenges │ │ │ │ ├── PasswordChallenge.php │ │ │ │ ├── PublicKeyChallenge.php │ │ │ │ └── TotpChallenge.php │ │ │ └── EnablesSudoMode.php │ │ └── Modifiers │ │ │ ├── EmailBased.php │ │ │ ├── UsernameBased.php │ │ │ └── WithoutVerificationEmail.php │ ├── LaravelAuth.php │ ├── LaravelAuthServiceProvider.php │ ├── Methods │ │ ├── Totp │ │ │ ├── Contracts │ │ │ │ └── TotpContract.php │ │ │ ├── Exceptions │ │ │ │ └── InvalidSecretException.php │ │ │ └── GoogleTwoFactorAuthenticator.php │ │ └── WebAuthn │ │ │ ├── Contracts │ │ │ └── WebAuthnContract.php │ │ │ ├── Exceptions │ │ │ ├── InvalidPublicKeyCredentialException.php │ │ │ ├── UnexpectedActionException.php │ │ │ └── WebAuthnException.php │ │ │ ├── Objects │ │ │ └── CredentialAttributes.php │ │ │ ├── SpomkyAdapter │ │ │ ├── AuthenticatorSelectionCriteria.php │ │ │ ├── PublicKeyCredentialCreationOptions.php │ │ │ ├── PublicKeyCredentialDescriptor.php │ │ │ ├── PublicKeyCredentialParameters.php │ │ │ ├── PublicKeyCredentialRequestOptions.php │ │ │ ├── PublicKeyCredentialRpEntity.php │ │ │ ├── PublicKeyCredentialSourceRepository.php │ │ │ └── PublicKeyCredentialUserEntity.php │ │ │ └── SpomkyWebAuthn.php │ ├── MultiFactorCredential.php │ ├── Notifications │ │ └── AccountRecoveryNotification.php │ ├── RecoveryCodeManager.php │ ├── Specifications │ │ └── WebAuthn │ │ │ ├── AttestedCredentialData.php │ │ │ ├── AuthenticatorData.php │ │ │ ├── ClientExtension.php │ │ │ ├── Dictionaries │ │ │ ├── AuthenticationExtensionsClientInputs.php │ │ │ ├── AuthenticationExtensionsClientOutputs.php │ │ │ ├── AuthenticatorSelectionCriteria.php │ │ │ ├── ClientExtensions.php │ │ │ ├── PublicKeyCredentialCreationOptions.php │ │ │ ├── PublicKeyCredentialDescriptor.php │ │ │ ├── PublicKeyCredentialParameters.php │ │ │ ├── PublicKeyCredentialRequestOptions.php │ │ │ ├── PublicKeyCredentialRpEntity.php │ │ │ └── PublicKeyCredentialUserEntity.php │ │ │ ├── Enums │ │ │ ├── AttestationConveyancePreference.php │ │ │ ├── AuthenticatorAttachment.php │ │ │ ├── AuthenticatorTransport.php │ │ │ ├── COSEAlgorithmIdentifier.php │ │ │ ├── PublicKeyCredentialType.php │ │ │ ├── ResidentKeyRequirement.php │ │ │ └── UserVerificationRequirement.php │ │ │ └── Helpers │ │ │ ├── AuthenticatorDataFlags.php │ │ │ ├── Enums │ │ │ └── AuthenticatorDataBit.php │ │ │ └── TypeSafeArrays │ │ │ ├── AuthenticatorTransports.php │ │ │ ├── PublicKeyCredentialDescriptors.php │ │ │ └── PublicKeyCredentialParametersCollection.php │ ├── Support │ │ ├── AccountSecurityIndicator.php │ │ └── QrImage.php │ └── Testing │ │ ├── AccountRecoveryChallengeTests.php │ │ ├── AccountRecoveryRequestTests.php │ │ ├── EmailVerification │ │ ├── RegisterWithVerificationEmailTests.php │ │ └── RegisterWithoutVerificationEmailTests.php │ │ ├── EmailVerificationTests.php │ │ ├── Flavors │ │ ├── EmailBased.php │ │ └── UsernameBased.php │ │ ├── GenerateRecoveryCodesTests.php │ │ ├── Helpers.php │ │ ├── LoginTests.php │ │ ├── LogoutTests.php │ │ ├── MultiFactorChallengeTests.php │ │ ├── Partials │ │ ├── CancelPasskeyBasedRegistrationTests.php │ │ ├── Challenges │ │ │ ├── MultiFactor │ │ │ │ ├── SubmitMultiFactorChallengeTests.php │ │ │ │ ├── SubmitMultiFactorChallengeUsingPublicKeyCredentialTests.php │ │ │ │ ├── SubmitMultiFactorChallengeUsingTotpCodeTests.php │ │ │ │ └── ViewMultiFactorChallengePageTests.php │ │ │ ├── Recovery │ │ │ │ ├── SubmitAccountRecoveryChallengeTests.php │ │ │ │ └── ViewAccountRecoveryChallengePageTests.php │ │ │ └── SudoMode │ │ │ │ ├── ConfirmSudoModeUsingCredentialTests.php │ │ │ │ ├── ConfirmSudoModeUsingPasswordTests.php │ │ │ │ └── ViewSudoModeChallengePageTests.php │ │ ├── Settings │ │ │ ├── PublicKey │ │ │ │ ├── ConfirmPublicKeyCredentialRegistrationTests.php │ │ │ │ └── InitializePublicKeyCredentialRegistrationTests.php │ │ │ ├── Recovery │ │ │ │ ├── ConfirmRecoveryCodesGenerationTests.php │ │ │ │ ├── InitializeRecoveryCodesGenerationTests.php │ │ │ │ └── ViewRecoveryCodesGenerationConfirmationPageTests.php │ │ │ └── Totp │ │ │ │ ├── CancelTotpCredentialRegistrationTests.php │ │ │ │ ├── ConfirmTotpCredentialRegistrationTests.php │ │ │ │ ├── InitializeTotpCredentialRegistrationTests.php │ │ │ │ └── ViewTotpCredentialRegistrationConfirmationPageTests.php │ │ ├── SubmitAccountRecoveryRequestTests.php │ │ ├── SubmitPasskeyBasedAuthenticationTests.php │ │ ├── SubmitPasskeyBasedRegistrationTests.php │ │ ├── SubmitPasswordBasedAuthenticationTests.php │ │ ├── SubmitPasswordBasedRegistrationTests.php │ │ ├── ViewAccountRecoveryRequestPageTests.php │ │ ├── ViewLoginPageTests.php │ │ └── ViewRegistrationPageTests.php │ │ ├── RegisterPublicKeyCredentialTests.php │ │ ├── RegisterTotpCredentialTests.php │ │ ├── RegistrationTests.php │ │ ├── RemoveCredentialTests.php │ │ ├── SubmitChangePasswordTests.php │ │ ├── SudoModeChallengeTests.php │ │ ├── Support │ │ └── InstantlyResolvingTimebox.php │ │ └── ViewCredentialsOverviewPageTests.php │ ├── templates │ ├── Console │ │ └── Kernel.bladetmpl │ ├── Database │ │ ├── 2014_10_12_000000_create_users_table.bladetmpl │ │ ├── User.bladetmpl │ │ └── UserFactory.bladetmpl │ └── Tests │ │ ├── PruneUnclaimedUsersTest.bladetmpl │ │ └── UserTest.bladetmpl │ └── tests │ ├── TestCase.php │ ├── Unit │ ├── Http │ │ └── Middleware │ │ │ ├── EnsurePasswordBasedUserTest.php │ │ │ └── EnsureSudoModeTest.php │ ├── LaravelAuthTest.php │ └── MultiFactorCredentialTest.php │ └── _fixtures │ └── FakeUser.php └── phpstan.neon.dist /.github/workflows/app-tests.yml: -------------------------------------------------------------------------------- 1 | name: App Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - '*.x' 8 | pull_request: 9 | schedule: 10 | - cron: '0 0 * * *' 11 | 12 | jobs: 13 | tests: 14 | runs-on: ubuntu-22.04 15 | 16 | strategy: 17 | fail-fast: true 18 | matrix: 19 | php: [ 8.1, 8.2 ] 20 | laravel: [ 9, 10 ] 21 | stability: [ 'prefer-lowest', 'prefer-stable' ] 22 | variants: [ 23 | '', 24 | '--kind username-based' 25 | ] 26 | 27 | name: PHP ${{ matrix.php }} L${{ matrix.laravel }} ${{ matrix.variants }} (w/ ${{ matrix.stability }}) 28 | steps: 29 | - name: Checkout code 30 | uses: actions/checkout@v3 31 | with: 32 | path: ./monorepo 33 | 34 | - name: Setup PHP 35 | uses: shivammathur/setup-php@v2 36 | with: 37 | php-version: ${{ matrix.php }} 38 | extensions: dom, curl, libxml, mbstring, zip 39 | ini-values: error_reporting=E_ALL 40 | tools: composer:v2 41 | coverage: none 42 | 43 | - name: Create Laravel Project 44 | uses: nick-fields/retry@v2 45 | with: 46 | timeout_minutes: 5 47 | max_attempts: 5 48 | command: composer create-project laravel/laravel app "${{ matrix.laravel }}.x" --remove-vcs --prefer-dist --no-interaction 49 | 50 | - name: Downgrade Laravel dependencies to lowest supported versions 51 | run: composer update --prefer-lowest --prefer-dist --no-interaction 52 | working-directory: ./app 53 | if: matrix.stability == 'prefer-lowest' 54 | 55 | - name: Set Laravel Environment 56 | run: | 57 | sed -i "s/APP_DEBUG=.*/APP_DEBUG=true/" .env 58 | sed -i "s/DB_PASSWORD=.*/DB_PASSWORD=secret/" .env 59 | working-directory: ./app 60 | 61 | - name: Relax dependency constraint for claudiodekker/laravel-auth-core 62 | run: | 63 | sed -i "s/\"claudiodekker\/laravel-auth-core\": \".*\"/\"claudiodekker\/laravel-auth-core\": \"\*\"/" composer.json 64 | working-directory: ./monorepo/packages/bladebones 65 | 66 | - name: Install Library & Bladebones Adapter 67 | run: | 68 | composer config minimum-stability dev 69 | composer config repositories.library path ../monorepo/packages/core 70 | composer config repositories.adapter path ../monorepo/packages/bladebones 71 | composer require claudiodekker/laravel-auth-core claudiodekker/laravel-auth-bladebones -W --${{ matrix.stability }} 72 | working-directory: ./app 73 | 74 | - name: Generate Auth Scaffolding 75 | run: php artisan auth:generate --yes ${{ matrix.variants }} 76 | working-directory: ./app 77 | 78 | - name: Migrate Database 79 | run: php artisan migrate 80 | working-directory: ./app 81 | 82 | - name: Execute tests 83 | run: vendor/bin/phpunit 84 | working-directory: ./app 85 | 86 | services: 87 | mysql: 88 | image: 'mysql:5.7' 89 | ports: 90 | - 3306:3306 91 | env: 92 | MYSQL_DATABASE: laravel 93 | MYSQL_ROOT_PASSWORD: secret 94 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: dependabot-auto-merge 2 | on: pull_request_target 3 | 4 | permissions: 5 | pull-requests: write 6 | contents: write 7 | 8 | jobs: 9 | dependabot: 10 | runs-on: ubuntu-22.04 11 | if: ${{ github.actor == 'dependabot[bot]' }} 12 | 13 | steps: 14 | - name: Dependabot metadata 15 | id: metadata 16 | uses: dependabot/fetch-metadata@v1.3.5 17 | with: 18 | github-token: "${{ secrets.GITHUB_TOKEN }}" 19 | 20 | - name: Auto-merge Dependabot PRs for semver-minor updates 21 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}} 22 | run: gh pr merge --auto --merge "$PR_URL" 23 | env: 24 | PR_URL: ${{github.event.pull_request.html_url}} 25 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 26 | 27 | - name: Auto-merge Dependabot PRs for semver-patch updates 28 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} 29 | run: gh pr merge --auto --merge "$PR_URL" 30 | env: 31 | PR_URL: ${{github.event.pull_request.html_url}} 32 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 33 | -------------------------------------------------------------------------------- /.github/workflows/fix-styling.yml: -------------------------------------------------------------------------------- 1 | name: Check & fix styling 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - '*.x' 8 | pull_request: 9 | 10 | jobs: 11 | pint: 12 | runs-on: ubuntu-22.04 13 | 14 | steps: 15 | - name: Checkout code 16 | uses: actions/checkout@v3 17 | 18 | - name: Setup PHP 19 | uses: shivammathur/setup-php@v2 20 | with: 21 | php-version: '8.1' 22 | tools: pint 23 | 24 | - name: Run Laravel Pint 25 | run: pint --preset laravel 26 | 27 | - name: Commit changes 28 | uses: stefanzweifel/git-auto-commit-action@v4 29 | with: 30 | commit_message: Fix styling 31 | -------------------------------------------------------------------------------- /.github/workflows/larastan.yml: -------------------------------------------------------------------------------- 1 | name: Larastan Static Analysis 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - '*.x' 8 | pull_request: 9 | 10 | jobs: 11 | larastan: 12 | runs-on: ubuntu-22.04 13 | 14 | steps: 15 | - name: Checkout code 16 | uses: actions/checkout@v3 17 | 18 | - name: Setup PHP 19 | uses: shivammathur/setup-php@v2 20 | with: 21 | php-version: 8.1 22 | tools: composer:v2 23 | 24 | - name: Install dependencies 25 | uses: nick-fields/retry@v2 26 | with: 27 | timeout_minutes: 5 28 | max_attempts: 5 29 | command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress 30 | 31 | - name: Run Larastan 32 | run: vendor/bin/phpstan 33 | -------------------------------------------------------------------------------- /.github/workflows/package-tests.yml: -------------------------------------------------------------------------------- 1 | name: Package Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - '*.x' 8 | pull_request: 9 | 10 | jobs: 11 | package-tests: 12 | runs-on: ubuntu-22.04 13 | 14 | strategy: 15 | fail-fast: true 16 | matrix: 17 | package: [ 'core', 'bladebones' ] 18 | php: [ 8.1, 8.2 ] 19 | laravel: [ 9, 10 ] 20 | stability: [ 'prefer-lowest', 'prefer-stable' ] 21 | 22 | name: ${{ matrix.package }} - PHP ${{ matrix.php }} L${{ matrix.laravel }} w/ ${{ matrix.stability }} 23 | steps: 24 | - name: Checkout code 25 | uses: actions/checkout@v3 26 | 27 | - name: Setup PHP 28 | uses: shivammathur/setup-php@v2 29 | with: 30 | php-version: ${{ matrix.php }} 31 | extensions: dom, curl, libxml, mbstring, zip 32 | ini-values: error_reporting=E_ALL 33 | tools: composer:v2 34 | coverage: none 35 | 36 | - name: Configure ${{ matrix.package }} to use local core package 37 | run: | 38 | sed -i "s/\"claudiodekker\/laravel-auth-core\": \".*\"/\"claudiodekker\/laravel-auth-core\": \"\*\"/" composer.json 39 | composer config repositories.library path ../core 40 | working-directory: ./packages/${{ matrix.package }} 41 | if: matrix.package != 'core' 42 | 43 | - name: Install dependencies 44 | uses: nick-fields/retry@v2 45 | with: 46 | timeout_minutes: 5 47 | max_attempts: 5 48 | command: | 49 | cd ./packages/${{ matrix.package }} 50 | composer require "illuminate/contracts=^${{ matrix.laravel }}" --no-update 51 | composer update --${{ matrix.stability }} --no-interaction 52 | 53 | - name: Execute tests 54 | run: vendor/bin/phpunit 55 | working-directory: ./packages/${{ matrix.package }} 56 | -------------------------------------------------------------------------------- /.github/workflows/split.yml: -------------------------------------------------------------------------------- 1 | name: 'Split monorepo' 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - '*.x' 8 | tags: 9 | - 'v*' 10 | 11 | jobs: 12 | split: 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | package: [ 'core', 'bladebones' ] 19 | 20 | steps: 21 | - name: Checkout code 22 | uses: actions/checkout@v3 23 | with: 24 | fetch-depth: 0 25 | 26 | - name: Split package ${{ matrix.package }} 27 | uses: "claudiodekker/splitsh-action@v1.0.0" 28 | env: 29 | GITHUB_TOKEN: ${{ secrets.MONOREPO_SPLITTER_PERSONAL_ACCESS_TOKEN }} 30 | with: 31 | prefix: "packages/${{ matrix.package }}" 32 | remote: "https://github.com/claudiodekker/laravel-auth-${{ matrix.package }}.git" 33 | reference: "${{ github.ref_name }}" 34 | as_tag: "${{ startsWith(github.ref, 'refs/tags/') }}" 35 | -------------------------------------------------------------------------------- /.github/workflows/update-changelog.yml: -------------------------------------------------------------------------------- 1 | name: Update Changelog on PR Merge 2 | 3 | on: 4 | pull_request_target: 5 | types: 6 | - closed 7 | 8 | jobs: 9 | update-changelog: 10 | name: Update Changelog 11 | runs-on: ubuntu-latest 12 | if: github.event.pull_request.merged == true 13 | 14 | permissions: 15 | contents: write 16 | 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v3 20 | with: 21 | ref: ${{ github.event.pull_request.base.ref }} 22 | fetch-depth: 0 23 | 24 | - name: Determine changelog section to update 25 | id: sections 26 | run: | 27 | section="" 28 | labels=$(echo '${{ toJSON(github.event.pull_request.labels.*.name) }}' | jq -r '.[]') 29 | for label in $labels; do 30 | lower_label=$(echo "$label" | tr '[:upper:]' '[:lower:]') 31 | case "$lower_label" in 32 | enhancement|feature) section="Added"; break;; 33 | bug|bugfix|fix|patch) section="Fixed"; break;; 34 | change) section="Changed"; break;; 35 | optimization|improvement|performance|refactor) section="Optimized"; break;; 36 | deprecation|deprecated) section="Deprecated"; break;; 37 | revert) section="Reverted"; break;; 38 | removal) section="Removed"; break;; 39 | security) section="Security"; break;; 40 | esac 41 | done 42 | 43 | if [ -z "$section" ]; then 44 | echo "No matching label found for changelog entry, skipping changelog update." 45 | exit 0 46 | else 47 | echo "section=$section" >> $GITHUB_OUTPUT 48 | fi 49 | 50 | - name: Add entry to CHANGELOG.md 51 | if: steps.sections.outputs.section != '' 52 | uses: claudiodekker/changelog-updater@master 53 | with: 54 | section: "${{ steps.sections.outputs.section }}" 55 | entry-text: "${{ github.event.pull_request.title }}" 56 | entry-link: "${{ github.event.pull_request.html_url }}" 57 | 58 | - name: Commit updated CHANGELOG 59 | if: steps.sections.outputs.section != '' 60 | uses: stefanzweifel/git-auto-commit-action@v4 61 | with: 62 | branch: ${{ github.event.pull_request.base.ref }} 63 | commit_message: "Update CHANGELOG.md w/ PR #${{ github.event.pull_request.number }}" 64 | file_pattern: CHANGELOG.md 65 | -------------------------------------------------------------------------------- /.github/workflows/validate-generator-styling.yml: -------------------------------------------------------------------------------- 1 | name: Validate Core Generator Styling 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - '*.x' 8 | pull_request: 9 | 10 | jobs: 11 | validator: 12 | runs-on: ubuntu-22.04 13 | if: github.event_name == 'pull_request' 14 | 15 | strategy: 16 | fail-fast: true 17 | matrix: 18 | variants: [ 19 | '', 20 | '--kind username-based' 21 | ] 22 | 23 | name: Variant - ${{ matrix.variants }} 24 | steps: 25 | - name: Checkout code 26 | uses: actions/checkout@v3 27 | with: 28 | path: ./monorepo 29 | 30 | - name: Setup PHP 31 | uses: shivammathur/setup-php@v2 32 | with: 33 | php-version: 8.1 34 | extensions: dom, curl, libxml, mbstring, zip 35 | ini-values: error_reporting=E_ALL 36 | tools: composer:v2, pint 37 | coverage: none 38 | 39 | - name: Create Laravel Project 40 | uses: nick-fields/retry@v2 41 | with: 42 | timeout_minutes: 5 43 | max_attempts: 5 44 | command: composer create-project laravel/laravel app "10.x" --remove-vcs --prefer-dist --no-interaction 45 | 46 | - name: Relax dependency constraint for claudiodekker/laravel-auth-core 47 | run: | 48 | sed -i "s/\"claudiodekker\/laravel-auth-core\": \".*\"/\"claudiodekker\/laravel-auth-core\": \"\*\"/" composer.json 49 | working-directory: ./monorepo/packages/bladebones 50 | 51 | - name: Install Library & Bladebones Adapter 52 | run: | 53 | composer config minimum-stability dev 54 | composer config repositories.library path ../monorepo/packages/core 55 | composer config repositories.adapter path ../monorepo/packages/bladebones 56 | composer require claudiodekker/laravel-auth-core claudiodekker/laravel-auth-bladebones -W 57 | working-directory: ./app 58 | 59 | - name: Generate Auth Scaffolding 60 | run: php artisan auth:generate --yes ${{ matrix.variants }} 61 | working-directory: ./app 62 | 63 | - name: Stage all generated files 64 | run: | 65 | git config --global user.email "github@actions.test" 66 | git config --global user.name "GitHub Actions" 67 | git init . 68 | git add . 69 | git commit -m "Generated Auth Scaffolding" 70 | working-directory: ./app 71 | 72 | - name: Fix using Laravel Pint 73 | run: pint --preset laravel 74 | working-directory: ./app 75 | 76 | - name: Show any to-be-fixed changes 77 | run: | 78 | if [[ -z $(git status --porcelain) ]]; then 79 | exit 0 80 | fi 81 | 82 | git -c color.ui=always --no-pager diff 83 | exit 1 84 | working-directory: ./app 85 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /.vscode 3 | /vendor 4 | .phpunit.result.cache 5 | composer.lock 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Claudio Dekker 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "claudiodekker/laravel-auth", 3 | "description": "Rich authentication logic and scaffoldings for your Laravel applications.", 4 | "authors": [ 5 | { 6 | "name": "Claudio Dekker", 7 | "email": "claudio@ubient.net" 8 | } 9 | ], 10 | "require": { 11 | "bacon/bacon-qr-code": "^2.0", 12 | "claudiodekker/word-generator": "^1.0", 13 | "laravel/framework": "^9.33|^10.0", 14 | "nyholm/psr7": "^1.5", 15 | "php": "~8.1.0|~8.2.0", 16 | "pragmarx/google2fa": "^8.0", 17 | "symfony/psr-http-message-bridge": "^2.1", 18 | "web-auth/webauthn-lib": "^4.0" 19 | }, 20 | "require-dev": { 21 | "nunomaduro/larastan": "^2.0", 22 | "orchestra/testbench": "^7.0|^8.0", 23 | "phpunit/phpunit": "^9.5.10", 24 | "roave/security-advisories": "dev-latest" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "ClaudioDekker\\LaravelAuthBladebones\\": "packages/bladebones/src/", 29 | "ClaudioDekker\\LaravelAuth\\": "packages/core/src/", 30 | "ClaudioDekker\\LaravelAuth\\Database\\Factories\\": "packages/core/database/factories/" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "ClaudioDekker\\LaravelAuthBladebones\\Tests\\": "packages/bladebones/tests/", 36 | "ClaudioDekker\\LaravelAuth\\Tests\\": "packages/core/tests" 37 | } 38 | }, 39 | "extra": { 40 | "laravel": { 41 | "providers": [ 42 | "ClaudioDekker\\LaravelAuthBladebones\\LaravelAuthBladebonesServiceProvider", 43 | "ClaudioDekker\\LaravelAuth\\LaravelAuthServiceProvider" 44 | ] 45 | } 46 | }, 47 | "replace": { 48 | "claudiodekker/laravel-auth-bladebones": "self.version", 49 | "claudiodekker/laravel-auth-core": "self.version" 50 | }, 51 | "minimum-stability": "dev", 52 | "prefer-stable": true 53 | } 54 | -------------------------------------------------------------------------------- /packages/bladebones/.github/workflows/close-pull-request.yml: -------------------------------------------------------------------------------- 1 | name: Close Pull Request 2 | 3 | on: 4 | pull_request_target: 5 | types: [opened] 6 | 7 | jobs: 8 | run: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: superbrothers/close-pull-request@v3 12 | with: 13 | comment: "Thank you for your pull request. However, you have submitted this PR on a read-only sub split repository of `claudiodekker/laravel-auth`. Please submit your PR on the https://github.com/claudiodekker/laravel-auth repository.

Thanks!" 14 | -------------------------------------------------------------------------------- /packages/bladebones/.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /.vscode 3 | /vendor 4 | .phpunit.result.cache 5 | composer.lock 6 | -------------------------------------------------------------------------------- /packages/bladebones/LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Claudio Dekker 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /packages/bladebones/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "claudiodekker/laravel-auth-bladebones", 3 | "description": "Rich (yet bare) authentication scaffolding for any blade-based Laravel application.", 4 | "license": "MIT", 5 | "homepage": "https://github.com/claudiodekker/laravel-auth", 6 | "support": { 7 | "issues": "https://github.com/claudiodekker/laravel-auth/issues", 8 | "source": "https://github.com/claudiodekker/laravel-auth" 9 | }, 10 | "keywords": [ 11 | "laravel", 12 | "auth", 13 | "authentication", 14 | "scaffolding", 15 | "blade", 16 | "barebones", 17 | "template" 18 | ], 19 | "authors": [ 20 | { 21 | "name": "Claudio Dekker", 22 | "email": "claudio@ubient.net" 23 | } 24 | ], 25 | "require": { 26 | "php": "~8.1.0|~8.2.0", 27 | "laravel/framework": "^9.33|^10.0", 28 | "claudiodekker/laravel-auth-core": "^0.2.0" 29 | }, 30 | "require-dev": { 31 | "roave/security-advisories": "dev-latest", 32 | "orchestra/testbench": "^7.0|^8.0", 33 | "phpunit/phpunit": "^9.5.10" 34 | }, 35 | "autoload": { 36 | "psr-4": { 37 | "ClaudioDekker\\LaravelAuthBladebones\\": "src/" 38 | } 39 | }, 40 | "autoload-dev": { 41 | "psr-4": { 42 | "ClaudioDekker\\LaravelAuthBladebones\\Tests\\": "tests/" 43 | } 44 | }, 45 | "scripts": { 46 | "test": "vendor/bin/phpunit" 47 | }, 48 | "extra": { 49 | "laravel": { 50 | "providers": [ 51 | "ClaudioDekker\\LaravelAuthBladebones\\LaravelAuthBladebonesServiceProvider" 52 | ] 53 | } 54 | }, 55 | "config": { 56 | "sort-packages": true 57 | }, 58 | "minimum-stability": "dev", 59 | "prefer-stable": true 60 | } 61 | -------------------------------------------------------------------------------- /packages/bladebones/phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | ./tests/Feature 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /packages/bladebones/src/Console/GenerateCommand.php: -------------------------------------------------------------------------------- 1 | copy('routes/web.stub', base_path('routes/web.php')); 23 | } 24 | 25 | /** 26 | * Installs the package's authentication tests. 27 | */ 28 | protected function installTests(): void 29 | { 30 | parent::installTests(); 31 | 32 | $this->generate('Tests.AuthenticationTest', base_path('tests/Feature/AuthenticationTest.php')); 33 | } 34 | 35 | /** 36 | * Installs the package's authentication views. 37 | */ 38 | protected function installViews(): void 39 | { 40 | $this->copy('views/challenges/multi_factor.blade.stub', resource_path('views/auth/challenges/multi_factor.blade.php')); 41 | $this->copy('views/challenges/recovery.blade.stub', resource_path('views/auth/challenges/recovery.blade.php')); 42 | $this->copy('views/challenges/sudo_mode.blade.stub', resource_path('views/auth/challenges/sudo_mode.blade.php')); 43 | $this->copy('views/home.blade.stub', resource_path('views/home.blade.php')); 44 | $this->copy('views/login.blade.stub', resource_path('views/auth/login.blade.php')); 45 | $this->copy('views/recover-account.blade.stub', resource_path('views/auth/recover-account.blade.php')); 46 | $this->copy('views/register.blade.stub', resource_path('views/auth/register.blade.php')); 47 | $this->copy('views/settings/confirm_public_key.blade.stub', resource_path('views/auth/settings/confirm_public_key.blade.php')); 48 | $this->copy('views/settings/confirm_recovery_codes.blade.stub', resource_path('views/auth/settings/confirm_recovery_codes.blade.php')); 49 | $this->copy('views/settings/confirm_totp.blade.stub', resource_path('views/auth/settings/confirm_totp.blade.php')); 50 | $this->copy('views/settings/credentials.blade.stub', resource_path('views/auth/settings/credentials.blade.php')); 51 | $this->copy('views/settings/recovery_codes.blade.stub', resource_path('views/auth/settings/recovery_codes.blade.php')); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /packages/bladebones/src/LaravelAuthBladebonesServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 16 | $this->commands(GenerateCommand::class); 17 | } 18 | } 19 | 20 | /** 21 | * Register the service provider. 22 | */ 23 | public function register(): void 24 | { 25 | // 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/BladeViewTests.php: -------------------------------------------------------------------------------- 1 | generateUser(['recovery_codes' => ['H4PFK-ENVZV', 'PIPIM-7LTUT', 'GPP13-AEXMR', 'WGAHD-95VNQ', 'BSFYG-VFG2N', 'AWOPQ-NWYJX', '2PVJM-QHPBM', 'STR7J-5ND0P']]); 13 | $token = Password::getRepository()->create($user); 14 | 15 | $response = $this->get(route('recover-account.challenge', [ 16 | 'token' => $token, 17 | 'email' => $user->getEmailForPasswordReset(), 18 | ])); 19 | 20 | $response->assertViewIs('auth.challenges.recovery'); 21 | $this->assertSame($token, $response->viewData('token')); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/AccountRecoveryRequestViewTests.php: -------------------------------------------------------------------------------- 1 | get(route('recover-account')); 11 | 12 | $response->assertViewIs('auth.recover-account'); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/CredentialsOverviewViewTests.php: -------------------------------------------------------------------------------- 1 | generateUser(); 13 | $totpOne = LaravelAuth::multiFactorCredentialModel()::factory()->totp()->forUser($user)->create(); 14 | $totpTwo = LaravelAuth::multiFactorCredentialModel()::factory()->totp()->forUser($user)->create(); 15 | $pubKeyOne = LaravelAuth::multiFactorCredentialModel()::factory()->publicKey()->forUser($user)->create(); 16 | $this->enableSudoMode(); 17 | 18 | $response = $this->actingAs($user) 19 | ->get(route('auth.settings')); 20 | 21 | $response->assertViewIs('auth.settings.credentials'); 22 | $this->assertCount(2, $response->viewData('totpCredentials')); 23 | $this->assertTrue($totpOne->is($response->viewData('totpCredentials')[0])); 24 | $this->assertTrue($totpTwo->is($response->viewData('totpCredentials')[1])); 25 | $this->assertCount(1, $response->viewData('publicKeyCredentials')); 26 | $this->assertTrue($pubKeyOne->is($response->viewData('publicKeyCredentials')[0])); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/LoginViewTests.php: -------------------------------------------------------------------------------- 1 | get(route('login')); 14 | 15 | /** @var PublicKeyCredentialRequestOptions $options */ 16 | $this->assertInstanceOf(PublicKeyCredentialRequestOptions::class, $options = unserialize(Session::get('auth.login.passkey_authentication_options'), [PublicKeyCredentialRequestOptions::class])); 17 | $response->assertViewIs('auth.login'); 18 | $response->assertViewHas('options', $options); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/MultiFactorChallengeViewTests.php: -------------------------------------------------------------------------------- 1 | assertSame($redirectsTo, Session::get('url.intended')); 18 | $user = $this->generateUser(); 19 | LaravelAuth::multiFactorCredentialModel()::factory()->publicKey()->forUser($user)->create(); 20 | LaravelAuth::multiFactorCredentialModel()::factory()->publicKey()->forUser($user)->create(); 21 | LaravelAuth::multiFactorCredentialModel()::factory()->totp()->forUser($user)->create(); 22 | $this->preAuthenticate($user); 23 | $this->assertNull(Session::get('url.intended')); 24 | 25 | $response = $this->get(route('login.challenge')); 26 | 27 | /** @var PublicKeyCredentialRequestOptions $options */ 28 | $this->assertInstanceOf(PublicKeyCredentialRequestOptions::class, $options = unserialize(Session::get('laravel-auth::public_key_challenge_request_options'), [PublicKeyCredentialRequestOptions::class])); 29 | 30 | $response->assertViewIs('auth.challenges.multi_factor'); 31 | $response->assertViewHas('availableMethods'); 32 | $response->assertViewHas('intendedLocation', $redirectsTo); 33 | $response->assertViewHas('options', $options); 34 | $this->assertCount(2, $response->viewData('availableMethods')); 35 | $this->assertSame(CredentialType::PUBLIC_KEY, $response->viewData('availableMethods')[0]); 36 | $this->assertSame(CredentialType::TOTP, $response->viewData('availableMethods')[1]); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/RegisterPublicKeyCredentialViewTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 14 | 15 | $response = $this->actingAs($this->generateUser()) 16 | ->get(route('auth.credentials.register_public_key')); 17 | 18 | /** @var PublicKeyCredentialCreationOptions $options */ 19 | $this->assertInstanceOf(PublicKeyCredentialCreationOptions::class, $options = unserialize(Session::get('auth.mfa_setup.public_key_credential_creation_options'), [PublicKeyCredentialCreationOptions::class])); 20 | 21 | $response->assertViewIs('auth.settings.confirm_public_key'); 22 | $response->assertViewHas('options', $options); 23 | $response->assertViewHas('randomName'); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/RegisterTotpCredentialViewTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 13 | Session::put('auth.mfa_setup.pending_totp_secret', 'test'); 14 | 15 | $response = $this->actingAs($this->generateUser()) 16 | ->get(route('auth.credentials.register_totp.confirm')); 17 | 18 | $response->assertViewIs('auth.settings.confirm_totp'); 19 | $response->assertViewHas('qrImage'); 20 | $response->assertViewHas('randomName'); 21 | $response->assertViewHas('secret', 'test'); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/RegisterViewTests.php: -------------------------------------------------------------------------------- 1 | get(route('register')); 11 | 12 | $response->assertViewIs('auth.register'); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /packages/bladebones/src/Testing/Partials/SudoModeChallengeViewTests.php: -------------------------------------------------------------------------------- 1 | unix()); 14 | $user = $this->generateUser(); 15 | 16 | $response = $this->actingAs($user) 17 | ->get(route('auth.sudo_mode')); 18 | 19 | $response->assertViewIs('auth.challenges.sudo_mode'); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /packages/bladebones/stubs/defaults/views/challenges/recovery.blade.stub: -------------------------------------------------------------------------------- 1 |

Account Recovery

2 |

Recovery code

3 | 4 | @if ($errors->any()) 5 | 10 | @endif 11 | 12 |
13 | 14 | 15 | 19 | 22 |
23 | -------------------------------------------------------------------------------- /packages/bladebones/stubs/defaults/views/home.blade.stub: -------------------------------------------------------------------------------- 1 |

Authenticated as {{ Auth::user()->name }}

2 | 3 | @if (($indicator = Auth::user()->accountSecurityIndicator()) && $indicator->hasIssues()) 4 |

{{ $indicator->message() }}

5 | @endif 6 | 7 | View Authentication Settings 8 | 9 |
10 | 11 | 12 | 15 |
16 | -------------------------------------------------------------------------------- /packages/bladebones/stubs/defaults/views/recover-account.blade.stub: -------------------------------------------------------------------------------- 1 |
2 |

You are using the barebones authentication views.

3 |

4 | Don't worry, you didn't forget to run npm run dev or some other build process, and the installation of laravel-auth finished successfully.
5 | These views are intentionally kept extremely basic, to make it easier for you to understand the bare minimum required code, and to customize it to your own liking, without having to remove a bunch of default styling first.

6 | 7 | If you want prettier default views, you can require and install a view-preset package (such as the inertia one, which internally extends the laravel-auth package) instead. 8 |

9 |
10 | 11 | @if (session('status')) 12 | {{ session('status') }} 13 | @endif 14 | 15 |

Recover Account

16 | Log in 17 |

18 | 19 | @if ($errors->any()) 20 | 25 | @endif 26 | 27 |
28 | 29 | 30 | 34 | 37 |
38 | -------------------------------------------------------------------------------- /packages/bladebones/stubs/defaults/views/settings/confirm_recovery_codes.blade.stub: -------------------------------------------------------------------------------- 1 |

Confirm Account Recovery Codes

2 | 3 |

4 | To prevent you from getting locked out of your account, as well as to make sure you have the correct codes, please confirm one of them below. 5 |

6 | 7 | @if ($errors->any()) 8 | 13 | @endif 14 | 15 |
16 | 17 | 21 | 24 |
25 | -------------------------------------------------------------------------------- /packages/bladebones/stubs/defaults/views/settings/confirm_totp.blade.stub: -------------------------------------------------------------------------------- 1 |

Register a new multi-factor authenticator

2 | 3 | Scannable QR Code 4 | 5 |
    6 |
  1. 7 | Download your preferred two-factor authenticator application.
    8 | If you don't already have one, we recommend using a cloud-based TOTP app such as 9 | 1Password, 10 | Authy, or 11 | Microsoft Authenticator. 12 |
  2. 13 |
  3. 14 | Scan this QR-code with your two-factor authentication application.
    15 | If you are unable to scan the QR code, please use this secret instead: {{ $secret }} 16 |
  4. 17 |
  5. 18 | The application should now display a six-digit code. Please enter this code in the form below, and click "Confirm". 19 |
  6. 20 |
21 | 22 | @if ($errors->any()) 23 | 28 | @endif 29 | 30 |
31 | 32 | 36 | 40 | 43 |
44 | -------------------------------------------------------------------------------- /packages/bladebones/stubs/defaults/views/settings/recovery_codes.blade.stub: -------------------------------------------------------------------------------- 1 |

Account Recovery Codes

2 | 3 |

4 | Treat your recovery codes with the same level of attention as you would your password!
5 | We recommend saving these in a password manager, or alternatively to print them out and keep them safe.
6 | If you lose your recovery codes, you will not be able to recover your account! 7 |

8 | 9 | 14 | 15 | Download recovery codes
16 | Print recovery codes
17 | 18 |
19 | 20 |
21 | 24 |
25 | 26 | 45 | -------------------------------------------------------------------------------- /packages/bladebones/templates/Controllers/Settings/ChangePasswordController.bladetmpl: -------------------------------------------------------------------------------- 1 | namespace App\Http\Controllers\Auth\Settings; 2 | 3 | use ClaudioDekker\LaravelAuth\Http\Controllers\Settings\ChangePasswordController as BaseController; 4 | use Illuminate\Http\RedirectResponse; 5 | use Illuminate\Http\Request; 6 | 7 | class ChangePasswordController extends BaseController 8 | { 9 | /** 10 | * Change the current user's password. 11 | * 12 | * {!! '@' !!}see static::sendPasswordChangedResponse() 13 | */ 14 | public function update(Request $request): RedirectResponse 15 | { 16 | return parent::update($request); 17 | } 18 | 19 | /** 20 | * Send a response indicating that the user's password has been changed. 21 | */ 22 | protected function sendPasswordChangedResponse(Request $request): RedirectResponse 23 | { 24 | if (property_exists($this, 'redirectTo')) { 25 | return redirect()->intended($this->redirectTo) 26 | ->with('status', __('laravel-auth::auth.settings.password-changed')); 27 | } 28 | 29 | return redirect()->route('auth.settings') 30 | ->with('status', __('laravel-auth::auth.settings.password-changed')); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /packages/bladebones/templates/Controllers/Settings/CredentialsController.bladetmpl: -------------------------------------------------------------------------------- 1 | namespace App\Http\Controllers\Auth\Settings; 2 | 3 | use ClaudioDekker\LaravelAuth\CredentialType; 4 | use ClaudioDekker\LaravelAuth\Http\Controllers\Settings\CredentialsController as BaseController; 5 | use ClaudioDekker\LaravelAuth\LaravelAuth; 6 | use Illuminate\Contracts\View\View; 7 | use Illuminate\Database\Eloquent\ModelNotFoundException; 8 | use Illuminate\Http\RedirectResponse; 9 | use Illuminate\Http\Request; 10 | use Illuminate\Support\Collection; 11 | 12 | class CredentialsController extends BaseController 13 | { 14 | /** 15 | * Display an overview of all security-related settings. 16 | * 17 | * {!! '@' !!}see static::sendOverviewPageResponse() 18 | */ 19 | public function index(Request $request): View 20 | { 21 | return parent::index($request); 22 | } 23 | 24 | /** 25 | * Delete a multi-factor credential. 26 | * 27 | * {!! '@' !!}see static::sendCredentialNotFoundResponse() 28 | * {!! '@' !!}see static::sendCredentialDeletedResponse() 29 | * 30 | * {!! '@' !!}param string $id 31 | */ 32 | public function destroy(Request $request, mixed $id): RedirectResponse 33 | { 34 | return parent::destroy($request, $id); 35 | } 36 | 37 | /** 38 | * Sends a response that displays the credential overview page. 39 | */ 40 | protected function sendOverviewPageResponse(Request $request, Collection $mfaCredentials): View 41 | { 42 | $groupedCredentials = $mfaCredentials->groupBy(fn ($credential) => $credential->type->value); 43 | 44 | return view('auth.settings.credentials', [ 45 | 'totpCredentials' => $groupedCredentials->get(CredentialType::TOTP->value, new Collection()), 46 | 'publicKeyCredentials' => $groupedCredentials->get(CredentialType::PUBLIC_KEY->value, new Collection()), 47 | ]); 48 | } 49 | 50 | /** 51 | * Sends a response indicating that the multi-factor credential could not be found. 52 | * 53 | * {!! '@' !!}param string $id 54 | * 55 | * {!! '@' !!}throws \Illuminate\Database\Eloquent\ModelNotFoundException 56 | */ 57 | protected function sendCredentialNotFoundResponse(Request $request, mixed $id): void 58 | { 59 | throw (new ModelNotFoundException())->setModel( 60 | LaravelAuth::multiFactorCredentialModel(), 61 | $id 62 | ); 63 | } 64 | 65 | /** 66 | * Sends a response indicating that the multi-factor credential was deleted. 67 | * 68 | * {!! '@' !!}param \ClaudioDekker\LaravelAuth\MultiFactorCredential $credential 69 | */ 70 | protected function sendCredentialDeletedResponse(Request $request, $credential): RedirectResponse 71 | { 72 | return redirect()->route('auth.settings') 73 | ->with('status', __('laravel-auth::auth.settings.credential-deleted')); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /packages/bladebones/templates/Controllers/VerifyEmailController.bladetmpl: -------------------------------------------------------------------------------- 1 | @php 2 | $flavorTrait = str_replace("-", "", \Illuminate\Support\Str::title($flavor)); 3 | @endphp 4 | 5 | namespace App\Http\Controllers\Auth; 6 | 7 | use App\Providers\RouteServiceProvider; 8 | use ClaudioDekker\LaravelAuth\Http\Controllers\VerifyEmailController as BaseController; 9 | use Illuminate\Foundation\Auth\EmailVerificationRequest; 10 | use Illuminate\Http\RedirectResponse; 11 | use Illuminate\Http\Request; 12 | 13 | class VerifyEmailController extends BaseController 14 | { 15 | /** 16 | * Handle an incoming request to (re)send the verification email. 17 | * 18 | * {!! '@' !!}see static::sendEmailAlreadyVerifiedResponse() 19 | * {!! '@' !!}see static::sendEmailVerificationSentResponse() 20 | */ 21 | public function store(Request $request): RedirectResponse 22 | { 23 | return parent::store($request); 24 | } 25 | 26 | /** 27 | * Handle an incoming request to confirm the email verification. 28 | * 29 | * {!! '@' !!}see static::sendEmailAlreadyVerifiedResponse() 30 | * {!! '@' !!}see static::sendEmailSuccessfullyVerifiedResponse() 31 | */ 32 | public function update(EmailVerificationRequest $request): RedirectResponse 33 | { 34 | return parent::update($request); 35 | } 36 | 37 | /** 38 | * Sends a response indicating that the email verification link has been resent. 39 | */ 40 | protected function sendEmailVerificationSentResponse(Request $request): RedirectResponse 41 | { 42 | return redirect()->route('auth.settings') 43 | ->with('status', __('laravel-auth::auth.verification.sent')); 44 | } 45 | 46 | /** 47 | * Sends a response indicating that the email has already been verified. 48 | */ 49 | protected function sendEmailAlreadyVerifiedResponse(Request $request): RedirectResponse 50 | { 51 | return redirect()->route('auth.settings') 52 | ->with('status', __('laravel-auth::auth.verification.already-verified')); 53 | } 54 | 55 | /** 56 | * Sends a response indicating that the email has been successfully verified. 57 | */ 58 | protected function sendEmailSuccessfullyVerifiedResponse(Request $request): RedirectResponse 59 | { 60 | return redirect()->to(RouteServiceProvider::HOME ?? '/') 61 | ->with('status', __('laravel-auth::auth.verification.verified')); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /packages/bladebones/templates/Tests/AuthenticationTest.bladetmpl: -------------------------------------------------------------------------------- 1 | @php 2 | $verificationTrait = $withoutEmailVerification ? "RegisterWithoutVerificationEmailTests" : "RegisterWithVerificationEmailTests"; 3 | $flavorTrait = str_replace("-", "", \Illuminate\Support\Str::title($flavor)); 4 | @endphp 5 | namespace Tests\Feature; 6 | 7 | use ClaudioDekker\LaravelAuth\Testing\AccountRecoveryChallengeTests; 8 | use ClaudioDekker\LaravelAuth\Testing\AccountRecoveryRequestTests; 9 | use ClaudioDekker\LaravelAuth\Testing\EmailVerification\{{ $verificationTrait }}; 10 | use ClaudioDekker\LaravelAuth\Testing\EmailVerificationTests; 11 | use ClaudioDekker\LaravelAuth\Testing\Flavors\{{ $flavorTrait }}; 12 | use ClaudioDekker\LaravelAuth\Testing\GenerateRecoveryCodesTests; 13 | use ClaudioDekker\LaravelAuth\Testing\LoginTests; 14 | use ClaudioDekker\LaravelAuth\Testing\LogoutTests; 15 | use ClaudioDekker\LaravelAuth\Testing\MultiFactorChallengeTests; 16 | use ClaudioDekker\LaravelAuth\Testing\RegisterPublicKeyCredentialTests; 17 | use ClaudioDekker\LaravelAuth\Testing\RegisterTotpCredentialTests; 18 | use ClaudioDekker\LaravelAuth\Testing\RegistrationTests; 19 | use ClaudioDekker\LaravelAuth\Testing\RemoveCredentialTests; 20 | use ClaudioDekker\LaravelAuth\Testing\SubmitChangePasswordTests; 21 | use ClaudioDekker\LaravelAuth\Testing\SudoModeChallengeTests; 22 | use ClaudioDekker\LaravelAuth\Testing\ViewCredentialsOverviewPageTests; 23 | @if (! $withoutViews) 24 | use ClaudioDekker\LaravelAuthBladebones\Testing\BladeViewTests; 25 | @endif 26 | use Illuminate\Foundation\Testing\RefreshDatabase; 27 | use Tests\TestCase; 28 | 29 | class AuthenticationTest extends TestCase 30 | { 31 | use RefreshDatabase; 32 | 33 | // Configuration Mixins 34 | @php 35 | $mixins = [ 36 | $flavorTrait, 37 | $verificationTrait 38 | ]; 39 | 40 | if (! $withoutViews) { 41 | $mixins[] = "BladeViewTests"; 42 | } 43 | 44 | asort($mixins); 45 | @endphp 46 | @foreach($mixins as $mixin) 47 | use {{ $mixin }}; 48 | @endforeach 49 | 50 | // Basic Auth 51 | use AccountRecoveryRequestTests; 52 | use RegistrationTests; 53 | use LoginTests; 54 | use LogoutTests; 55 | 56 | // Challenges 57 | use AccountRecoveryChallengeTests; 58 | use MultiFactorChallengeTests; 59 | use SudoModeChallengeTests; 60 | 61 | // Settings 62 | use ViewCredentialsOverviewPageTests; 63 | use EmailVerificationTests; 64 | use GenerateRecoveryCodesTests; 65 | use SubmitChangePasswordTests; 66 | use RegisterPublicKeyCredentialTests; 67 | use RegisterTotpCredentialTests; 68 | use RemoveCredentialTests; 69 | 70 | protected function setUp(): void 71 | { 72 | parent::setUp(); 73 | 74 | $this->useInstantlyResolvingTimebox(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /packages/bladebones/tests/TestCase.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | protected function getPackageProviders($app) 17 | { 18 | return [ 19 | LaravelAuthBladebonesServiceProvider::class, 20 | ]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/core/.github/workflows/close-pull-request.yml: -------------------------------------------------------------------------------- 1 | name: Close Pull Request 2 | 3 | on: 4 | pull_request_target: 5 | types: [opened] 6 | 7 | jobs: 8 | run: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: superbrothers/close-pull-request@v3 12 | with: 13 | comment: "Thank you for your pull request. However, you have submitted this PR on a read-only sub split repository of `claudiodekker/laravel-auth`. Please submit your PR on the https://github.com/claudiodekker/laravel-auth repository.

Thanks!" 14 | -------------------------------------------------------------------------------- /packages/core/.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /.vscode 3 | /vendor 4 | .php-cs-fixer.cache 5 | .php-cs-fixer.php 6 | .phpunit.result.cache 7 | composer.lock 8 | -------------------------------------------------------------------------------- /packages/core/LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Claudio Dekker 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /packages/core/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "claudiodekker/laravel-auth-core", 3 | "description": "Rich authentication logic for your Laravel applications.", 4 | "license": "MIT", 5 | "homepage": "https://github.com/claudiodekker/laravel-auth", 6 | "support": { 7 | "issues": "https://github.com/claudiodekker/laravel-auth/issues", 8 | "source": "https://github.com/claudiodekker/laravel-auth" 9 | }, 10 | "authors": [ 11 | { 12 | "name": "Claudio Dekker", 13 | "email": "claudio@ubient.net" 14 | } 15 | ], 16 | "require": { 17 | "php": "~8.1.0|~8.2.0", 18 | "bacon/bacon-qr-code": "^2.0", 19 | "claudiodekker/word-generator": "^1.0", 20 | "laravel/framework": "^9.33|^10.0", 21 | "nyholm/psr7": "^1.5", 22 | "pragmarx/google2fa": "^8.0", 23 | "symfony/psr-http-message-bridge": "^2.1", 24 | "web-auth/webauthn-lib": "^4.0" 25 | }, 26 | "require-dev": { 27 | "roave/security-advisories": "dev-latest", 28 | "orchestra/testbench": "^7.0|^8.0", 29 | "phpunit/phpunit": "^9.5.10" 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "ClaudioDekker\\LaravelAuth\\": "src/", 34 | "ClaudioDekker\\LaravelAuth\\Database\\Factories\\": "database/factories/" 35 | } 36 | }, 37 | "autoload-dev": { 38 | "psr-4": { 39 | "ClaudioDekker\\LaravelAuth\\Tests\\": "tests" 40 | } 41 | }, 42 | "scripts": { 43 | "test": "vendor/bin/phpunit" 44 | }, 45 | "extra": { 46 | "laravel": { 47 | "providers": [ 48 | "ClaudioDekker\\LaravelAuth\\LaravelAuthServiceProvider" 49 | ] 50 | } 51 | }, 52 | "config": { 53 | "sort-packages": true 54 | }, 55 | "minimum-stability": "dev", 56 | "prefer-stable": true 57 | } 58 | -------------------------------------------------------------------------------- /packages/core/database/factories/MultiFactorCredentialFactory.php: -------------------------------------------------------------------------------- 1 | fn () => 'unknown-'.Str::orderedUuid(), 31 | 'name' => $this->faker->ean13(), 32 | 'type' => fn () => Arr::random([CredentialType::TOTP, CredentialType::PUBLIC_KEY]), 33 | 'secret' => 'super-secret-value', 34 | 'created_at' => $this->faker->dateTime(), 35 | 'user_id' => fn () => LaravelAuth::userModel()::factory(), 36 | ]; 37 | } 38 | 39 | /** 40 | * Update the Factory state to generate a token for the specified user. 41 | */ 42 | public function forUser(Authenticatable $user): self 43 | { 44 | return $this->state(['user_id' => $user]); 45 | } 46 | 47 | /** 48 | * Update the Factory state to generate a time-based one-time-password credential. 49 | */ 50 | public function totp(): self 51 | { 52 | return $this->state([ 53 | 'id' => fn () => CredentialType::TOTP->value.'-'.Str::orderedUuid(), 54 | 'type' => CredentialType::TOTP, 55 | 'secret' => function () { 56 | $shuffled = str_shuffle('KRUGS4ZAON2HE2LOM4QHEZLBNRWHSIDJONXCO5BAMFWGYIDUNBQXIIDJNZ2GK4TFON2GS3THFQQHI4TVON2CA3LFFY'); 57 | 58 | return substr($shuffled, 0, 32); 59 | }, 60 | ]); 61 | } 62 | 63 | /** 64 | * Update the Factory state to generate a public key credential. 65 | */ 66 | public function publicKey(): self 67 | { 68 | return $this->state([ 69 | 'id' => fn () => CredentialType::PUBLIC_KEY->value.'-'.Str::orderedUuid(), 70 | 'type' => CredentialType::PUBLIC_KEY, 71 | 'secret' => '{"id":"mMihuIx9LukswxBOMjMHDf6EAONOy7qdWhaQQ7dOtViR2cVB\/MNbZxURi2cvgSvKSILb3mISe9lPNG9sYgojuY5iNinYOg6hRVxmm0VssuNG2pm1+RIuTF9DUtEJZEEK","publicKey":"pQECAyYgASFYIBw\/HArIcANWNOBOxq3hH8lrHo9a17nQDxlqwybjDpHEIlggu3QUKIbALqsGuHfJI3LTKJSNmk0YCFb5oz1hjJidRMk=","signCount":0,"userHandle":"1","transports":[]}', 72 | ]); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /packages/core/database/migrations/2022_02_08_000002_create_multi_factor_credentials_table.php: -------------------------------------------------------------------------------- 1 | string('id')->primary(); 18 | $table->string('type'); 19 | $table->unsignedBigInteger('user_id')->nullable()->index(); 20 | $table->string('name'); 21 | $table->text('secret'); 22 | $table->timestamp('created_at')->nullable(); 23 | }); 24 | } 25 | 26 | /** 27 | * Reverse the migrations. 28 | * 29 | * @return void 30 | */ 31 | public function down() 32 | { 33 | Schema::dropIfExists('multi_factor_credentials'); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /packages/core/lang/en/auth.php: -------------------------------------------------------------------------------- 1 | 'These credentials do not match our records.', 17 | 'password' => 'The provided password is incorrect.', 18 | 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', 19 | 20 | 'success' => 'You have been successfully authenticated.', 21 | 'challenge' => [ 22 | 'public-key' => 'The provided public key credential is incorrect.', 23 | 'recovery' => 'The provided recovery code is incorrect.', 24 | 'throttle' => 'Too many confirmation attempts. Please try again in :seconds seconds.', 25 | 'totp' => 'The provided one-time-password code is incorrect.', 26 | ], 27 | 'settings' => [ 28 | 'credential-deleted' => 'The multi-factor credential has been deleted.', 29 | 'password-changed' => 'Your password has been changed successfully.', 30 | 'public-key-registered' => 'Public key credential successfully registered.', 31 | 'recovery-configured' => 'Account recovery codes successfully configured.', 32 | 'totp-registered' => 'Time-based one-time-password credential successfully registered.', 33 | ], 34 | 'recovery' => [ 35 | 'sent' => 'If the provided email address is associated with an account, you will receive a recovery link shortly.', 36 | 'throttle' => 'Too many recovery requests. Please try again in :seconds seconds.', 37 | ], 38 | 'verification' => [ 39 | 'already-verified' => 'Your email address has already been verified.', 40 | 'sent' => 'A verification link has been sent to the email address you provided during registration.', 41 | 'verified' => 'Your email address has been verified.', 42 | ], 43 | 'security-indicator' => [ 44 | 'no-mfa-no-recovery-codes' => 'Your account is vulnerable. Please enable multi-factor authentication and set up account recovery codes.', 45 | 'no-mfa-has-recovery-codes' => 'Your account is vulnerable without multi-factor authentication. Please enable it to secure your account.', 46 | 'has-mfa-no-recovery-codes' => 'Your account could be compromised if someone gains access to your email account. Protect yourself by setting up account recovery codes.', 47 | 'has-mfa-has-recovery-codes' => 'Your account is well-protected.', 48 | ], 49 | ]; 50 | -------------------------------------------------------------------------------- /packages/core/phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | ./tests/Unit 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /packages/core/src/CredentialType.php: -------------------------------------------------------------------------------- 1 | logout($request); 25 | 26 | return $this->sendLoggedOutResponse($request); 27 | } 28 | 29 | /** 30 | * Sign the user out of the application. 31 | */ 32 | protected function logout(Request $request): void 33 | { 34 | Auth::logoutCurrentDevice(); 35 | 36 | $request->session()->invalidate(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /packages/core/src/Http/Concerns/InteractsWithRateLimiting.php: -------------------------------------------------------------------------------- 1 | by('ip::'.$request->ip()), 35 | ]; 36 | } 37 | 38 | /** 39 | * Determines whether the request is currently rate limited. 40 | */ 41 | protected function isCurrentlyRateLimited(Request $request): bool 42 | { 43 | return Collection::make($this->rateLimits($request))->contains(function (Limit $limit) { 44 | return RateLimiter::tooManyAttempts($this->throttleKey($limit->key), $limit->maxAttempts); 45 | }); 46 | } 47 | 48 | /** 49 | * Determines the seconds remaining until rate limiting is lifted. 50 | */ 51 | protected function rateLimitExpiresInSeconds(Request $request): int 52 | { 53 | return Collection::make($this->rateLimits($request)) 54 | ->max(fn (Limit $limit) => RateLimiter::availableIn($this->throttleKey($limit->key))); 55 | } 56 | 57 | /** 58 | * Increments the rate limiting counter. 59 | */ 60 | protected function incrementRateLimitingCounter(Request $request): void 61 | { 62 | Collection::make($this->rateLimits($request))->each(function (Limit $limit) { 63 | RateLimiter::hit($this->throttleKey($limit->key), $limit->decayMinutes * 60); 64 | }); 65 | } 66 | 67 | /** 68 | * Clears the rate limiting counter (if any). 69 | */ 70 | protected function resetRateLimitingCounter(Request $request): void 71 | { 72 | Collection::make($this->rateLimits($request)) 73 | ->filter(fn (Limit $limit) => $limit->key) 74 | ->each(fn (Limit $limit) => RateLimiter::clear($this->throttleKey($limit->key))); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /packages/core/src/Http/Concerns/Registration/PasswordBasedRegistration.php: -------------------------------------------------------------------------------- 1 | isCurrentlyRateLimited($request)) { 28 | $this->emitLockoutEvent($request); 29 | 30 | return $this->sendRateLimitedResponse($request, $this->rateLimitExpiresInSeconds($request)); 31 | } 32 | 33 | $this->incrementRateLimitingCounter($request); 34 | 35 | return App::make(Timebox::class)->call(function (Timebox $timebox) use ($request) { 36 | $this->validatePasswordBasedRequest($request); 37 | 38 | $user = $this->createPasswordBasedUser($request); 39 | 40 | $this->emitRegisteredEvent($user); 41 | $this->sendEmailVerificationNotification($user); 42 | $this->authenticate($user); 43 | $this->enableSudoMode($request); 44 | $this->resetRateLimitingCounter($request); 45 | $timebox->returnEarly(); 46 | 47 | return $this->sendRegisteredResponse($request, $user); 48 | }, 300 * 1000); 49 | } 50 | 51 | /** 52 | * Validate a password based user registration request. 53 | * 54 | * @throws \Illuminate\Validation\ValidationException 55 | */ 56 | protected function validatePasswordBasedRequest(Request $request): void 57 | { 58 | $request->validate([ 59 | ...$this->registrationValidationRules(), 60 | 'name' => ['required', 'string', 'max:255'], 61 | 'password' => ['required', 'confirmed', Password::defaults()], 62 | ]); 63 | } 64 | 65 | /** 66 | * Create a password based user account using the given details. 67 | */ 68 | protected function createPasswordBasedUser(Request $request): Authenticatable 69 | { 70 | /** @var \Illuminate\Database\Eloquent\Builder $query */ 71 | $query = LaravelAuth::userModel()::query(); 72 | 73 | return $query->create([ 74 | 'email' => $request->input('email'), 75 | $this->usernameField() => $request->input($this->usernameField()), 76 | 'name' => $request->name, 77 | 'password' => Hash::make($request->password), 78 | 'has_password' => true, 79 | ]); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /packages/core/src/Http/Controllers/Settings/ChangePasswordController.php: -------------------------------------------------------------------------------- 1 | validatePasswordChangeRequest($request); 31 | 32 | $user = $request->user(); 33 | 34 | $this->updateUserPassword($user, $request->input('new_password')); 35 | $this->emitPasswordChangedEvent($user); 36 | 37 | return $this->sendPasswordChangedResponse($request); 38 | } 39 | 40 | /** 41 | * Validate the password change request. 42 | * 43 | * @throws \Illuminate\Validation\ValidationException 44 | */ 45 | protected function validatePasswordChangeRequest(Request $request): void 46 | { 47 | $request->validate([ 48 | 'current_password' => ['required', 'current_password'], 49 | 'new_password' => ['required', 'confirmed', Password::defaults()], 50 | ]); 51 | } 52 | 53 | /** 54 | * Change the user's password and persist it to the database. 55 | */ 56 | protected function updateUserPassword(Authenticatable $user, string $newPassword): void 57 | { 58 | $user->forceFill([ 59 | 'password' => Hash::make($newPassword), 60 | ])->save(); 61 | } 62 | 63 | /** 64 | * Emits an event indicating that the user's password has changed. 65 | */ 66 | protected function emitPasswordChangedEvent(Authenticatable $user): void 67 | { 68 | Event::dispatch(new PasswordChanged($user)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /packages/core/src/Http/Middleware/EnsurePasswordBasedUser.php: -------------------------------------------------------------------------------- 1 | hasSession(), 501); 18 | abort_if(! $request->user(), 401); 19 | abort_if(! $request->user()->has_password, 403); 20 | 21 | return $next($request); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /packages/core/src/Http/Middleware/EnsurePreAuthenticated.php: -------------------------------------------------------------------------------- 1 | hasSession() || $request->session()->missing('auth.mfa.user_id')) { 18 | return redirect()->route('login'); 19 | } 20 | 21 | return $next($request); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /packages/core/src/Http/Middleware/EnsureSudoMode.php: -------------------------------------------------------------------------------- 1 | hasSession(), 501); 35 | 36 | $timestamp = $request->session()->get(self::CONFIRMED_AT_KEY, 0); 37 | 38 | if (Carbon::parse($timestamp)->diffInSeconds() < config('laravel-auth.sudo_mode_duration', 900)) { 39 | $request->session()->put(self::CONFIRMED_AT_KEY, Carbon::now()->unix()); 40 | 41 | return $next($request); 42 | } 43 | 44 | Event::dispatch(new SudoModeChallenged($request, $request->user())); 45 | 46 | $request->session()->forget(self::CONFIRMED_AT_KEY); 47 | $request->session()->put(self::REQUIRED_AT_KEY, Carbon::now()->unix()); 48 | 49 | return $request->expectsJson() 50 | ? response()->json(['message' => 'Sudo-mode required.'], 403) 51 | : redirect()->guest(route('auth.sudo_mode')); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /packages/core/src/Http/Mixins/Challenges/PasswordChallenge.php: -------------------------------------------------------------------------------- 1 | isCurrentlyRateLimited($request)) { 37 | $this->emitLockoutEvent($request); 38 | 39 | return $this->sendRateLimitedResponse($request, $this->rateLimitExpiresInSeconds($request)); 40 | } 41 | 42 | $this->incrementRateLimitingCounter($request); 43 | 44 | return App::make(Timebox::class)->call(function (Timebox $timebox) use ($request) { 45 | $this->validatePasswordChallengeRequest($request); 46 | 47 | if (! $this->hasValidPassword($request)) { 48 | return $this->sendPasswordChallengeFailedResponse($request); 49 | } 50 | 51 | $this->resetRateLimitingCounter($request); 52 | $timebox->returnEarly(); 53 | 54 | return $this->sendPasswordChallengeSuccessfulResponse($request); 55 | }, 300 * 1000); 56 | } 57 | 58 | /** 59 | * Validate the password challenge confirmation request. 60 | * 61 | * @throws \Illuminate\Validation\ValidationException 62 | */ 63 | protected function validatePasswordChallengeRequest(Request $request): void 64 | { 65 | $request->validate([ 66 | 'password' => 'required|string', 67 | ]); 68 | } 69 | 70 | /** 71 | * Determine whether the provided password matches the current user. 72 | */ 73 | protected function hasValidPassword(Request $request): bool 74 | { 75 | return Auth::validate([ 76 | 'id' => Auth::id(), 77 | 'password' => $request->input('password'), 78 | ]); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /packages/core/src/Http/Mixins/EnablesSudoMode.php: -------------------------------------------------------------------------------- 1 | session()->put(EnsureSudoMode::CONFIRMED_AT_KEY, now()->unix()); 16 | $request->session()->forget(EnsureSudoMode::REQUIRED_AT_KEY); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /packages/core/src/Http/Modifiers/EmailBased.php: -------------------------------------------------------------------------------- 1 | usernameField() => ['required', 'max:255', 'unique:users', 'email'], 22 | ]; 23 | } 24 | 25 | /** 26 | * Any flavor-specific validation rules used to validate an authentication request. 27 | */ 28 | protected function authenticationValidationRules(): array 29 | { 30 | return [ 31 | $this->usernameField() => ['required', 'email'], 32 | ]; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /packages/core/src/Http/Modifiers/UsernameBased.php: -------------------------------------------------------------------------------- 1 | usernameField() => ['required', 'max:255', 'unique:users'], 22 | 'email' => ['required', 'max:255', 'email'], 23 | ]; 24 | } 25 | 26 | /** 27 | * Any flavor-specific validation rules used to validate an authentication request. 28 | */ 29 | protected function authenticationValidationRules(): array 30 | { 31 | return [ 32 | $this->usernameField() => ['required'], 33 | ]; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /packages/core/src/Http/Modifiers/WithoutVerificationEmail.php: -------------------------------------------------------------------------------- 1 | registerResources(); 19 | $this->registerMigrations(); 20 | $this->registerPublishing(); 21 | } 22 | 23 | /** 24 | * Register the service provider. 25 | */ 26 | public function register(): void 27 | { 28 | $this->mergeConfigFrom(__DIR__.'/../config/laravel-auth.php', 'laravel-auth'); 29 | 30 | $this->app->bind(TotpContract::class, GoogleTwoFactorAuthenticator::class); 31 | $this->app->bind(WebAuthnContract::class, SpomkyWebAuthn::class); 32 | } 33 | 34 | /** 35 | * Register the Laravel Auth resources. 36 | */ 37 | protected function registerResources(): void 38 | { 39 | $this->loadTranslationsFrom(__DIR__.'/../lang', 'laravel-auth'); 40 | } 41 | 42 | /** 43 | * Register the Laravel Auth migration files. 44 | */ 45 | protected function registerMigrations(): void 46 | { 47 | if ($this->app->runningInConsole() && LaravelAuth::$runsMigrations) { 48 | $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); 49 | } 50 | } 51 | 52 | /** 53 | * Register the package's publishable resources. 54 | */ 55 | protected function registerPublishing(): void 56 | { 57 | if ($this->app->runningInConsole()) { 58 | $this->publishes([ 59 | __DIR__.'/../config/laravel-auth.php' => config_path('laravel-auth.php'), 60 | ], 'laravel-auth-config'); 61 | 62 | $this->publishes([ 63 | __DIR__.'/../lang' => lang_path('vendor/laravel-auth'), 64 | ], 'laravel-auth-translations'); 65 | 66 | $this->publishes([ 67 | __DIR__.'/../database/migrations' => database_path('migrations'), 68 | ], 'laravel-auth-migrations'); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /packages/core/src/Methods/Totp/Contracts/TotpContract.php: -------------------------------------------------------------------------------- 1 | engine->generateSecretKey(32); 35 | } catch (Google2FAException $e) { 36 | throw new InvalidSecretException($e->getMessage()); 37 | } 38 | } 39 | 40 | /** 41 | * Verify whether the given time-based one-time-password is valid for the given secret. 42 | * If the code is valid, we'll mark it as used as to prevent replay attacks. 43 | * 44 | * @param int $userId 45 | */ 46 | public function verify(mixed $userId, string $secret, string $code): bool 47 | { 48 | $cacheKey = 'auth.mfa.totp_timestamps.'.$userId; 49 | 50 | try { 51 | $timestamp = $this->engine->verifyKeyNewer($secret, $code, $this->cache->get($cacheKey)); 52 | } catch (Google2FAException|CacheException) { 53 | return false; 54 | } 55 | 56 | if ($timestamp === false) { 57 | return false; 58 | } 59 | 60 | $this->cache->put($cacheKey, $timestamp, $this->engine->getWindow() * 60); 61 | 62 | return true; 63 | } 64 | 65 | /** 66 | * Generate a QR Code Image instance for the given secret and owner. 67 | */ 68 | public function toQrImage(string $secret, string $holder): QrImage 69 | { 70 | $url = $this->engine->getQRCodeUrl( 71 | Config::get('app.name'), 72 | $holder, 73 | $secret, 74 | ); 75 | 76 | return QrImage::make($url); 77 | } 78 | 79 | /** 80 | * Generates a currently valid time-based one-time-password for the given secret. 81 | * This method is only intended to be used within your tests. 82 | * 83 | * @throws \ClaudioDekker\LaravelAuth\Methods\Totp\Exceptions\InvalidSecretException 84 | */ 85 | public function testCode(string $secret): string 86 | { 87 | try { 88 | return $this->engine->getCurrentOtp($secret); 89 | } catch (Google2FAException $e) { 90 | throw new InvalidSecretException($e->getMessage()); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /packages/core/src/Methods/WebAuthn/Contracts/WebAuthnContract.php: -------------------------------------------------------------------------------- 1 | getAuthenticatorAttachment(); 18 | $residentKey = $criteria->getResidentKey(); 19 | 20 | return new static( 21 | is_null($authenticatorAttachment) ? null : AuthenticatorAttachment::from($authenticatorAttachment), 22 | ResidentKeyRequirement::tryFrom($residentKey) ?? ResidentKeyRequirement::PREFERRED, 23 | UserVerificationRequirement::from($criteria->getUserVerification()) 24 | ); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /packages/core/src/Methods/WebAuthn/SpomkyAdapter/PublicKeyCredentialDescriptor.php: -------------------------------------------------------------------------------- 1 | getType()), 20 | $descriptor->getId(), 21 | new AuthenticatorTransports( 22 | ...Collection::make($descriptor->getTransports()) 23 | ->map(fn (string $transport) => AuthenticatorTransport::from($transport)) 24 | ->all() 25 | ) 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /packages/core/src/Methods/WebAuthn/SpomkyAdapter/PublicKeyCredentialParameters.php: -------------------------------------------------------------------------------- 1 | getType()), 18 | COSEAlgorithmIdentifier::from($parameters->getAlg()), 19 | ); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /packages/core/src/Methods/WebAuthn/SpomkyAdapter/PublicKeyCredentialRequestOptions.php: -------------------------------------------------------------------------------- 1 | getChallenge(), 21 | $options->getTimeout(), 22 | $options->getRpId(), 23 | new PublicKeyCredentialDescriptors( 24 | ...Collection::make($options->getAllowCredentials()) 25 | ->map(fn (\Webauthn\PublicKeyCredentialDescriptor $descriptor) => PublicKeyCredentialDescriptor::fromSpomky($descriptor)) 26 | ->all() 27 | ), 28 | UserVerificationRequirement::tryFrom($options->getUserVerification() ?? UserVerificationRequirement::PREFERRED->value), 29 | new AuthenticationExtensionsClientInputs( 30 | ...Collection::make($options->getExtensions()) 31 | ->map(fn (\Webauthn\AuthenticationExtensions\AuthenticationExtension $extension) => new ClientExtension( 32 | $extension->name(), 33 | $extension->value() 34 | )) 35 | ->all() 36 | ) 37 | ); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /packages/core/src/Methods/WebAuthn/SpomkyAdapter/PublicKeyCredentialRpEntity.php: -------------------------------------------------------------------------------- 1 | getId(), $rp->getName()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /packages/core/src/Methods/WebAuthn/SpomkyAdapter/PublicKeyCredentialSourceRepository.php: -------------------------------------------------------------------------------- 1 | query() 18 | ->where('type', CredentialType::PUBLIC_KEY) 19 | ->find(CredentialType::PUBLIC_KEY->value.'-'.Base64UrlSafe::encodeUnpadded($publicKeyCredentialId)); 20 | 21 | if ($credential === null) { 22 | return null; 23 | } 24 | 25 | $attributes = CredentialAttributes::fromJson($credential->secret); 26 | 27 | // A lot of the following fields are not required as per the RFC, but are required by the Spomky implementation. 28 | // https://www.w3.org/TR/webauthn-2/#sctn-registering-a-new-credential (step 25) 29 | // https://www.w3.org/TR/webauthn-2/#sctn-verifying-assertion 30 | return \Webauthn\PublicKeyCredentialSource::create( 31 | $attributes->id(), 32 | \Webauthn\PublicKeyCredentialDescriptor::CREDENTIAL_TYPE_PUBLIC_KEY, 33 | array_map(static fn (AuthenticatorTransport $transport) => $transport->value, $attributes->transports()->all()), 34 | 'invalid', 35 | new \Webauthn\TrustPath\EmptyTrustPath(), 36 | new NilUlid(), 37 | $attributes->publicKey(), 38 | $attributes->userHandle(), 39 | $attributes->signCount() 40 | ); 41 | } 42 | 43 | /** 44 | * @return \WebAuthn\PublicKeyCredentialSource[] 45 | */ 46 | public function findAllForUserEntity(\Webauthn\PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity): array 47 | { 48 | throw new LogicException('Not implemented (unused).'); 49 | } 50 | 51 | public function saveCredentialSource(\Webauthn\PublicKeyCredentialSource $publicKeyCredentialSource): void 52 | { 53 | // Spomky calls this method internally as to provide a way to store update the credential's counter. 54 | // However, it also returns the same credential data directly after, and since we prefer to give 55 | // the developer as much control as possible over managing database calls, we'll just ignore 56 | // this method, and will call an update method ourselves on the controller-level instead. 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /packages/core/src/Methods/WebAuthn/SpomkyAdapter/PublicKeyCredentialUserEntity.php: -------------------------------------------------------------------------------- 1 | getId(), $user->getName(), $user->getDisplayName()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /packages/core/src/MultiFactorCredential.php: -------------------------------------------------------------------------------- 1 | 'datetime', 42 | 'secret' => 'encrypted', 43 | 'type' => CredentialType::class, 44 | ]; 45 | 46 | /** 47 | * The guarded attributes on the model. 48 | * 49 | * @var array 50 | */ 51 | protected $guarded = []; 52 | 53 | /** 54 | * The name of the "updated at" column. 55 | * 56 | * @var string|null 57 | */ 58 | public const UPDATED_AT = null; 59 | 60 | /** 61 | * The attributes that should be hidden for serialization. 62 | * 63 | * @var array 64 | */ 65 | protected $hidden = [ 66 | 'secret', 67 | ]; 68 | 69 | /** 70 | * Create a new factory instance for the model. 71 | */ 72 | protected static function newFactory(): Factory 73 | { 74 | return MultiFactorCredentialFactory::new(); 75 | } 76 | 77 | /** 78 | * Get the user that the Multi-Factor Registration belongs to. 79 | * 80 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo 81 | */ 82 | public function user() 83 | { 84 | return $this->belongsTo( 85 | LaravelAuth::userModel(), 86 | 'user_id', 87 | LaravelAuth::user()->getKeyName() 88 | ); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /packages/core/src/Notifications/AccountRecoveryNotification.php: -------------------------------------------------------------------------------- 1 | subject(Lang::get('Account Recovery Notification')) 24 | ->line(Lang::get('You are receiving this email because we received a request to regain access to your account.')) 25 | ->action('Recover Account', $this->resetUrl($notifiable)) 26 | ->line(Lang::get('This recovery link will expire in :count minutes.', ['count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')])) 27 | ->line(Lang::get('If you did not request the recovery of your account, you do not need to take any further action and can safely disregard this email.')); 28 | } 29 | 30 | /** 31 | * Get the reset URL for the given notifiable. 32 | * 33 | * @param mixed $notifiable 34 | * @return string 35 | */ 36 | protected function resetUrl($notifiable) 37 | { 38 | return url(route('recover-account.challenge', [ 39 | 'token' => $this->token, 40 | 'email' => $notifiable->getEmailForPasswordReset(), 41 | ], false)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /packages/core/src/RecoveryCodeManager.php: -------------------------------------------------------------------------------- 1 | codes = Collection::make($codes); 25 | } 26 | 27 | /** 28 | * Create a new recovery code manager instance from existing codes. 29 | */ 30 | public static function from(array $codes): static 31 | { 32 | return new static($codes); 33 | } 34 | 35 | /** 36 | * Generate a fresh batch of recovery codes. 37 | */ 38 | public static function generate(): static 39 | { 40 | return new static(Collection::times(8, static fn () => Str::random(10)) 41 | ->map(fn ($code) => strtoupper($code)) 42 | ->map(fn ($code) => chunk_split($code, 5, '-')) 43 | ->map(fn ($code) => substr($code, 0, -1)) 44 | ->toArray() 45 | ); 46 | } 47 | 48 | /** 49 | * Determine whether the provided codes are identical. 50 | */ 51 | protected function isIdentical(string $expected, string $provided): bool 52 | { 53 | return strtoupper(Str::remove('-', $expected)) === strtoupper(Str::remove('-', $provided)); 54 | } 55 | 56 | /** 57 | * Determine whether the provided code exists in the collection. 58 | */ 59 | public function contains(string $code): bool 60 | { 61 | return $this->codes->contains(fn ($entry) => $this->isIdentical($code, $entry)); 62 | } 63 | 64 | /** 65 | * Remove the provided code from the collection. 66 | * 67 | * @return $this 68 | */ 69 | public function remove(string $code): self 70 | { 71 | $this->codes = $this->codes->filter(fn ($entry) => ! $this->isIdentical($code, $entry)); 72 | 73 | return $this; 74 | } 75 | 76 | /** 77 | * Get the recovery codes as an array. 78 | */ 79 | public function toArray(): array 80 | { 81 | return $this->codes->values()->toArray(); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/AttestedCredentialData.php: -------------------------------------------------------------------------------- 1 | aaguid; 27 | } 28 | 29 | /** 30 | * Byte length L of Credential ID, 16-bit unsigned big-endian integer. 31 | * 32 | * @link https://www.w3.org/TR/webauthn-2/#credentialid 33 | */ 34 | public function credentialIdLength(): int 35 | { 36 | return strlen($this->credentialId); 37 | } 38 | 39 | /** 40 | * The credential ID. 41 | * 42 | * @link https://www.w3.org/TR/webauthn-2/#credentialid 43 | */ 44 | public function credentialId(): string 45 | { 46 | return $this->credentialId; 47 | } 48 | 49 | /** 50 | * The credential public key. 51 | * 52 | * The credential public key encoded in COSE_Key format, as defined in Section 7 53 | * of [RFC8152], using the CTAP2 canonical CBOR encoding form. 54 | * 55 | * The COSE_Key-encoded credential public key MUST contain the "alg" parameter 56 | * and MUST NOT contain any other OPTIONAL parameters. The "alg" parameter 57 | * MUST contain a COSEAlgorithmIdentifier value. 58 | * 59 | * The encoded credential public key MUST also contain any additional REQUIRED parameters 60 | * stipulated by the relevant key type specification, i.e., REQUIRED for the 61 | * key type "kty" and algorithm "alg" (see Section 8 of [RFC8152]). 62 | * 63 | * @link https://www.w3.org/TR/webauthn-2/#credentialpublickey 64 | * @link https://www.w3.org/TR/webauthn-2/#credential-public-key 65 | * @link https://tools.ietf.org/html/rfc8152#section-7 66 | * @link https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#ctap2-canonical-cbor-encoding-form 67 | * @link https://www.w3.org/TR/webauthn-2/#typedefdef-cosealgorithmidentifier 68 | * @link https://www.w3.org/TR/webauthn-2/#biblio-rfc8152 69 | */ 70 | public function credentialPublicKey(): ?string 71 | { 72 | return $this->credentialPublicKey; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/AuthenticatorData.php: -------------------------------------------------------------------------------- 1 | rpIdHash; 32 | } 33 | 34 | /** 35 | * @link https://www.w3.org/TR/webauthn-2/#flags 36 | * @see AuthenticatorDataFlags 37 | */ 38 | public function flags(): AuthenticatorDataFlags 39 | { 40 | return $this->flags; 41 | } 42 | 43 | /** 44 | * Signature counter, 32-bit unsigned big-endian integer. 45 | * 46 | * @link https://www.w3.org/TR/webauthn-2/#signcount 47 | * @link https://www.w3.org/TR/webauthn-2/#signature-counter 48 | */ 49 | public function signCount(): int 50 | { 51 | return $this->signCount; 52 | } 53 | 54 | /** 55 | * Attested credential data (if present). 56 | * 57 | * See § 6.5.1 Attested Credential Data for details. 58 | * Its length depends on the length of the credential ID and credential public key being attested. 59 | * 60 | * @link https://www.w3.org/TR/webauthn-2/#attestedcredentialdata 61 | * @link https://www.w3.org/TR/webauthn-2/#sctn-attested-credential-data 62 | */ 63 | public function attestedCredentialData(): ?AttestedCredentialData 64 | { 65 | return $this->attestedCredentialData; 66 | } 67 | 68 | /** 69 | * Extension-defined authenticator data. 70 | * 71 | * This is a CBOR [RFC8949] map with extension identifiers as keys, and authenticator 72 | * extension outputs as values. See § 9 WebAuthn Extensions for details. 73 | * 74 | * @link https://www.w3.org/TR/webauthn-2/#authdataextensions 75 | * @link https://www.w3.org/TR/webauthn-2/#sctn-extensions 76 | */ 77 | public function extensions(): ?AuthenticationExtensionsClientOutputs 78 | { 79 | return $this->extensions; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/ClientExtension.php: -------------------------------------------------------------------------------- 1 | key; 21 | } 22 | 23 | public function value(): mixed 24 | { 25 | return $this->value; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Dictionaries/AuthenticationExtensionsClientInputs.php: -------------------------------------------------------------------------------- 1 | set($value); 26 | } 27 | } 28 | 29 | /** 30 | * Set a new item in the collection. 31 | * 32 | * @return $this 33 | */ 34 | public function set(ClientExtension $value): static 35 | { 36 | $this->inputs[$value->key()] = $value; 37 | 38 | return $this; 39 | } 40 | 41 | /** 42 | * Get all of the items in the collection. 43 | * 44 | * @return ClientExtension[] 45 | */ 46 | public function all(): array 47 | { 48 | return $this->inputs; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Dictionaries/PublicKeyCredentialDescriptor.php: -------------------------------------------------------------------------------- 1 | type; 31 | } 32 | 33 | /** 34 | * The credential ID of the public key credential the caller is referring to. 35 | * 36 | * @link https://www.w3.org/TR/webauthn-2/#dom-publickeycredentialdescriptor-id 37 | */ 38 | public function id(): string 39 | { 40 | return $this->id; 41 | } 42 | 43 | /** 44 | * A hint as to how the client might communicate with the managing authenticator 45 | * of the public key credential the caller is referring to. 46 | * 47 | * @link https://www.w3.org/TR/webauthn-2/#dom-publickeycredentialdescriptor-transports 48 | */ 49 | public function transports(): AuthenticatorTransports 50 | { 51 | return $this->transports; 52 | } 53 | 54 | /** 55 | * Convert the object into something JSON serializable. 56 | */ 57 | public function jsonSerialize(): array 58 | { 59 | $data = [ 60 | 'type' => $this->type()->value, 61 | 'id' => Base64UrlSafe::encodeUnpadded($this->id()), 62 | ]; 63 | 64 | if (count($transports = $this->transports()->jsonSerialize()) > 0) { 65 | $data['transports'] = $transports; 66 | } 67 | 68 | return $data; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Dictionaries/PublicKeyCredentialParameters.php: -------------------------------------------------------------------------------- 1 | type; 29 | } 30 | 31 | /** 32 | * The the cryptographic signature algorithm with which the newly generated credential will be used, 33 | * and thus also the type of asymmetric key pair to be generated, e.g., RSA or Elliptic Curve. 34 | * 35 | * @link https://www.w3.org/TR/webauthn-2/#dom-publickeycredentialparameters-alg 36 | */ 37 | public function alg(): COSEAlgorithmIdentifier 38 | { 39 | return $this->alg; 40 | } 41 | 42 | /** 43 | * Convert the object into something JSON serializable. 44 | */ 45 | public function jsonSerialize(): array 46 | { 47 | return [ 48 | 'type' => $this->type()->value, 49 | 'alg' => $this->alg()->value, 50 | ]; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Dictionaries/PublicKeyCredentialRpEntity.php: -------------------------------------------------------------------------------- 1 | id; 38 | } 39 | 40 | /** 41 | * A human-palatable identifier for the Relying Party. 42 | * 43 | * It is intended only for display. For example, "ACME Corporation", 44 | * "Wonderful Widgets, Inc." or "ОАО Примертех". 45 | * 46 | * @link https://www.w3.org/TR/webauthn-2/#dictdef-publickeycredentialentity 47 | * @link https://www.w3.org/TR/webauthn-2/#dom-publickeycredentialentity-name 48 | */ 49 | public function name(): string 50 | { 51 | return $this->name; 52 | } 53 | 54 | /** 55 | * Convert the object into something JSON serializable. 56 | */ 57 | public function jsonSerialize(): array 58 | { 59 | $data = ['name' => $this->name()]; 60 | 61 | if (! is_null($id = $this->id())) { 62 | $data['id'] = $id; 63 | } 64 | 65 | return $data; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Dictionaries/PublicKeyCredentialUserEntity.php: -------------------------------------------------------------------------------- 1 | name; 34 | } 35 | 36 | /** 37 | * The user handle of the user account entity. 38 | * 39 | * To ensure secure operation, authentication and authorization decisions MUST be 40 | * made on the basis of this id member. Not meant to be displayed to the user. 41 | * 42 | * @link https://www.w3.org/TR/webauthn-2/#dom-publickeycredentialuserentity-id 43 | */ 44 | public function id(): string 45 | { 46 | return $this->id; 47 | } 48 | 49 | /** 50 | * A human-palatable name for the user account. 51 | * 52 | * It is intended only for display. For example, "Alex Müller" or "田中倫". 53 | * The Relying Party SHOULD let the user choose this, and SHOULD NOT 54 | * restrict the choice more than necessary. 55 | * 56 | * @link https://www.w3.org/TR/webauthn-2/#dom-publickeycredentialuserentity-displayname 57 | */ 58 | public function displayName(): string 59 | { 60 | return $this->displayName; 61 | } 62 | 63 | /** 64 | * Convert the object into something JSON serializable. 65 | */ 66 | public function jsonSerialize(): array 67 | { 68 | return [ 69 | 'name' => $this->name(), 70 | 'id' => Base64UrlSafe::encodeUnpadded($this->id()), 71 | 'displayName' => $this->displayName(), 72 | ]; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Enums/AttestationConveyancePreference.php: -------------------------------------------------------------------------------- 1 | flags; 26 | } 27 | 28 | /** 29 | * Bit 0: User Present (UP) result. 30 | * 31 | * - 1 means the user is present. 32 | * - 0 means the user is not present. 33 | * 34 | * @link https://www.w3.org/TR/webauthn-2/#concept-user-present 35 | * @link https://www.w3.org/TR/webauthn-2/#up 36 | */ 37 | public function isUserPresent(): bool 38 | { 39 | return 0 !== (ord($this->flags) & AuthenticatorDataBit::USER_PRESENT->value); 40 | } 41 | 42 | /** 43 | * Bit 1: Reserved for future use (RFU1). 44 | */ 45 | public function isReservedForFutureUse1(): int 46 | { 47 | return ord($this->flags) & AuthenticatorDataBit::RESERVED_FUTURE_USE_RFU1->value; 48 | } 49 | 50 | /** 51 | * Bit 2: User Verified (UV) result. 52 | * 53 | * - 1 means the user is verified. 54 | * - 0 means the user is not verified. 55 | * 56 | * @link https://www.w3.org/TR/webauthn-2/#concept-user-verified 57 | * @link https://www.w3.org/TR/webauthn-2/#uv 58 | */ 59 | public function isUserVerified(): bool 60 | { 61 | return 0 !== (ord($this->flags) & AuthenticatorDataBit::USER_VERIFIED->value); 62 | } 63 | 64 | /** 65 | * Bits 3-5: Reserved for future use (RFU2). 66 | */ 67 | public function isReservedForFutureUse2(): int 68 | { 69 | return ord($this->flags) & AuthenticatorDataBit::RESERVED_FUTURE_USE_RFU2->value; 70 | } 71 | 72 | /** 73 | * Bit 6: Attested credential data included (AT). 74 | * 75 | * Indicates whether the authenticator added attested credential data. 76 | * 77 | * @link https://www.w3.org/TR/webauthn-2/#attested-credential-data 78 | */ 79 | public function hasAttestedCredentialData(): bool 80 | { 81 | return 0 !== (ord($this->flags) & AuthenticatorDataBit::ATTESTED_CREDENTIAL_DATA->value); 82 | } 83 | 84 | /** 85 | * Bit 7: Extension data included (ED). 86 | * 87 | * Indicates if the authenticator data has extensions. 88 | * 89 | * @link https://www.w3.org/TR/webauthn-2/#authenticator-data 90 | * @link https://www.w3.org/TR/webauthn-2/#authdataextensions 91 | */ 92 | public function hasExtensions(): bool 93 | { 94 | return 0 !== (ord($this->flags) & AuthenticatorDataBit::EXTENSION_DATA_INCLUDED->value); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Helpers/Enums/AuthenticatorDataBit.php: -------------------------------------------------------------------------------- 1 | add($transport); 28 | } 29 | } 30 | 31 | /** 32 | * Add a new item to the array. 33 | * 34 | * @return $this 35 | */ 36 | public function add(AuthenticatorTransport $transport): static 37 | { 38 | $this->transports[] = $transport; 39 | 40 | return $this; 41 | } 42 | 43 | /** 44 | * Get all of the items in the array. 45 | * 46 | * @return AuthenticatorTransport[] 47 | */ 48 | public function all(): array 49 | { 50 | return $this->transports; 51 | } 52 | 53 | /** 54 | * Convert the object into something JSON serializable. 55 | */ 56 | public function jsonSerialize(): mixed 57 | { 58 | return array_map(static fn (AuthenticatorTransport $transport) => $transport->value, $this->all()); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Helpers/TypeSafeArrays/PublicKeyCredentialDescriptors.php: -------------------------------------------------------------------------------- 1 | set($descriptor); 28 | } 29 | } 30 | 31 | /** 32 | * Set a new item in the array. 33 | */ 34 | public function set(PublicKeyCredentialDescriptor $descriptor): static 35 | { 36 | $this->descriptors[$descriptor->id()] = $descriptor; 37 | 38 | return $this; 39 | } 40 | 41 | /** 42 | * Get all of the items in the array. 43 | * 44 | * @return PublicKeyCredentialDescriptor[] 45 | */ 46 | public function all(): array 47 | { 48 | return array_values($this->descriptors); 49 | } 50 | 51 | /** 52 | * Convert the object into something JSON serializable. 53 | */ 54 | public function jsonSerialize(): mixed 55 | { 56 | return array_map(static fn (PublicKeyCredentialDescriptor $descriptor) => $descriptor->jsonSerialize(), $this->all()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /packages/core/src/Specifications/WebAuthn/Helpers/TypeSafeArrays/PublicKeyCredentialParametersCollection.php: -------------------------------------------------------------------------------- 1 | add($parameter); 27 | } 28 | } 29 | 30 | /** 31 | * Add a new item to the array. 32 | * 33 | * @return $this 34 | */ 35 | public function add(PublicKeyCredentialParameters $parameter): static 36 | { 37 | $this->parameters[] = $parameter; 38 | 39 | return $this; 40 | } 41 | 42 | /** 43 | * Get all of the items in the array. 44 | * 45 | * @return PublicKeyCredentialParameters[] 46 | */ 47 | public function all(): array 48 | { 49 | return $this->parameters; 50 | } 51 | 52 | /** 53 | * Convert the object into something JSON serializable. 54 | */ 55 | public function jsonSerialize(): mixed 56 | { 57 | return array_map(static fn (PublicKeyCredentialParameters $params) => $params->jsonSerialize(), $this->all()); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /packages/core/src/Support/AccountSecurityIndicator.php: -------------------------------------------------------------------------------- 1 | 'RED', 21 | self::HAS_MFA_NO_RECOVERY_CODES => 'ORANGE', 22 | self::HAS_MFA_HAS_RECOVERY_CODES => 'GREEN', 23 | }; 24 | } 25 | 26 | /** 27 | * Determine whether the account security indicator has any issues to indicate. 28 | */ 29 | public function hasIssues(): bool 30 | { 31 | return $this->color() !== 'GREEN'; 32 | } 33 | 34 | /** 35 | * Determine the message that should be displayed for the indicator. 36 | */ 37 | public function message(): string 38 | { 39 | return match ($this) { 40 | self::NO_MFA_NO_RECOVERY_CODES => __('laravel-auth::auth.security-indicator.no-mfa-no-recovery-codes'), 41 | self::NO_MFA_HAS_RECOVERY_CODES => __('laravel-auth::auth.security-indicator.no-mfa-has-recovery-codes'), 42 | self::HAS_MFA_NO_RECOVERY_CODES => __('laravel-auth::auth.security-indicator.has-mfa-no-recovery-codes'), 43 | self::HAS_MFA_HAS_RECOVERY_CODES => __('laravel-auth::auth.security-indicator.has-mfa-has-recovery-codes'), 44 | }; 45 | } 46 | 47 | /** 48 | * Get the instance as an array. 49 | * 50 | * @return array 51 | */ 52 | public function toArray() 53 | { 54 | return [ 55 | 'color' => $this->color(), 56 | 'has_issues' => $this->hasIssues(), 57 | 'message' => $this->message(), 58 | ]; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /packages/core/src/Support/QrImage.php: -------------------------------------------------------------------------------- 1 | writeString($this->contents); 50 | } 51 | 52 | /** 53 | * Convert the QR Image to a SVG string, encoded as an image data URI. 54 | * Can be directly embedded in an HTML document src attribute. 55 | * 56 | * @param int[] $rgb 57 | */ 58 | public function svgData(int $size = 400, int $margin = 0, array $rgb = [0, 0, 0]): string 59 | { 60 | return 'data:image/svg+xml;base64,'.base64_encode($this->svg($size, $margin, $rgb)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /packages/core/src/Testing/AccountRecoveryChallengeTests.php: -------------------------------------------------------------------------------- 1 | assertCount(0, LaravelAuth::userModel()::all()); 17 | $this->expectTimeboxWithEarlyReturn(); 18 | 19 | $this->submitPasswordBasedRegisterAttempt(); 20 | 21 | Notification::assertSentTo(LaravelAuth::userModel()::first(), VerifyEmail::class); 22 | } 23 | 24 | /** @test */ 25 | public function it_sends_a_verification_email_for_passkey_based_registration_requests(): void 26 | { 27 | Notification::fake(); 28 | $user = $this->generateUser(['id' => 1, 'has_password' => false]); 29 | $options = $this->mockPasskeyCreationOptions($user); 30 | Session::put('auth.register.passkey_creation_options', serialize($options)); 31 | $this->expectTimeboxWithEarlyReturn(); 32 | 33 | $this->submitPasskeyBasedRegisterAttempt(); 34 | 35 | Notification::assertSentTo($user, VerifyEmail::class); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /packages/core/src/Testing/EmailVerification/RegisterWithoutVerificationEmailTests.php: -------------------------------------------------------------------------------- 1 | assertCount(0, LaravelAuth::userModel()::all()); 16 | $this->expectTimeboxWithEarlyReturn(); 17 | 18 | $this->submitPasswordBasedRegisterAttempt(); 19 | 20 | $this->assertCount(1, LaravelAuth::userModel()::all()); 21 | Notification::assertNothingSent(); 22 | } 23 | 24 | /** @test */ 25 | public function it_does_not_send_a_verification_email_for_passkey_based_registration_requests(): void 26 | { 27 | Notification::fake(); 28 | $user = $this->generateUser(['id' => 1, 'has_password' => false]); 29 | $options = $this->mockPasskeyCreationOptions($user); 30 | Session::put('auth.register.passkey_creation_options', serialize($options)); 31 | $this->expectTimeboxWithEarlyReturn(); 32 | 33 | $this->submitPasskeyBasedRegisterAttempt(); 34 | 35 | $this->assertCount(1, LaravelAuth::multiFactorCredentialModel()::all()); 36 | Notification::assertNothingSent(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Flavors/EmailBased.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf(ValidationException::class, $response->exception); 46 | $this->assertSame([$this->usernameField() => [__('validation.required', ['attribute' => 'email'])]], $response->exception->errors()); 47 | } 48 | 49 | protected function assertUsernameMustBeValidValidationError(TestResponse $response): void 50 | { 51 | $this->assertInstanceOf(ValidationException::class, $response->exception); 52 | $this->assertSame([$this->usernameField() => [__('validation.email', ['attribute' => 'email'])]], $response->exception->errors()); 53 | } 54 | 55 | protected function assertUsernameTooLongValidationError(TestResponse $response): void 56 | { 57 | $this->assertInstanceOf(ValidationException::class, $response->exception); 58 | $this->assertSame([$this->usernameField() => [__('validation.max.string', ['attribute' => 'email', 'max' => 255])]], $response->exception->errors()); 59 | } 60 | 61 | protected function assertUsernameAlreadyExistsValidationError(TestResponse $response): void 62 | { 63 | $this->assertInstanceOf(ValidationException::class, $response->exception); 64 | $this->assertSame([$this->usernameField() => [__('validation.unique', ['attribute' => 'email'])]], $response->exception->errors()); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Flavors/UsernameBased.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf(ValidationException::class, $response->exception); 46 | $this->assertSame([$this->usernameField() => [__('validation.required', ['attribute' => 'username'])]], $response->exception->errors()); 47 | } 48 | 49 | protected function assertUsernameMustBeValidValidationError(TestResponse $response): void 50 | { 51 | $this->assertInstanceOf(ValidationException::class, $response->exception); 52 | $this->assertSame([$this->usernameField() => [__('laravel-auth::auth.failed')]], $response->exception->errors()); 53 | } 54 | 55 | protected function assertUsernameTooLongValidationError(TestResponse $response): void 56 | { 57 | $this->assertInstanceOf(ValidationException::class, $response->exception); 58 | $this->assertSame([$this->usernameField() => [__('validation.max.string', ['attribute' => 'username', 'max' => 255])]], $response->exception->errors()); 59 | } 60 | 61 | protected function assertUsernameAlreadyExistsValidationError(TestResponse $response): void 62 | { 63 | $this->assertInstanceOf(ValidationException::class, $response->exception); 64 | $this->assertSame([$this->usernameField() => [__('validation.unique', ['attribute' => 'username'])]], $response->exception->errors()); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /packages/core/src/Testing/GenerateRecoveryCodesTests.php: -------------------------------------------------------------------------------- 1 | actingAs($this->generateUser()); 13 | Session::put('some_random_key', 'some_random_value'); 14 | 15 | $response = $this->delete(route('logout')); 16 | 17 | $response->assertRedirect(route('login')); 18 | $response->assertSessionMissing('some_random_key'); 19 | $this->assertGuest(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /packages/core/src/Testing/MultiFactorChallengeTests.php: -------------------------------------------------------------------------------- 1 | unix()); 15 | $user = $this->generateUser(); 16 | LaravelAuth::multiFactorCredentialModel()::factory()->publicKey()->forUser($user)->create(); 17 | $this->assertFalse(Session::has('laravel-auth::sudo_mode.public_key_challenge_request_options')); 18 | $this->expectTimebox(); 19 | 20 | $response = $this->actingAs($user)->get(route('auth.sudo_mode')); 21 | 22 | $response->assertOk(); 23 | $response->assertSessionHas('laravel-auth::sudo_mode.public_key_challenge_request_options'); 24 | } 25 | 26 | /** @test */ 27 | public function the_sudo_mode_page_does_not_initialize_a_public_key_challenge_when_the_user_has_no_public_key_credentials(): void 28 | { 29 | Session::put(EnsureSudoMode::REQUIRED_AT_KEY, now()->unix()); 30 | $user = $this->generateUser(); 31 | $this->assertFalse(Session::has('laravel-auth::sudo_mode.public_key_challenge_request_options')); 32 | $this->expectTimebox(); 33 | 34 | $response = $this->actingAs($user)->get(route('auth.sudo_mode')); 35 | 36 | $response->assertOk(); 37 | $response->assertSessionMissing('laravel-auth::sudo_mode.public_key_challenge_request_options'); 38 | } 39 | 40 | /** @test */ 41 | public function the_user_cannot_view_the_sudo_mode_page_directly(): void 42 | { 43 | $user = $this->generateUser(); 44 | 45 | $response = $this->actingAs($user)->get(route('auth.sudo_mode')); 46 | 47 | $response->assertStatus(400); 48 | } 49 | 50 | /** @test */ 51 | public function guests_cannot_view_the_sudo_mode_page(): void 52 | { 53 | $response = $this->get(route('auth.sudo_mode')); 54 | 55 | $response->assertRedirect(route('login')); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/Settings/Recovery/InitializeRecoveryCodesGenerationTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 14 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_recovery_codes')); 15 | 16 | $response = $this->actingAs($this->generateUser()) 17 | ->post(route('auth.settings.generate_recovery')); 18 | 19 | $response->assertOk(); 20 | $this->assertInstanceOf(RecoveryCodeManager::class, $codes = Session::get('auth.mfa_setup.pending_recovery_codes')); 21 | $this->assertCount(8, $codes->toArray()); 22 | } 23 | 24 | /** @test */ 25 | public function the_user_cannot_initialize_the_generation_of_fresh_recovery_codes_when_no_longer_in_sudo_mode(): void 26 | { 27 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_recovery_codes')); 28 | 29 | $response = $this->actingAs($this->generateUser()) 30 | ->post(route('auth.settings.generate_recovery')); 31 | 32 | $response->assertRedirect(route('auth.sudo_mode')); 33 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_recovery_codes')); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/Settings/Recovery/ViewRecoveryCodesGenerationConfirmationPageTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 13 | Session::put('auth.mfa_setup.pending_recovery_codes', ['H4PFK-ENVZV', 'PIPIM-7LTUT', 'GPP13-AEXMR', 'WGAHD-95VNQ', 'BSFYG-VFG2N', 'AWOPQ-NWYJX', '2PVJM-QHPBM', 'STR7J-5ND0P']); 14 | 15 | $response = $this->actingAs($this->generateUser()) 16 | ->get(route('auth.settings.generate_recovery.confirm')); 17 | 18 | $response->assertOk(); 19 | } 20 | 21 | /** @test */ 22 | public function the_user_cannot_view_the_page_used_to_confirm_new_recovery_codes_when_none_have_been_prepared(): void 23 | { 24 | $this->enableSudoMode(); 25 | 26 | $response = $this->actingAs($this->generateUser()) 27 | ->get(route('auth.settings.generate_recovery.confirm')); 28 | 29 | $response->assertStatus(428); 30 | } 31 | 32 | /** @test */ 33 | public function the_user_cannot_view_the_page_used_to_confirm_the_newly_generated_recovery_codes_when_no_longer_in_sudo_mode(): void 34 | { 35 | Session::put('auth.mfa_setup.pending_recovery_codes', ['H4PFK-ENVZV', 'PIPIM-7LTUT', 'GPP13-AEXMR', 'WGAHD-95VNQ', 'BSFYG-VFG2N', 'AWOPQ-NWYJX', '2PVJM-QHPBM', 'STR7J-5ND0P']); 36 | 37 | $response = $this->actingAs($this->generateUser()) 38 | ->get(route('auth.settings.generate_recovery.confirm')); 39 | 40 | $response->assertRedirect(route('auth.sudo_mode')); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/Settings/Totp/CancelTotpCredentialRegistrationTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 15 | Session::put('auth.mfa_setup.pending_totp_secret', App::make(Authenticator::class)->generateSecret()); 16 | 17 | $response = $this->actingAs($this->generateUser()) 18 | ->delete(route('auth.credentials.register_totp')); 19 | 20 | $response->assertRedirect(route('auth.settings')); 21 | $this->assertFalse(Session::has('auth.mfa_setup.pending_totp_secret')); 22 | } 23 | 24 | /** @test */ 25 | public function the_user_cannot_cancel_the_time_based_one_time_password_credential_registration_process_when_no_longer_in_sudo_mode(): void 26 | { 27 | Session::put('auth.mfa_setup.pending_totp_secret', App::make(Authenticator::class)->generateSecret()); 28 | 29 | $response = $this->actingAs($this->generateUser()) 30 | ->delete(route('auth.credentials.register_totp')); 31 | 32 | $response->assertRedirect(route('auth.sudo_mode')); 33 | $this->assertTrue(Session::has('auth.mfa_setup.pending_totp_secret')); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/Settings/Totp/InitializeTotpCredentialRegistrationTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 13 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_totp_secret')); 14 | 15 | $response = $this->actingAs($this->generateUser()) 16 | ->post(route('auth.credentials.register_totp')); 17 | 18 | $response->assertRedirect(route('auth.credentials.register_totp.confirm')); 19 | $this->assertIsString(Session::get('auth.mfa_setup.pending_totp_secret')); 20 | $this->assertSame(32, strlen(Session::get('auth.mfa_setup.pending_totp_secret'))); 21 | } 22 | 23 | /** @test */ 24 | public function the_user_cannot_initialize_a_new_one_time_based_time_password_credential_registration_process_when_no_longer_in_sudo_mode(): void 25 | { 26 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_totp_secret')); 27 | 28 | $response = $this->actingAs($this->generateUser()) 29 | ->post(route('auth.credentials.register_totp')); 30 | 31 | $response->assertRedirect(route('auth.sudo_mode')); 32 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_totp_secret')); 33 | } 34 | 35 | /** @test */ 36 | public function a_new_one_time_based_time_password_credential_registration_process_cannot_be_initialized_when_the_user_is_not_password_based(): void 37 | { 38 | $this->enableSudoMode(); 39 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_totp_secret')); 40 | 41 | $response = $this->actingAs($this->generateUser(['has_password' => false])) 42 | ->post(route('auth.credentials.register_totp')); 43 | 44 | $response->assertForbidden(); 45 | $this->assertTrue(Session::missing('auth.mfa_setup.pending_totp_secret')); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/Settings/Totp/ViewTotpCredentialRegistrationConfirmationPageTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 13 | Session::put('auth.mfa_setup.pending_totp_secret', 'test'); 14 | 15 | $response = $this->actingAs($this->generateUser()) 16 | ->get(route('auth.credentials.register_totp.confirm')); 17 | 18 | $response->assertOk(); 19 | } 20 | 21 | /** @test */ 22 | public function the_user_cannot_view_the_time_based_one_time_password_credential_registration_confirmation_page_when_none_is_being_registered(): void 23 | { 24 | $this->enableSudoMode(); 25 | 26 | $response = $this->actingAs($this->generateUser()) 27 | ->get(route('auth.credentials.register_totp.confirm')); 28 | 29 | $response->assertStatus(428); 30 | } 31 | 32 | /** @test */ 33 | public function the_user_cannot_view_the_time_based_one_time_password_credential_registration_confirmation_page_when_no_longer_in_sudo_mode(): void 34 | { 35 | Session::put('auth.mfa_setup.pending_totp_secret', 'test'); 36 | 37 | $response = $this->actingAs($this->generateUser()) 38 | ->get(route('auth.credentials.register_totp.confirm')); 39 | 40 | $response->assertRedirect(route('auth.sudo_mode')); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/ViewAccountRecoveryRequestPageTests.php: -------------------------------------------------------------------------------- 1 | get(route('recover-account')); 13 | 14 | $response->assertOk(); 15 | } 16 | 17 | /** @test */ 18 | public function the_account_recovery_request_page_cannot_be_viewed_when_authenticated(): void 19 | { 20 | $this->actingAs($this->generateUser()); 21 | 22 | $response = $this->get(route('recover-account')); 23 | 24 | $response->assertRedirect(RouteServiceProvider::HOME); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/ViewLoginPageTests.php: -------------------------------------------------------------------------------- 1 | mockWebauthnChallenge($challenge = 'cPMfYjCIb804eqvknNWAqA'); 17 | $response = $this->get(route('login')); 18 | 19 | $response->assertOk(); 20 | $this->assertInstanceOf(PublicKeyCredentialRequestOptions::class, $options = unserialize(Session::get('auth.login.passkey_authentication_options'), [PublicKeyCredentialRequestOptions::class])); 21 | $this->assertSame([ 22 | 'challenge' => $challenge, 23 | 'rpId' => 'configured.rpid', 24 | 'userVerification' => 'required', 25 | ], $options->jsonSerialize()); 26 | } 27 | 28 | /** @test */ 29 | public function the_login_page_cannot_be_viewed_when_already_authenticated(): void 30 | { 31 | $this->actingAs($this->generateUser()); 32 | 33 | $response = $this->get(route('login')); 34 | 35 | $response->assertRedirect(RouteServiceProvider::HOME); 36 | $response->assertSessionMissing('auth.login.passkey_authentication_options'); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /packages/core/src/Testing/Partials/ViewRegistrationPageTests.php: -------------------------------------------------------------------------------- 1 | get(route('register')); 13 | 14 | $response->assertOk(); 15 | } 16 | 17 | /** @test */ 18 | public function the_register_page_cannot_be_viewed_when_authenticated(): void 19 | { 20 | $this->actingAs($this->generateUser()); 21 | 22 | $response = $this->get(route('register')); 23 | 24 | $response->assertRedirect(RouteServiceProvider::HOME); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /packages/core/src/Testing/RegisterPublicKeyCredentialTests.php: -------------------------------------------------------------------------------- 1 | enableSudoMode(); 13 | $user = $this->generateUser(); 14 | $credential = LaravelAuth::multiFactorCredentialModel()::factory()->totp()->forUser($user)->create(); 15 | 16 | $response = $this->actingAs($user) 17 | ->delete(route('auth.credentials.destroy', ['id' => $credential->id])); 18 | 19 | $response->assertRedirect(route('auth.settings')); 20 | $this->assertNull($credential->fresh()); 21 | } 22 | 23 | /** @test */ 24 | public function the_user_cannot_remove_a_credential_that_does_not_exist(): void 25 | { 26 | $this->enableSudoMode(); 27 | $user = $this->generateUser(); 28 | 29 | $response = $this->actingAs($user) 30 | ->delete(route('auth.credentials.destroy', ['id' => 1])); 31 | 32 | $response->assertNotFound(); 33 | } 34 | 35 | /** @test */ 36 | public function the_user_cannot_remove_a_credential_that_does_not_belong_to_them(): void 37 | { 38 | $this->enableSudoMode(); 39 | $userA = $this->generateUser([$this->usernameField() => $this->defaultUsername()]); 40 | $userB = $this->generateUser([$this->usernameField() => $this->anotherUsername()]); 41 | $credential = LaravelAuth::multiFactorCredentialModel()::factory()->totp()->forUser($userA)->create(); 42 | 43 | $response = $this->actingAs($userB) 44 | ->delete(route('auth.credentials.destroy', ['id' => $credential->id])); 45 | 46 | $response->assertNotFound(); 47 | $this->assertNotNull($credential->fresh()); 48 | } 49 | 50 | /** @test */ 51 | public function the_user_cannot_remove_a_credential_when_no_longer_in_sudo_mode(): void 52 | { 53 | $user = $this->generateUser(); 54 | $credential = LaravelAuth::multiFactorCredentialModel()::factory()->totp()->forUser($user)->create(); 55 | 56 | $response = $this->actingAs($user) 57 | ->delete(route('auth.credentials.destroy', ['id' => $credential->id])); 58 | 59 | $response->assertRedirect(route('auth.sudo_mode')); 60 | $this->assertNotNull($credential->fresh()); 61 | } 62 | 63 | /** @test */ 64 | public function a_credential_cannot_be_removed_when_the_user_is_not_password_based(): void 65 | { 66 | $this->enableSudoMode(); 67 | $user = $this->generateUser(['has_password' => false]); 68 | $credential = LaravelAuth::multiFactorCredentialModel()::factory()->totp()->forUser($user)->create(); 69 | 70 | $response = $this->actingAs($user) 71 | ->delete(route('auth.credentials.destroy', ['id' => $credential->id])); 72 | 73 | $response->assertForbidden(); 74 | $this->assertNotNull($credential->fresh()); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /packages/core/src/Testing/SudoModeChallengeTests.php: -------------------------------------------------------------------------------- 1 | generateUser(); 11 | $this->enableSudoMode(); 12 | 13 | $response = $this->actingAs($user) 14 | ->get(route('auth.settings')); 15 | 16 | $response->assertOk(); 17 | } 18 | 19 | /** @test */ 20 | public function the_credentials_overview_page_cannot_be_viewed_when_no_longer_in_sudo_mode(): void 21 | { 22 | $user = $this->generateUser(); 23 | 24 | $response = $this->actingAs($user) 25 | ->get(route('auth.settings')); 26 | 27 | $response->assertRedirect(route('auth.sudo_mode')); 28 | } 29 | 30 | /** @test */ 31 | public function the_credentials_overview_page_cannot_be_viewed_when_not_authenticated(): void 32 | { 33 | $response = $this->get(route('auth.settings')); 34 | 35 | $response->assertRedirect(route('login')); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /packages/core/templates/Console/Kernel.bladetmpl: -------------------------------------------------------------------------------- 1 | namespace App\Console; 2 | 3 | use Illuminate\Console\Scheduling\Schedule; 4 | use Illuminate\Foundation\Console\Kernel as ConsoleKernel; 5 | 6 | class Kernel extends ConsoleKernel 7 | { 8 | /** 9 | * Define the application's command schedule. 10 | @if (! $useStrictTypes) 11 | * 12 | * {!! '@' !!}return void 13 | */ 14 | protected function schedule(Schedule $schedule) 15 | @else 16 | */ 17 | protected function schedule(Schedule $schedule): void 18 | @endif 19 | { 20 | $this->artisan('model:prune'); 21 | } 22 | 23 | /** 24 | * Register the commands for the application. 25 | @if (! $useStrictTypes) 26 | * 27 | * {!! '@' !!}return void 28 | */ 29 | protected function commands() 30 | @else 31 | */ 32 | protected function commands(): void 33 | @endif 34 | { 35 | $this->load(__DIR__.'/Commands'); 36 | 37 | require base_path('routes/console.php'); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /packages/core/templates/Database/2014_10_12_000000_create_users_table.bladetmpl: -------------------------------------------------------------------------------- 1 | use Illuminate\Database\Migrations\Migration; 2 | use Illuminate\Database\Schema\Blueprint; 3 | use Illuminate\Support\Facades\Schema; 4 | 5 | return new class extends Migration 6 | { 7 | /** 8 | * Run the migrations. 9 | * 10 | * {!! '@' !!}return void 11 | */ 12 | public function up() 13 | { 14 | Schema::create('users', function (Blueprint $table) { 15 | $table->id(); 16 | $table->string('name'); 17 | @if ($flavor === 'username-based') 18 | $table->string('username')->unique(); 19 | $table->string('email'); 20 | @else 21 | $table->string('email')->unique(); 22 | @endif 23 | $table->timestamp('email_verified_at')->nullable(); 24 | $table->string('password'); 25 | $table->boolean('has_password'); 26 | $table->json('recovery_codes')->nullable()->default(null); 27 | $table->rememberToken(); 28 | $table->timestamps(); 29 | }); 30 | } 31 | 32 | /** 33 | * Reverse the migrations. 34 | * 35 | * {!! '@' !!}return void 36 | */ 37 | public function down() 38 | { 39 | Schema::dropIfExists('users'); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /packages/core/templates/Database/User.bladetmpl: -------------------------------------------------------------------------------- 1 | namespace App\Models; 2 | 3 | use ClaudioDekker\LaravelAuth\LaravelAuth; 4 | use ClaudioDekker\LaravelAuth\Support\AccountSecurityIndicator; 5 | // use Illuminate\Contracts\Auth\MustVerifyEmail; 6 | use Illuminate\Database\Eloquent\Factories\HasFactory; 7 | use Illuminate\Database\Eloquent\Prunable; 8 | use Illuminate\Foundation\Auth\User as Authenticatable; 9 | use Illuminate\Notifications\Notifiable; 10 | use Laravel\Sanctum\HasApiTokens; 11 | 12 | class User extends Authenticatable 13 | { 14 | use HasApiTokens, HasFactory, Notifiable, Prunable; 15 | 16 | /** 17 | * The attributes that are mass assignable. 18 | * 19 | * {!! '@' !!}var array 20 | */ 21 | protected $fillable = [ 22 | 'name', 23 | @if($flavor === 'username-based') 24 | 'username', 25 | @endif 26 | 'email', 27 | 'password', 28 | 'has_password', 29 | 'recovery_codes', 30 | ]; 31 | 32 | /** 33 | * The attributes that should be hidden for serialization. 34 | * 35 | * {!! '@' !!}var array 36 | */ 37 | protected $hidden = [ 38 | 'password', 39 | 'recovery_codes', 40 | 'remember_token', 41 | ]; 42 | 43 | /** 44 | * The attributes that should be cast. 45 | * 46 | * {!! '@' !!}var array 47 | */ 48 | protected $casts = [ 49 | 'email_verified_at' => 'datetime', 50 | 'has_password' => 'boolean', 51 | 'recovery_codes' => 'array', 52 | ]; 53 | 54 | /** 55 | * Get all of the multi factor credentials for the user. 56 | * 57 | * {!! '@' !!}return \Illuminate\Database\Eloquent\Relations\HasMany 58 | */ 59 | public function multiFactorCredentials() 60 | { 61 | return $this->hasMany(LaravelAuth::multiFactorCredentialModel(), 'user_id')->orderBy('created_at', 'desc'); 62 | } 63 | 64 | /** 65 | * Determine the current account safety level. 66 | */ 67 | public function accountSecurityIndicator(): AccountSecurityIndicator 68 | { 69 | if (! $this->recovery_codes && $this->multiFactorCredentials->isEmpty()) { 70 | return AccountSecurityIndicator::NO_MFA_NO_RECOVERY_CODES; 71 | } 72 | 73 | if ($this->multiFactorCredentials->isEmpty()) { 74 | return AccountSecurityIndicator::NO_MFA_HAS_RECOVERY_CODES; 75 | } 76 | 77 | if (! $this->recovery_codes) { 78 | return AccountSecurityIndicator::HAS_MFA_NO_RECOVERY_CODES; 79 | } 80 | 81 | return AccountSecurityIndicator::HAS_MFA_HAS_RECOVERY_CODES; 82 | } 83 | 84 | /** 85 | * Get the prunable model query. 86 | * 87 | * {!! '@' !!}return \Illuminate\Database\Eloquent\Builder 88 | */ 89 | public function prunable() 90 | { 91 | return static::query() 92 | ->where('has_password', false) 93 | ->where('created_at', '<', now()->subHour()) 94 | ->where('created_at', '>', now()->subDay()) 95 | ->doesntHave('multiFactorCredentials'); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /packages/core/templates/Database/UserFactory.bladetmpl: -------------------------------------------------------------------------------- 1 | namespace Database\Factories; 2 | 3 | use Illuminate\Database\Eloquent\Factories\Factory; 4 | use Illuminate\Support\Str; 5 | 6 | /** 7 | * {!! '@' !!}extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User> 8 | */ 9 | class UserFactory extends Factory 10 | { 11 | /** 12 | * Define the model's default state. 13 | * 14 | * {!! '@' !!}return array 15 | */ 16 | public function definition() 17 | { 18 | return [ 19 | 'name' => fake()->name(), 20 | @if ($flavor === 'username-based') 21 | 'username' => fake()->unique()->username(), 22 | @endif 23 | 'email' => fake()->safeEmail(), 24 | 'email_verified_at' => now(), 25 | 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 26 | 'remember_token' => Str::random(10), 27 | 'has_password' => true, 28 | ]; 29 | } 30 | 31 | /** 32 | * Indicate that the model's email address should be unverified. 33 | * 34 | * {!! '@' !!}return static 35 | */ 36 | public function unverified() 37 | { 38 | return $this->state(function (array $attributes) { 39 | return [ 40 | 'email_verified_at' => null, 41 | ]; 42 | }); 43 | } 44 | 45 | /** 46 | * Indicate that the model's password field is not usable. 47 | * 48 | * {!! '@' !!}return static 49 | */ 50 | public function passwordless() 51 | { 52 | return $this->state(function (array $attributes) { 53 | return [ 54 | 'has_password' => false, 55 | ]; 56 | }); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /packages/core/templates/Tests/PruneUnclaimedUsersTest.bladetmpl: -------------------------------------------------------------------------------- 1 | namespace Tests\Unit; 2 | 3 | use ClaudioDekker\LaravelAuth\LaravelAuth; 4 | use Illuminate\Foundation\Testing\DatabaseMigrations; 5 | use Illuminate\Support\Carbon; 6 | use Tests\TestCase; 7 | 8 | class PruneUnclaimedUsersTest extends TestCase 9 | { 10 | use DatabaseMigrations; 11 | 12 | /** {!! '@' !!}test */ 13 | public function it_prunes_unclaimed_users_after_an_hour(): void 14 | { 15 | Carbon::setTestNow('2022-01-01 00:00:00'); 16 | $userA = LaravelAuth::userModel()::factory()->passwordless()->create(); 17 | $userB = LaravelAuth::userModel()::factory()->passwordless()->create(); 18 | $userC = LaravelAuth::userModel()::factory()->passwordless()->create(); 19 | LaravelAuth::multiFactorCredentialModel()::factory()->forUser($userC)->publicKey()->create(); 20 | Carbon::setTestNow('2022-01-01 00:45:00'); 21 | $userD = LaravelAuth::userModel()::factory()->passwordless()->create(); 22 | Carbon::setTestNow('2022-01-01 01:00:01'); 23 | 24 | $this->artisan('model:prune'); 25 | 26 | $this->assertNull($userA->fresh()); 27 | $this->assertNull($userB->fresh()); 28 | $this->assertNotNull($userC->fresh()); 29 | $this->assertNotNull($userD->fresh()); 30 | Carbon::setTestNow(); 31 | } 32 | 33 | /** {!! '@' !!}test */ 34 | public function it_retains_seemingly_unclaimed_users_that_have_existed_for_a_while_as_a_data_integrity_precaution(): void 35 | { 36 | Carbon::setTestNow('2022-01-01 00:00:00'); 37 | $userA = LaravelAuth::userModel()::factory()->passwordless()->create(); 38 | Carbon::setTestNow('2022-01-02 00:00:01'); 39 | $userB = LaravelAuth::userModel()::factory()->passwordless()->create(); 40 | Carbon::setTestNow('2022-01-02 00:45:00'); 41 | $userC = LaravelAuth::userModel()::factory()->passwordless()->create(); 42 | Carbon::setTestNow('2022-01-02 01:00:02'); 43 | 44 | $this->artisan('model:prune'); 45 | 46 | $this->assertNotNull($userA->fresh()); 47 | $this->assertNull($userB->fresh()); 48 | $this->assertNotNull($userC->fresh()); 49 | Carbon::setTestNow(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /packages/core/templates/Tests/UserTest.bladetmpl: -------------------------------------------------------------------------------- 1 | namespace Tests\Unit; 2 | 3 | use ClaudioDekker\LaravelAuth\LaravelAuth; 4 | use ClaudioDekker\LaravelAuth\Support\AccountSecurityIndicator; 5 | use Illuminate\Foundation\Testing\DatabaseMigrations; 6 | use Tests\TestCase; 7 | 8 | class UserTest extends TestCase 9 | { 10 | use DatabaseMigrations; 11 | 12 | /** {!! '@' !!}test */ 13 | public function the_account_security_indicator_indicates_the_user_has_both_mfa_and_recovery_codes(): void 14 | { 15 | $user = LaravelAuth::userModel()::factory()->create(['recovery_codes' => ['foo', 'bar']]); 16 | LaravelAuth::multiFactorCredentialModel()::factory()->forUser($user)->publicKey()->create(); 17 | 18 | tap($user->accountSecurityIndicator(), function (AccountSecurityIndicator $indicator) { 19 | $this->assertFalse($indicator->hasIssues()); 20 | $this->assertSame('GREEN', $indicator->color()); 21 | $this->assertSame(__('laravel-auth::auth.security-indicator.has-mfa-has-recovery-codes'), $indicator->message()); 22 | }); 23 | } 24 | 25 | /** {!! '@' !!}test */ 26 | public function the_account_security_indicator_indicates_the_user_has_no_mfa_and_no_recovery_codes(): void 27 | { 28 | $user = LaravelAuth::userModel()::factory()->create(); 29 | 30 | tap($user->accountSecurityIndicator(), function (AccountSecurityIndicator $indicator) { 31 | $this->assertTrue($indicator->hasIssues()); 32 | $this->assertSame('RED', $indicator->color()); 33 | $this->assertSame(__('laravel-auth::auth.security-indicator.no-mfa-no-recovery-codes'), $indicator->message()); 34 | }); 35 | } 36 | 37 | /** {!! '@' !!}test */ 38 | public function the_account_security_indicator_indicates_the_user_has_no_mfa(): void 39 | { 40 | $user = LaravelAuth::userModel()::factory()->create(['recovery_codes' => ['foo', 'bar']]); 41 | 42 | tap($user->accountSecurityIndicator(), function (AccountSecurityIndicator $indicator) { 43 | $this->assertTrue($indicator->hasIssues()); 44 | $this->assertSame('RED', $indicator->color()); 45 | $this->assertSame(__('laravel-auth::auth.security-indicator.no-mfa-has-recovery-codes'), $indicator->message()); 46 | }); 47 | } 48 | 49 | /** {!! '@' !!}test */ 50 | public function the_account_security_indicator_indicates_the_user_has_mfa_but_no_recovery_codes(): void 51 | { 52 | $user = LaravelAuth::userModel()::factory()->create(); 53 | LaravelAuth::multiFactorCredentialModel()::factory()->forUser($user)->publicKey()->create(); 54 | 55 | tap($user->accountSecurityIndicator(), function (AccountSecurityIndicator $indicator) { 56 | $this->assertTrue($indicator->hasIssues()); 57 | $this->assertSame('ORANGE', $indicator->color()); 58 | $this->assertSame(__('laravel-auth::auth.security-indicator.has-mfa-no-recovery-codes'), $indicator->message()); 59 | }); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /packages/core/tests/TestCase.php: -------------------------------------------------------------------------------- 1 | loadLaravelMigrations(); 22 | } 23 | 24 | /** 25 | * Define environment setup. 26 | * 27 | * @param \Illuminate\Foundation\Application $app 28 | * @return void 29 | */ 30 | protected function getEnvironmentSetUp($app) 31 | { 32 | config()->set('database.default', 'testbench'); 33 | config()->set('database.connections.testbench', [ 34 | 'driver' => 'sqlite', 35 | 'database' => ':memory:', 36 | 'prefix' => '', 37 | ]); 38 | } 39 | 40 | /** 41 | * Get package providers. 42 | * 43 | * @param \Illuminate\Foundation\Application $app 44 | * @return array 45 | */ 46 | protected function getPackageProviders($app) 47 | { 48 | return [ 49 | LaravelAuthServiceProvider::class, 50 | ]; 51 | } 52 | 53 | /** 54 | * Mocks the container-bound Rate Limiter instance 55 | * with one that has exceeded the limit. 56 | */ 57 | protected function mockRateLimitExceeded(): void 58 | { 59 | $mock = RateLimiter::partialMock(); 60 | 61 | $mock->shouldReceive('tooManyAttempts')->andReturn(true); 62 | $mock->shouldReceive('availableIn')->andReturn(75); 63 | $mock->shouldReceive('hit')->andReturn(1); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /packages/core/tests/Unit/Http/Middleware/EnsurePasswordBasedUserTest.php: -------------------------------------------------------------------------------- 1 | ['web']], function () { 20 | Route::get('/baz')->name('auth.password_based_only'); 21 | Route::middleware(EnsurePasswordBasedUser::class)->get('/foo', function () { 22 | return 'bar'; 23 | }); 24 | }); 25 | } 26 | 27 | /** @test */ 28 | public function it_aborts_the_request_when_not_authenticated(): void 29 | { 30 | $response = $this->get('/foo'); 31 | 32 | $response->assertStatus(401); 33 | } 34 | 35 | /** @test */ 36 | public function it_aborts_the_request_when_the_user_does_not_have_a_password(): void 37 | { 38 | $user = UserFactory::new()->create(); 39 | $user->has_password = false; 40 | 41 | $response = $this->actingAs($user)->get('/foo'); 42 | 43 | $response->assertStatus(403); 44 | } 45 | 46 | /** @test */ 47 | public function it_continues_when_the_user_has_a_password(): void 48 | { 49 | $user = UserFactory::new()->create(); 50 | $user->has_password = true; 51 | 52 | $response = $this->actingAs($user)->get('/foo'); 53 | 54 | $response->assertStatus(200); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /packages/core/tests/Unit/LaravelAuthTest.php: -------------------------------------------------------------------------------- 1 | 20 | */ 21 | protected function getPackageProviders($app) 22 | { 23 | return []; 24 | } 25 | 26 | protected function tearDown(): void 27 | { 28 | LaravelAuth::$runsMigrations = true; 29 | LaravelAuth::useMultiFactorCredentialModel(MultiFactorCredential::class); 30 | LaravelAuth::useUserModel(); 31 | 32 | parent::tearDown(); 33 | } 34 | 35 | /** @test */ 36 | public function it_loads_migration_by_default(): void 37 | { 38 | $this->app->register(LaravelAuthServiceProvider::class); 39 | $this->artisan('migrate'); 40 | 41 | $this->assertTrue(Schema::hasTable('multi_factor_credentials')); 42 | } 43 | 44 | /** @test */ 45 | public function it_skips_loading_migrations_when_ignored(): void 46 | { 47 | LaravelAuth::ignoreMigrations(); 48 | 49 | $this->app->register(LaravelAuthServiceProvider::class); 50 | $this->artisan('migrate'); 51 | 52 | $this->assertFalse(Schema::hasTable('multi_factor_credentials')); 53 | } 54 | 55 | /** @test */ 56 | public function it_uses_the_included_multi_factor_credential_model_by_default(): void 57 | { 58 | $this->assertSame(LaravelAuth::multiFactorCredentialModel(), MultiFactorCredential::class); 59 | $this->assertInstanceOf(MultiFactorCredential::class, LaravelAuth::multiFactorCredential()); 60 | } 61 | 62 | /** @test */ 63 | public function it_can_customize_the_multi_factor_credential_model(): void 64 | { 65 | LaravelAuth::useMultiFactorCredentialModel(User::class); 66 | 67 | $this->assertSame(LaravelAuth::multiFactorCredentialModel(), User::class); 68 | $this->assertInstanceOf(User::class, LaravelAuth::multiFactorCredential()); 69 | } 70 | 71 | /** @test */ 72 | public function it_uses_the_authentication_guard_defined_user_model_by_default(): void 73 | { 74 | $this->assertSame(LaravelAuth::userModel(), User::class); 75 | $this->assertInstanceOf(User::class, LaravelAuth::user()); 76 | } 77 | 78 | /** @test */ 79 | public function it_can_customize_the_user_model(): void 80 | { 81 | LaravelAuth::useUserModel(FakeUser::class); 82 | 83 | $this->assertSame(LaravelAuth::userModel(), FakeUser::class); 84 | $this->assertInstanceOf(FakeUser::class, LaravelAuth::user()); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /packages/core/tests/Unit/MultiFactorCredentialTest.php: -------------------------------------------------------------------------------- 1 | create(); 18 | 19 | $credential = LaravelAuth::multiFactorCredentialModel()::factory()->create([ 20 | 'user_id' => $user->id, 21 | ]); 22 | 23 | $this->assertInstanceOf(LaravelAuth::userModel(), $credential->user); 24 | $this->assertTrue($credential->user->is($user)); 25 | } 26 | 27 | /** @test */ 28 | public function it_can_customize_the_user_relationship_model_based_on_the_standard_laravel_auth_config(): void 29 | { 30 | config([ 31 | 'auth.defaults.guard' => 'foo', 32 | 'auth.guards.foo.provider' => 'bar', 33 | 'auth.providers.bar.model' => LaravelAuth::userModel(), 34 | ]); 35 | $user = UserFactory::new()->create(); 36 | 37 | $credential = LaravelAuth::multiFactorCredentialModel()::factory()->create([ 38 | 'user_id' => $user->id, 39 | ]); 40 | 41 | $this->assertInstanceOf(LaravelAuth::userModel(), $credential->user); 42 | $this->assertTrue($credential->user->is($user)); 43 | } 44 | 45 | /** @test */ 46 | public function it_does_not_expose_the_secret_when_serialized(): void 47 | { 48 | $token = LaravelAuth::multiFactorCredentialModel()::factory()->create([ 49 | 'user_id' => 1, 50 | 'secret' => 'foo', 51 | ]); 52 | 53 | $this->assertArrayNotHasKey('secret', $token->toArray()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /packages/core/tests/_fixtures/FakeUser.php: -------------------------------------------------------------------------------- 1 |