diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c68765b..36c2228 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1 @@ -github: :vendor_name +github: vormkracht10 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 96701be..21b9d9e 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Ask a question - url: https://github.com/:vendor_name/:package_name/discussions/new?category=q-a + url: https://github.com/vormkracht10/filament-two-factor-auth/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/:vendor_name/:package_name/discussions/new?category=ideas + url: https://github.com/vormkracht10/filament-two-factor-auth/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/:vendor_name/:package_name/security/policy + url: https://github.com/vormkracht10/filament-two-factor-auth/security/policy about: Learn how to notify us for sensitive bugs diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 12ab7c2..67a1a8e 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,3 +1,3 @@ # Security Policy -If you discover any security related issues, please email author@domain.com instead of using the issue tracker. +If you discover any security related issues, please email hello@baspa.dev instead of using the issue tracker. diff --git a/CHANGELOG.md b/CHANGELOG.md index 767365d..30ad9b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -All notable changes to `:package_name` will be documented in this file. +All notable changes to `filament-two-factor-auth` will be documented in this file. ## 1.0.0 - 202X-XX-XX diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..cdcbb7a 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) vormkracht10 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 98f321d..3900dd4 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,59 @@ -# :package_description +# Filament Two Factor Auth -[![Latest Version on Packagist](https://img.shields.io/packagist/v/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) -[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/fix-php-code-styling.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3A"Fix+PHP+code+styling"+branch%3Amain) -[![Total Downloads](https://img.shields.io/packagist/dt/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) +[![Latest Version on Packagist](https://img.shields.io/packagist/v/vormkracht10/filament-two-factor-auth.svg?style=flat-square)](https://packagist.org/packages/vormkracht10/filament-two-factor-auth) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/vormkracht10/filament-two-factor-auth/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/vormkracht10/filament-two-factor-auth/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/vormkracht10/filament-two-factor-auth/fix-php-code-styling.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/vormkracht10/filament-two-factor-auth/actions?query=workflow%3A"Fix+PHP+code+styling"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/vormkracht10/filament-two-factor-auth.svg?style=flat-square)](https://packagist.org/packages/vormkracht10/filament-two-factor-auth) - ---- -This repo can be used to scaffold a Filament plugin. Follow these steps to get started: -1. Press the "Use this template" button at the top of this repo to create a new repo with the contents of this skeleton. -2. Run "php ./configure.php" to run a script that will replace all placeholders throughout all the files. -3. Make something great! ---- - -This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. +This package helps you integrate Laravel Fortify with ease in your Filament apps. ## Installation You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug +composer require vormkracht10/filament-two-factor-auth ``` -You can publish and run the migrations with: +You can easily install the plugin by running the following command: ```bash -php artisan vendor:publish --tag=":package_slug-migrations" -php artisan migrate + php artisan filament-two-factor-auth:install ``` -You can publish the config file with: +If you don't have [Laravel Fortify](https://laravel.com/docs/11.x/fortify) installed yet, you can install it by running the following commands: ```bash -php artisan vendor:publish --tag=":package_slug-config" -``` +composer require laravel/fortify -Optionally, you can publish the views using +php artisan fortify:install -```bash -php artisan vendor:publish --tag=":package_slug-views" +php artisan migrate ``` -This is the contents of the published config file: +Then add the plugin to your `PanelProvider`: ```php -return [ -]; +->plugin(TwoFactorAuthPlugin::make()) +``` + +Make sure your user uses the `TwoFactorAuthenticatable` trait: + +```php +class User extends Authenticatable implements FilamentUser +{ + use HasApiTokens, HasFactory, Notifiable, TwoFactorAuthenticatable; + // ... +} ``` ## Usage ```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +$twoFactorAuth = new Vormkracht10\TwoFactorAuth(); +echo $twoFactorAuth->echoPhrase('Hello, Vormkracht10!'); ``` ## Testing @@ -78,7 +76,7 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [:author_name](https://github.com/:author_username) +- [Baspa](https://github.com/vormkracht10) - [All Contributors](../../contributors) ## License diff --git a/bin/build.js b/bin/build.js index 913baf4..e82bb63 100644 --- a/bin/build.js +++ b/bin/build.js @@ -46,5 +46,5 @@ const defaultOptions = { compile({ ...defaultOptions, entryPoints: ['./resources/js/index.js'], - outfile: './resources/dist/skeleton.js', + outfile: './resources/dist/filament-two-factor-auth.js', }) diff --git a/composer.json b/composer.json index bb6be65..3a75e6a 100644 --- a/composer.json +++ b/composer.json @@ -1,29 +1,28 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "vormkracht10/filament-two-factor-auth", + "description": "This package helps you integrate Laravel Fortify with ease in your Filament apps. ", "keywords": [ - ":vendor_name", + "vormkracht10", "laravel", - ":package_slug" + "filament-two-factor-auth" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/vormkracht10/filament-two-factor-auth", "support": { - "issues": "https://github.com/:vendor_slug/:package_slug/issues", - "source": "https://github.com/:vendor_slug/:package_slug" + "issues": "https://github.com/vormkracht10/filament-two-factor-auth/issues", + "source": "https://github.com/vormkracht10/filament-two-factor-auth" }, "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Baspa", + "email": "hello@baspa.dev", "role": "Developer" } ], "require": { "php": "^8.1", "filament/filament": "^3.0", - "filament/forms": "^3.0", - "filament/tables": "^3.0", + "laravel/fortify": "^1.23", "spatie/laravel-package-tools": "^1.15.0" }, "require-dev": { @@ -36,18 +35,17 @@ "pestphp/pest-plugin-laravel": "^2.0", "phpstan/extension-installer": "^1.1", "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-phpunit": "^1.0", - "spatie/laravel-ray": "^1.26" + "phpstan/phpstan-phpunit": "^1.0" }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src/", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories/" + "Vormkracht10\\TwoFactorAuth\\": "src/", + "Vormkracht10\\TwoFactorAuth\\Database\\Factories\\": "database/factories/" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests/" + "Vormkracht10\\TwoFactorAuth\\Tests\\": "tests/" } }, "scripts": { @@ -67,10 +65,10 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" + "Vormkracht10\\TwoFactorAuth\\TwoFactorAuthServiceProvider" ], "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" + "TwoFactorAuth": "Vormkracht10\\TwoFactorAuth\\Facades\\TwoFactorAuth" } } }, diff --git a/config/skeleton.php b/config/skeleton.php deleted file mode 100644 index 7e74186..0000000 --- a/config/skeleton.php +++ /dev/null @@ -1,6 +0,0 @@ -" : '') . "\e[0m"); -writeln("Namespace : \e[0;36m$vendorNamespace\\$className\e[0m"); -writeln("Class name : \e[0;36m$className\e[0m"); -writeln('---'); -writeln("\e[1;37mPackages & Utilities\e[0m"); -writeln('Larastan/PhpStan : ' . ($usePhpStan ? "\e[0;32mYes" : "\e[0;31mNo") . "\e[0m"); -writeln('Pint : ' . ($usePint ? "\e[0;32mYes" : "\e[0;31mNo") . "\e[0m"); -writeln('Use Dependabot : ' . ($useDependabot ? "\e[0;32mYes" : "\e[0;31mNo") . "\e[0m"); -writeln('Use Ray : ' . ($useLaravelRay ? "\e[0;32mYes" : "\e[0;31mNo") . "\e[0m"); -writeln('Auto-Changelog : ' . ($useUpdateChangelogWorkflow ? "\e[0;32mYes" : "\e[0;31mNo") . "\e[0m"); -if ($formsOnly) { - writeln("Filament/Forms : \e[0;32mYes\e[0m"); -} elseif ($tablesOnly) { - writeln("Filament/Tables : \e[0;32mYes\e[0m"); -} else { - writeln("Filament/Filament : \e[0;32mYes\e[0m"); -} -writeln('------'); -writeln("\r"); -writeln('This script will replace the above values in all relevant files in the project directory.'); -writeln("\r"); - -if (! confirm('Modify files?', true)) { - exit(1); -} - -if ($formsOnly) { - safeUnlink(__DIR__ . '/src/SkeletonTheme.php'); - safeUnlink(__DIR__ . '/src/SkeletonPlugin.php'); - - removeComposerDeps([ - 'filament/filament', - 'filament/tables', - ], 'require'); -} elseif ($tablesOnly) { - safeUnlink(__DIR__ . '/src/SkeletonTheme.php'); - safeUnlink(__DIR__ . '/src/SkeletonPlugin.php'); - - removeComposerDeps([ - 'filament/filament', - 'filament/forms', - ], 'require'); -} else { - if ($isTheme) { - safeUnlink(__DIR__ . '/src/SkeletonServiceProvider.php'); - safeUnlink(__DIR__ . '/src/SkeletonPlugin.php'); - safeUnlink(__DIR__ . '/src/Skeleton.php'); - removeDirectory(__DIR__ . '/bin'); - removeDirectory(__DIR__ . '/config'); - removeDirectory(__DIR__ . '/database'); - removeDirectory(__DIR__ . '/stubs'); - removeDirectory(__DIR__ . '/resources/js'); - removeDirectory(__DIR__ . '/resources/lang'); - removeDirectory(__DIR__ . '/resources/views'); - removeDirectory(__DIR__ . '/src/Commands'); - removeDirectory(__DIR__ . '/src/Facades'); - removeDirectory(__DIR__ . '/src/Testing'); - - setupPackageJsonForTheme(); - - } else { - safeUnlink(__DIR__ . '/src/SkeletonTheme.php'); - } - - removeComposerDeps([ - 'filament/forms', - 'filament/tables', - ], 'require'); -} - -$files = (str_starts_with(strtoupper(PHP_OS), 'WIN') ? replaceForWindows() : replaceForAllOtherOSes()); - -foreach ($files as $file) { - replaceInFile($file, [ - ':author_name' => $authorName, - ':author_username' => $authorUsername, - 'author@domain.com' => $authorEmail, - ':vendor_name' => $vendorName, - ':vendor_slug' => $vendorSlug, - 'VendorName' => $vendorNamespace, - ':package_name' => $packageName, - ':package_slug' => $packageSlug, - ':package_slug_without_prefix' => $packageSlugWithoutPrefix, - 'Skeleton' => $className, - 'skeleton' => $packageSlug, - 'migration_table_name' => titleSnake($packageSlug), - 'variable' => $variableName, - ':package_description' => $description, - ]); - - match (true) { - str_contains($file, determineSeparator('src/Skeleton.php')) => rename($file, determineSeparator('./src/' . $className . '.php')), - str_contains($file, determineSeparator('src/SkeletonServiceProvider.php')) => rename($file, determineSeparator('./src/' . $className . 'ServiceProvider.php')), - str_contains($file, determineSeparator('src/SkeletonTheme.php')) => rename($file, determineSeparator('./src/' . $className . (str_ends_with($className, 'Theme') ? '.php' : 'Theme.php'))), - str_contains($file, determineSeparator('src/SkeletonPlugin.php')) => rename($file, determineSeparator('./src/' . $className . 'Plugin.php')), - str_contains($file, determineSeparator('src/Facades/Skeleton.php')) => rename($file, determineSeparator('./src/Facades/' . $className . '.php')), - str_contains($file, determineSeparator('src/Commands/SkeletonCommand.php')) => rename($file, determineSeparator('./src/Commands/' . $className . 'Command.php')), - str_contains($file, determineSeparator('src/Testing/TestsSkeleton.php')) => rename($file, determineSeparator('./src/Testing/Tests' . $className . '.php')), - str_contains($file, determineSeparator('database/migrations/create_skeleton_table.php.stub')) => rename($file, determineSeparator('./database/migrations/create_' . titleSnake($packageSlugWithoutPrefix) . '_table.php.stub')), - str_contains($file, determineSeparator('config/skeleton.php')) => rename($file, determineSeparator('./config/' . $packageSlugWithoutPrefix . '.php')), - str_contains($file, determineSeparator('resources/lang/en/skeleton.php')) => rename($file, determineSeparator('./resources/lang/en/' . $packageSlugWithoutPrefix . '.php')), - str_contains($file, 'README.md') => removeTag($file, 'delete'), - default => [], - }; -} - -if (! $useDependabot) { - safeUnlink(__DIR__ . '/.github/dependabot.yml'); - safeUnlink(__DIR__ . '/.github/workflows/dependabot-auto-merge.yml'); -} - -if (! $useLaravelRay) { - removeComposerDeps(['spatie/laravel-ray'], 'require-dev'); -} - -if (! $usePhpStan) { - safeUnlink(__DIR__ . '/phpstan.neon.dist'); - safeUnlink(__DIR__ . '/phpstan-baseline.neon'); - safeUnlink(__DIR__ . '/.github/workflows/phpstan.yml'); - - removeComposerDeps([ - 'phpstan/extension-installer', - 'phpstan/phpstan-deprecation-rules', - 'phpstan/phpstan-phpunit', - 'nunomaduro/larastan', - ], 'require-dev'); - - removeComposerDeps(['analyse'], 'scripts'); -} - -if (! $usePint) { - safeUnlink(__DIR__ . '/.github/workflows/fix-php-code-style-issues.yml'); - safeUnlink(__DIR__ . '/pint.json'); - - removeComposerDeps([ - 'laravel/pint', - ], 'require-dev'); - - removeComposerDeps(['format'], 'scripts'); -} - -if (! $useUpdateChangelogWorkflow) { - safeUnlink(__DIR__ . '/.github/workflows/update-changelog.yml'); -} - -confirm('Execute `composer install`?') && run('composer install'); - -if (confirm('Let this script delete itself?', true)) { - unlink(__FILE__); -} - -function ask(string $question, string $default = ''): string -{ - $def = $default ? "\e[0;33m ($default)" : ''; - $answer = readline("\e[0;32m" . $question . $def . ": \e[0m"); - - if (! $answer) { - return $default; - } - - return $answer; -} - -function confirm(string $question, bool $default = false): bool -{ - $answer = ask($question, ($default ? 'Y/n' : 'y/N')); - - if (strtolower($answer) === 'y/n') { - return $default; - } - - return strtolower($answer) === 'y'; -} - -function writeln(string $line): void -{ - echo $line . PHP_EOL; -} - -function run(string $command): string -{ - return trim((string) shell_exec($command)); -} - -function slugify(string $subject): string -{ - return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $subject), '-')); -} - -function titleCase(string $subject): string -{ - return str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $subject))); -} - -function titleSnake(string $subject, string $replace = '_'): string -{ - return str_replace(['-', '_'], $replace, $subject); -} - -function replaceInFile(string $file, array $replacements): void -{ - $contents = file_get_contents($file); - - file_put_contents( - $file, - str_replace( - array_keys($replacements), - array_values($replacements), - $contents - ) - ); -} - -function removePrefix(string $prefix, string $content): string -{ - if (str_starts_with($content, $prefix)) { - return substr($content, strlen($prefix)); - } - - return $content; -} - -function removeComposerDeps(array $names, string $location): void -{ - $data = json_decode(file_get_contents(__DIR__ . '/composer.json'), true); - - foreach ($data[$location] as $name => $version) { - if (in_array($name, $names, true)) { - unset($data[$location][$name]); - } - } - - file_put_contents(__DIR__ . '/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function removeNpmDeps(array $names, string $location): void -{ - $data = json_decode(file_get_contents(__DIR__ . '/package.json'), true); - - foreach ($data[$location] as $name => $version) { - if (in_array($name, $names, true)) { - unset($data[$location][$name]); - } - } - - file_put_contents(__DIR__ . '/package.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | - JSON_UNESCAPED_UNICODE)); -} - -function removeTag(string $file, string $tag): void -{ - $contents = file_get_contents($file); - - file_put_contents( - $file, - preg_replace('/.*/s', '', $contents) ?: $contents - ); -} - -function setupPackageJsonForTheme(): void -{ - removeNpmDeps([ - 'purge', - 'dev', - 'dev:scripts', - 'build', - 'build:scripts', - ], 'scripts'); - - removeNpmDeps([ - '@awcodes/filament-plugin-purge', - 'esbuild', - 'npm-run-all', - 'prettier', - 'prettier-plugin-tailwindcss', - ], 'devDependencies'); - - replaceInFile(__DIR__ . '/package.json', [ - 'dev:styles' => 'dev', - 'build:styles' => 'build', - ]); -} - -function safeUnlink(string $filename): void -{ - if (file_exists($filename) && is_file($filename)) { - unlink($filename); - } -} - -function determineSeparator(string $path): string -{ - return str_replace('/', DIRECTORY_SEPARATOR, $path); -} - -function replaceForWindows(): array -{ - return preg_split('/\\r\\n|\\r|\\n/', run('dir /S /B * | findstr /v /i .git\ | findstr /v /i vendor | findstr /v /i ' . basename(__FILE__) . ' | findstr /r /i /M /F:/ ":author :vendor :package VendorName skeleton migration_table_name vendor_name vendor_slug author@domain.com"')); -} - -function replaceForAllOtherOSes(): array -{ - return explode(PHP_EOL, run('find ./* ./.github/* -name "vendor" -type d -prune \ - -o -name "configure.php" -prune \ - -o -type f -print0 | xargs -0 grep -E -r -l -i ":author|:vendor|:package|VendorName|skeleton|migration_table_name|vendor_name|vendor_slug|author@domain.com"')); -} - -function removeDirectory($dir): void -{ - if (is_dir($dir)) { - $objects = scandir($dir); - foreach ($objects as $object) { - if ($object != '.' && $object != '..') { - if (filetype($dir . '/' . $object) == 'dir') { - removeDirectory($dir . '/' . $object); - } else { - unlink($dir . '/' . $object); - } - } - } - rmdir($dir); - } -} diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index c51604f..daf1e2e 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -1,6 +1,6 @@ id(); // add fields diff --git a/package.json b/package.json index afec3c0..6e730ee 100644 --- a/package.json +++ b/package.json @@ -2,11 +2,11 @@ "private": true, "type": "module", "scripts": { - "dev:styles": "npx tailwindcss -i resources/css/index.css -o resources/dist/skeleton.css --postcss --watch", + "dev:styles": "npx tailwindcss -i resources/css/index.css -o resources/dist/filament-two-factor-auth.css --postcss --watch", "dev:scripts": "node bin/build.js --dev", - "build:styles": "npx tailwindcss -i resources/css/index.css -o resources/dist/skeleton.css --postcss --minify && npm run purge", + "build:styles": "npx tailwindcss -i resources/css/index.css -o resources/dist/filament-two-factor-auth.css --postcss --minify && npm run purge", "build:scripts": "node bin/build.js", - "purge": "filament-purge -i resources/dist/skeleton.css -o resources/dist/skeleton.css -v 3.x", + "purge": "filament-purge -i resources/dist/filament-two-factor-auth.css -o resources/dist/filament-two-factor-auth.css -v 3.x", "dev": "npm-run-all --parallel dev:*", "build": "npm-run-all build:*" }, diff --git a/phpunit.xml.dist b/phpunit.xml.dist index e953c0e..f7d5428 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,7 +16,7 @@ backupStaticProperties="false" > - + tests diff --git a/resources/lang/en/skeleton.php b/resources/lang/en/skeleton.php deleted file mode 100644 index d1b24d9..0000000 --- a/resources/lang/en/skeleton.php +++ /dev/null @@ -1,6 +0,0 @@ - 'Secure your account', + 'Your account has been secured with two factor authentication' => 'Your account has been secured with two factor authentication', + 'Add additional security to your account using two factor authentication' => 'Add additional security to your account using two factor authentication', + 'You have three options to confirm your identity, please choose one of the options below to continue' => 'You have three options to confirm your identity, please choose one of the options below to continue', + 'Two-Factor Authentication enabled' => 'Two-Factor Authentication enabled', + 'Or scan the QR code with your authenticator app' => 'Or scan the QR code with your authenticator app', + 'The secret key to setup the authenticator app is' => 'The secret key to setup the authenticator app is', + 'Save these recovery codes in a secure place as they can be used to recover access to your account if you lose your device.' => 'Save these recovery codes in a secure place as they can be used to recover access to your account if you lose your device.', + 'Cancel' => 'Cancel', + 'Login' => 'Login', + 'Authenticate with your Authentication code' => 'Authenticate with your Authentication code', + 'Reset Password' => 'Reset Password', + 'Submit' => 'Submit', + 'Resend' => 'Resend', + 'Successfully resend the OTP code' => 'Successfully resend the OTP code', + 'Recovery code' => 'Recovery code', + 'Password Confirmation' => 'Password Confirmation', + 'Confirm' => 'Confirm', + 'Verify' => 'Verify', + 'Code' => 'Code', + 'Two-Factor Authentication' => 'Two-Factor Authentication', +]; diff --git a/resources/views/auth/login-two-factor.blade.php b/resources/views/auth/login-two-factor.blade.php new file mode 100644 index 0000000..0142b5c --- /dev/null +++ b/resources/views/auth/login-two-factor.blade.php @@ -0,0 +1,38 @@ +
+
+
+ +

+ {{ __('filament-two-factor-auth::Authenticate with your Authentication code') }} +

+ {{ $this->resend() }} + +
+ + @csrf + {{ $this->form }} + +
+ + {{ __('filament-two-factor-auth::Cancel') }} + + + {{ __('filament-two-factor-auth::Login') }} + +
+
+ +
+
+ +
diff --git a/resources/views/auth/login.blade.php b/resources/views/auth/login.blade.php new file mode 100644 index 0000000..4392fae --- /dev/null +++ b/resources/views/auth/login.blade.php @@ -0,0 +1,35 @@ +
+
+
+ +

+ {{ __('filament-panels::pages/auth/login.heading') }} +

+ + @if (filament()->hasRegistration()) + {{ __('filament-panels::pages/auth/login.actions.register.before') }} + + {{ $this->registerAction }} + @endif + + {{ \Filament\Support\Facades\FilamentView::renderHook(\Filament\View\PanelsRenderHook::AUTH_LOGIN_FORM_BEFORE, scopes: $this->getRenderHookScopes()) }} + + {{ $this->form }} + + + + + {{ \Filament\Support\Facades\FilamentView::renderHook(\Filament\View\PanelsRenderHook::AUTH_LOGIN_FORM_AFTER, scopes: $this->getRenderHookScopes()) }} +
+
+ +
diff --git a/resources/views/auth/password-confirmation.blade.php b/resources/views/auth/password-confirmation.blade.php new file mode 100644 index 0000000..59cf0f0 --- /dev/null +++ b/resources/views/auth/password-confirmation.blade.php @@ -0,0 +1,25 @@ +
config('filament.dark_mode'), +])> +
+
config('filament.dark_mode'), + ])> + +

+ {{ __('filament-two-factor-auth::Confirm') }} +

+ + @csrf + {{ $this->form }} + + + {{ __('filament-two-factor-auth::Confirm') }} + +
+ + +
+
diff --git a/resources/views/auth/password-reset.blade.php b/resources/views/auth/password-reset.blade.php new file mode 100644 index 0000000..42cf9f3 --- /dev/null +++ b/resources/views/auth/password-reset.blade.php @@ -0,0 +1,31 @@ +
+
+
+ +

+ {{ __('filament-two-factor-auth::Reset Password') }} +

+ +
+ + @csrf + {{ $this->form }} + + + {{ __('filament-two-factor-auth::Reset Password') }} + +
+ +
+
+ +
diff --git a/resources/views/auth/register.blade.php b/resources/views/auth/register.blade.php new file mode 100644 index 0000000..93456ac --- /dev/null +++ b/resources/views/auth/register.blade.php @@ -0,0 +1,20 @@ + + @if (filament()->hasLogin()) + + {{ __('filament-panels::pages/auth/register.actions.login.before') }} + + {{ $this->loginAction }} + + @endif + + {{ \Filament\Support\Facades\FilamentView::renderHook(\Filament\View\PanelsRenderHook::AUTH_REGISTER_FORM_BEFORE, scopes: $this->getRenderHookScopes()) }} + + + {{ $this->form }} + + + + + {{ \Filament\Support\Facades\FilamentView::renderHook(\Filament\View\PanelsRenderHook::AUTH_REGISTER_FORM_AFTER, scopes: $this->getRenderHookScopes()) }} + + diff --git a/resources/views/auth/request-password-reset.blade.php b/resources/views/auth/request-password-reset.blade.php new file mode 100644 index 0000000..5f61fb8 --- /dev/null +++ b/resources/views/auth/request-password-reset.blade.php @@ -0,0 +1,39 @@ +
+
+
+ +

+ {{ __('filament-two-factor-auth::Reset Password') }} +

+ +
+ @csrf + {{ $this->form }} + +
+ + {{ __('filament-two-factor-auth::Cancel')}} + + + + {{ __('filament-two-factor-auth::Submit') }} + + + +
+
+ +
+
+ +
diff --git a/resources/views/auth/verify-email.blade.php b/resources/views/auth/verify-email.blade.php new file mode 100644 index 0000000..c77c8eb --- /dev/null +++ b/resources/views/auth/verify-email.blade.php @@ -0,0 +1,11 @@ + +
+
+ + @csrf + + {{ __('filament-two-factor-auth::Verifyl') }} + +
+
+
diff --git a/resources/views/layouts/login.blade.php b/resources/views/layouts/login.blade.php new file mode 100644 index 0000000..dda9e92 --- /dev/null +++ b/resources/views/layouts/login.blade.php @@ -0,0 +1,19 @@ +@php + use Filament\Support\Enums\MaxWidth; +@endphp + + + @props([ + 'after' => null, + 'heading' => null, + 'subheading' => null, + ]) + +
+ {{ $slot }} +
+ + + {{ \Filament\Support\Facades\FilamentView::renderHook(\Filament\View\PanelsRenderHook::FOOTER, scopes: $livewire->getRenderHookScopes()) }} + +
diff --git a/resources/views/two-factor.blade.php b/resources/views/two-factor.blade.php new file mode 100644 index 0000000..b06e2d3 --- /dev/null +++ b/resources/views/two-factor.blade.php @@ -0,0 +1,110 @@ + +
+
+
+

{{ __('Secure your account') }}

+ + @if (!$showingRecoveryCodes && auth()->user()->two_factor_confirmed_at) +

+ {{ __('filament-two-factor-auth::Your account has been secured with two factor authentication') }}. +

+ {{ $this->disableAction() }} + @else +

+ {{ __('filament-two-factor-auth::Add additional security to your account using two factor authentication') }}. +

+ @endif +
+ + @if (!auth()->user()->hasEnabledTwoFactorAuthentication() || $this->showingRecoveryCodes) +
+ + @if (!$this->showTwoFactor()) +
+ + +

+ {{ __('filament-two-factor-auth::You have three options to confirm your identity, please choose one of the options below to continue') }}. +

+
+ + {{ $this->twoFactorOptionForm }} + +
{{ $this->enableAction() }}
+
+ @endif + + @if ($this->showTwoFactor()) +
+ +
+
+ + + @if ($this->showQrCode) +
+
+ @unless ($showingQrCode) +
+ {!! __('filament-two-factor-auth::Two-Factor Authentication enabled') !!} +
+ @else +
+ {!! __('filament-two-factor-auth::Or scan the QR code with your authenticator app') !!}. +
+
+ {!! auth()->user()->twoFactorQrCodeSvg() !!} +
+
+

+ {!! __('filament-two-factor-auth::The secret key to setup the authenticator app is') !!}:
+ {{ decrypt(auth()->user()->two_factor_secret) }} +

+ @endunless +
+
+ @endif + + @if ($showingRecoveryCodes) +
+ {!! __( + 'Save these recovery codes in a secure place as they can be used to recover access to your account if you lose your device', + ) !!}. +
+
+ @foreach ((array) auth()->user()->recoveryCodes() as $index => $code) +

{{ $code }}

+ @endforeach +
+
+
+ @endif + + @if ($showingConfirmation) +
+ {{ $this->otpCodeForm }} +
+ @endif + +
+ @if (!$showingRecoveryCodes && !auth()->user()->two_factor_confirmed_at) + {{ $this->disableAction() }} + @endif + + @if ($showingRecoveryCodes) + {{ $this->regenerateAction() }} + @elseif ($showingConfirmation) + {{ $this->confirmAction() }} + @endif +
+ +
+
+
+ @endif +
+ @endif +
+
+
diff --git a/src/Commands/SkeletonCommand.php b/src/Commands/TwoFactorAuthCommand.php similarity index 58% rename from src/Commands/SkeletonCommand.php rename to src/Commands/TwoFactorAuthCommand.php index 3e5f628..cb802da 100644 --- a/src/Commands/SkeletonCommand.php +++ b/src/Commands/TwoFactorAuthCommand.php @@ -1,12 +1,12 @@ $type->label(), self::cases()); + } + + public function label(): string + { + return match ($this) { + self::email => __('E-mail'), + self::authenticator => __('Authenticator app'), + }; + } +} diff --git a/src/Facades/Skeleton.php b/src/Facades/Skeleton.php deleted file mode 100644 index 1fa9076..0000000 --- a/src/Facades/Skeleton.php +++ /dev/null @@ -1,16 +0,0 @@ -resetPasswordEnabled = Features::enabled(Features::resetPasswords()); + $this->registrationEnabled = Features::enabled(Features::registration()); + + if (session('status')) { + Notification::make() + ->title(session('status')) + ->success() + ->send(); + } + } + + protected function getFormSchema(): array + { + return [ + TextInput::make('email') + ->extraInputAttributes(['name' => 'email']) + ->label(__('filament::login.fields.email.label')) + ->email() + ->required() + ->autocomplete(), + TextInput::make('password') + ->extraInputAttributes(['name' => 'password']) + ->label(__('filament::login.fields.password.label')) + ->password() + ->required(), + Checkbox::make('remember') + ->extraInputAttributes(['name' => 'remember']) + ->label(__('filament::login.fields.remember.label')), + ]; + } + + public function loginWithFortify() + { + try { + $this->rateLimit(5); + } catch (TooManyRequestsException $exception) { + Notification::make() + ->title(__('filament-panels::pages/auth/login.notifications.throttled.title', [ + 'seconds' => $exception->secondsUntilAvailable, + 'minutes' => ceil($exception->secondsUntilAvailable / 60), + ])) + ->body(array_key_exists('body', __('filament-panels::pages/auth/login.notifications.throttled') ?: []) ? __('filament-panels::pages/auth/login.notifications.throttled.body', [ + 'seconds' => $exception->secondsUntilAvailable, + 'minutes' => ceil($exception->secondsUntilAvailable / 60), + ]) : null) + ->danger() + ->send(); + + return null; + } + + $data = $this->form->getState(); + + $request = request()->merge($data); + + return $this->loginPipeline($request)->then(function (Request $request) use ($data) { + + if (! Filament::auth()->attempt($this->getCredentialsFromFormData($data), $data['remember'] ?? false)) { + $this->throwFailureValidationException(); + } + + $user = Filament::auth()->user(); + + if ( + ($user instanceof FilamentUser) && + (! $user->canAccessPanel(Filament::getCurrentPanel())) + ) { + Filament::auth()->logout(); + + $this->throwFailureValidationException(); + } + + session()->regenerate(); + + return app(LoginResponse::class); + }); + } + + protected function loginPipeline(Request $request) + { + if (Fortify::$authenticateThroughCallback) { + return (new Pipeline(app()))->send($request)->through(array_filter( + call_user_func(Fortify::$authenticateThroughCallback, $request) + )); + } + + if (is_array(config('fortify.pipelines.login'))) { + return (new Pipeline(app()))->send($request)->through(array_filter( + config('fortify.pipelines.login') + )); + } + + return (new Pipeline(app()))->send($request)->through(array_filter([ + config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class, + config('fortify.lowercase_usernames') ? CanonicalizeUsername::class : null, + Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null, + AttemptToAuthenticate::class, + PrepareAuthenticatedSession::class, + ])); + } + + protected function getPasswordFormComponent(): Component + { + return TextInput::make('password') + ->label(__('filament-panels::pages/auth/login.form.password.label')) + ->hint(filament()->hasPasswordReset() ? new HtmlString(Blade::render(' {{ __(\'filament-panels::pages/auth/login.actions.request_password_reset.label\') }}')) : null) + ->password() + ->revealable(filament()->arePasswordsRevealable()) + ->autocomplete('current-password') + ->required() + ->extraInputAttributes(['tabindex' => 2]); + } + + protected function getAuthenticateFormAction(): Action + { + return Action::make('authenticate') + ->color('info') + ->label(__('filament-panels::pages/auth/login.form.actions.authenticate.label')) + ->submit('authenticate'); + } +} diff --git a/src/Http/Livewire/Auth/LoginTwoFactor.php b/src/Http/Livewire/Auth/LoginTwoFactor.php new file mode 100644 index 0000000..0eeb70b --- /dev/null +++ b/src/Http/Livewire/Auth/LoginTwoFactor.php @@ -0,0 +1,101 @@ +challengedUser()) { + $this->challengedUser = $request->challengedUser(); + } + + $this->form->fill(); + } + + public function hasLogo(): bool + { + return false; + } + + public function resend(): ?Action + { + return Action::make('resend') + ->label(__('filament-two-factor-auth::Resend')) + ->color('info') + ->extraAttributes(['class' => 'w-full text-xs']) + ->link() + ->action(function () { + if (! $this->throttle()) { + return; + } + + $this->challengedUser->notify(app(SendOTP::class)); + + Notification::make() + ->title(__('filament-two-factor-auth::Successfully resend the OTP code')) + ->success() + ->send(); + }); + } + + private function throttle(): bool + { + try { + $this->rateLimit(1); + + return true; + } catch (TooManyRequestsException $exception) { + Notification::make() + ->title(__('filament-panels::pages/auth/email-verification/email-verification-prompt.notifications.notification_resend_throttled.title', [ + 'seconds' => $exception->secondsUntilAvailable, + 'minutes' => $exception->minutesUntilAvailable, + ])) + ->body(array_key_exists('body', __('filament-panels::pages/auth/email-verification/email-verification-prompt.notifications.notification_resend_throttled') ?: []) ? __('filament-panels::pages/auth/email-verification/email-verification-prompt.notifications.notification_resend_throttled.body', [ + 'seconds' => $exception->secondsUntilAvailable, + 'minutes' => $exception->minutesUntilAvailable, + ]) : null) + ->danger() + ->send(); + + return false; + } + } + + protected function getFormSchema(): array + { + return [ + TextInput::make('code') + ->extraInputAttributes(['name' => 'code']) + ->label(__('filament-two-factor-auth::Code')), + TextInput::make('recovery_code') + ->extraInputAttributes(['name' => 'recovery_code']) + ->label(__('filament-two-factor-auth::Recovery code')), + + ]; + } +} diff --git a/src/Http/Livewire/Auth/PasswordConfirmation.php b/src/Http/Livewire/Auth/PasswordConfirmation.php new file mode 100644 index 0000000..24093ad --- /dev/null +++ b/src/Http/Livewire/Auth/PasswordConfirmation.php @@ -0,0 +1,49 @@ +form->fill(); + + if (session('status')) { + Notification::make() + ->title(session('status')) + ->success() + ->send(); + } + } + + protected function getFormSchema(): array + { + return [ + TextInput::make('password') + ->extraInputAttributes(['name' => 'password']) + ->label(__('filament-two-factor-auth::Password')) + ->password() + ->required(), + ]; + } + + public function render(): View + { + return view('filament-two-factor-auth::auth.password-confirmation') + ->layout('filament::components.layouts.app', [ + 'title' => __('filament-two-factor-auth::Password Confirmation'), + 'breadcrumbs' => [ + __('filament-two-factor-auth::Password Confirmation'), + ], + ]); + } +} diff --git a/src/Http/Livewire/Auth/PasswordReset.php b/src/Http/Livewire/Auth/PasswordReset.php new file mode 100644 index 0000000..6d93d1c --- /dev/null +++ b/src/Http/Livewire/Auth/PasswordReset.php @@ -0,0 +1,87 @@ +check()) { + redirect()->intended(Filament::getUrl()); + } + + $this->form->fill(); + + if (session('status')) { + Notification::make() + ->title(session('status')) + ->success() + ->send(); + } + } + + public function hasLogo(): bool + { + return false; + } + + protected function getFormSchema(): array + { + return [ + TextInput::make('email') + ->label('E-mail') + ->afterStateHydrated(function (TextInput $component) { + $component->state(request()->get('email')); + }) + ->disabled(), + TextInput::make('password') + ->extraInputAttributes(['name' => 'password']) + ->label('Wachtwoord') + ->password() + ->required() + ->rules(['confirmed']) + ->autocomplete('new-password'), + TextInput::make('password_confirmation') + ->extraInputAttributes(['name' => 'password_confirmation']) + ->label('Bevestig wachtwoord') + ->password() + ->autocomplete('new-password') + ->required(), + Hidden::make('email') + ->extraAttributes(['name' => 'email']) + ->afterStateHydrated(fn ($component) => $component->state(request()->get('email'))), + Hidden::make('token') + ->extraAttributes(['name' => 'token']) + ->afterStateHydrated(fn ($component) => $component->state(request()->route('token'))), + ]; + } + + public function render(): View + { + return view('filament-two-factor-auth::auth.password-reset', $this->getViewData()) + ->layout($this->getLayout(), [ + 'livewire' => $this, + 'maxContentWidth' => $this->getMaxContentWidth(), + ...$this->getLayoutData(), + ]); + } +} diff --git a/src/Http/Livewire/Auth/Register.php b/src/Http/Livewire/Auth/Register.php new file mode 100644 index 0000000..51f5f0d --- /dev/null +++ b/src/Http/Livewire/Auth/Register.php @@ -0,0 +1,20 @@ +check()) { + redirect()->intended(Filament::getUrl()); + } + + $this->form->fill(); + + if (session('status')) { + Notification::make() + ->title(session('status')) + ->success() + ->send(); + + redirect()->route('login'); + } + } + + public function hasLogo(): bool + { + return false; + } + + protected function getFormSchema(): array + { + return [ + TextInput::make('email') + ->extraInputAttributes(['name' => 'email']) + ->label('E-mail') + ->email() + ->required() + ->autocomplete(), + ]; + } + + public function render(): View + { + return view('filament-two-factor-auth::auth.request-password-reset', $this->getViewData()) + ->layout($this->getLayout(), [ + 'livewire' => $this, + 'maxContentWidth' => $this->getMaxContentWidth(), + ...$this->getLayoutData(), + ]); + } +} diff --git a/src/Http/Responses/LoginResponse.php b/src/Http/Responses/LoginResponse.php new file mode 100644 index 0000000..cbdba76 --- /dev/null +++ b/src/Http/Responses/LoginResponse.php @@ -0,0 +1,22 @@ +wantsJson() + ? response()->json(['two_factor' => false]) + : redirect()->intended(Filament::getUrl()); + } +} diff --git a/src/Http/Responses/RegistrationResponse.php b/src/Http/Responses/RegistrationResponse.php new file mode 100644 index 0000000..20eedee --- /dev/null +++ b/src/Http/Responses/RegistrationResponse.php @@ -0,0 +1,15 @@ +intended(route('filament.admin.auth.email-verification.prompt')); + } +} diff --git a/src/Http/Responses/TwoFactorChallengeViewResponse.php b/src/Http/Responses/TwoFactorChallengeViewResponse.php new file mode 100644 index 0000000..16c42d8 --- /dev/null +++ b/src/Http/Responses/TwoFactorChallengeViewResponse.php @@ -0,0 +1,20 @@ +intended(Filament::getUrl()); + } +} diff --git a/src/Http/Responses/TwoFactorLoginResponse.php b/src/Http/Responses/TwoFactorLoginResponse.php new file mode 100644 index 0000000..9add8e6 --- /dev/null +++ b/src/Http/Responses/TwoFactorLoginResponse.php @@ -0,0 +1,20 @@ +intended(Filament::getUrl()); + } +} diff --git a/src/Pages/TwoFactor.php b/src/Pages/TwoFactor.php new file mode 100644 index 0000000..4fc9262 --- /dev/null +++ b/src/Pages/TwoFactor.php @@ -0,0 +1,215 @@ +two_factor_confirmed_at) + ) { + app(DisableTwoFactorAuthentication::class)(Auth::user()); + } + + if (session('status') == 'two-factor-authentication-enabled') { + Notification::make() + ->title(__('Two-Factor Authentication enabled')) + ->success() + ->send(); + } + } + + public function requireConfirmation(): bool + { + return ! $this->passwordIsConfirmed(); + } + + public function getConfirmationForm(): array + { + return [ + TextInput::make('current_password') + ->label(__('Password')) + ->dehydrateStateUsing(fn ($state) => filled($state)) + ->required() + ->password() + ->inlineLabel() + ->rule('current_password'), + ]; + } + + public function twoFactorOptionForm(Form $form): Form + { + return $form->schema([ + Radio::make('option') + ->label(__('Authentication method')) + ->hiddenLabel() + ->options(TwoFactorType::array()), + ])->statePath('twoFactorData'); + } + + public function otpCodeForm(Form $form): Form + { + return $form->schema([ + TextInput::make('code') + ->label(__('OTP code')) + ->validationAttribute('OTP code') + ->inlineLabel() + ->required(), + ])->statePath('otpCodeData'); + } + + protected function getForms(): array + { + return [ + 'twoFactorOptionForm', + 'otpCodeForm', + ]; + } + + public function enableAction(): Action + { + return Action::make('enable') + ->label(__('Activate 2FA')) + ->color('primary') + ->action(function ($data) { + + $formData = []; + + if (isset($data['email'])) { + $formData['email'] = $data['email']; + } + + if ($this->twoFactorData['option']) { + $formData['two_factor_type'] = TwoFactorType::tryFrom($this->twoFactorData['option']); + } + + if (count($formData) > 0) { + auth()->user()->update($formData); + $this->showQrCode = true; + } + + $this->enableTwoFactorAuthentication(app(EnableTwoFactorAuthentication::class)); + }); + } + + public function confirmAction(): Action + { + return Action::make('confirm') + ->label(__('Confirm')) + ->color('primary') + ->action(function ($data) { + $this->confirmTwoFactorAuthentication(app(ConfirmTwoFactorAuthentication::class)); + }); + } + + public function regenerateAction(): Action + { + return Action::make('regenerate') + ->label(__('Generate new recovery codes')) + ->color('primary') + ->action(function () { + $this->regenerateRecoveryCodes(app(GenerateNewRecoveryCodes::class)); + }); + } + + public function disableAction(): Action + { + return Action::make('disable') + ->label(auth()->user()->two_factor_confirmed_at ? __('Deactivate 2FA') : __('Cancel')) + ->color('danger') + ->action(function ($data) { + if (isset($data['current_password']) && $data['current_password']) { + $this->userConfirmedPassword(); + } + + $this->disableTwoFactorAuthentication(app(DisableTwoFactorAuthentication::class)); + }); + } + + /** This method is used in the view */ + private function showTwoFactor(): bool + { + return ! empty(Auth::user()->two_factor_secret); + } + + public function enableTwoFactorAuthentication(EnableTwoFactorAuthentication $enable): void + { + $enable(Auth::user()); + + $this->showingQrCode = true; + + if (Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm')) { + $this->showingConfirmation = true; + } else { + $this->showingRecoveryCodes = true; + } + } + + public function confirmTwoFactorAuthentication(ConfirmTwoFactorAuthentication $confirm): void + { + $confirm(Auth::user(), $this->otpCodeData['code']); + + $this->showingQrCode = false; + $this->showingConfirmation = false; + $this->showingRecoveryCodes = true; + } + + public function disableTwoFactorAuthentication(DisableTwoFactorAuthentication $disable): void + { + $disable(Auth::user()); + + $this->showingQrCode = false; + $this->showingConfirmation = false; + $this->showingRecoveryCodes = false; + } + + public function showRecoveryCodes(): void + { + $this->showingRecoveryCodes = true; + } + + public function regenerateRecoveryCodes(GenerateNewRecoveryCodes $generate): void + { + $generate(Auth::user()); + + $this->showingRecoveryCodes = true; + } +} diff --git a/src/Skeleton.php b/src/Skeleton.php deleted file mode 100644 index 34c7194..0000000 --- a/src/Skeleton.php +++ /dev/null @@ -1,5 +0,0 @@ -getId()); - - return $plugin; - } -} diff --git a/src/SkeletonServiceProvider.php b/src/SkeletonServiceProvider.php deleted file mode 100644 index 6caab3f..0000000 --- a/src/SkeletonServiceProvider.php +++ /dev/null @@ -1,152 +0,0 @@ -name(static::$name) - ->hasCommands($this->getCommands()) - ->hasInstallCommand(function (InstallCommand $command) { - $command - ->publishConfigFile() - ->publishMigrations() - ->askToRunMigrations() - ->askToStarRepoOnGitHub(':vendor_slug/:package_slug'); - }); - - $configFileName = $package->shortName(); - - if (file_exists($package->basePath("/../config/{$configFileName}.php"))) { - $package->hasConfigFile(); - } - - if (file_exists($package->basePath('/../database/migrations'))) { - $package->hasMigrations($this->getMigrations()); - } - - if (file_exists($package->basePath('/../resources/lang'))) { - $package->hasTranslations(); - } - - if (file_exists($package->basePath('/../resources/views'))) { - $package->hasViews(static::$viewNamespace); - } - } - - public function packageRegistered(): void {} - - public function packageBooted(): void - { - // Asset Registration - FilamentAsset::register( - $this->getAssets(), - $this->getAssetPackageName() - ); - - FilamentAsset::registerScriptData( - $this->getScriptData(), - $this->getAssetPackageName() - ); - - // Icon Registration - FilamentIcon::register($this->getIcons()); - - // Handle Stubs - if (app()->runningInConsole()) { - foreach (app(Filesystem::class)->files(__DIR__ . '/../stubs/') as $file) { - $this->publishes([ - $file->getRealPath() => base_path("stubs/skeleton/{$file->getFilename()}"), - ], 'skeleton-stubs'); - } - } - - // Testing - Testable::mixin(new TestsSkeleton); - } - - protected function getAssetPackageName(): ?string - { - return ':vendor_slug/:package_slug'; - } - - /** - * @return array - */ - protected function getAssets(): array - { - return [ - // AlpineComponent::make('skeleton', __DIR__ . '/../resources/dist/components/skeleton.js'), - Css::make('skeleton-styles', __DIR__ . '/../resources/dist/skeleton.css'), - Js::make('skeleton-scripts', __DIR__ . '/../resources/dist/skeleton.js'), - ]; - } - - /** - * @return array - */ - protected function getCommands(): array - { - return [ - SkeletonCommand::class, - ]; - } - - /** - * @return array - */ - protected function getIcons(): array - { - return []; - } - - /** - * @return array - */ - protected function getRoutes(): array - { - return []; - } - - /** - * @return array - */ - protected function getScriptData(): array - { - return []; - } - - /** - * @return array - */ - protected function getMigrations(): array - { - return [ - 'create_skeleton_table', - ]; - } -} diff --git a/src/SkeletonTheme.php b/src/SkeletonTheme.php deleted file mode 100644 index 6c647e0..0000000 --- a/src/SkeletonTheme.php +++ /dev/null @@ -1,39 +0,0 @@ -font('DM Sans') - ->primaryColor(Color::Amber) - ->secondaryColor(Color::Gray) - ->warningColor(Color::Amber) - ->dangerColor(Color::Rose) - ->successColor(Color::Green) - ->grayColor(Color::Gray) - ->theme('skeleton'); - } - - public function boot(Panel $panel): void - { - // - } -} diff --git a/src/Testing/TestsSkeleton.php b/src/Testing/TestsTwoFactorAuth.php similarity index 56% rename from src/Testing/TestsSkeleton.php rename to src/Testing/TestsTwoFactorAuth.php index 0e33b51..79d9755 100644 --- a/src/Testing/TestsSkeleton.php +++ b/src/Testing/TestsTwoFactorAuth.php @@ -1,13 +1,13 @@ $enum->name, static::cases()); + } +} diff --git a/src/Traits/EnumValuesTrait.php b/src/Traits/EnumValuesTrait.php new file mode 100644 index 0000000..582741f --- /dev/null +++ b/src/Traits/EnumValuesTrait.php @@ -0,0 +1,13 @@ + $enum->value, static::cases()); + } +} diff --git a/src/TwoFactorAuth.php b/src/TwoFactorAuth.php new file mode 100644 index 0000000..63d4909 --- /dev/null +++ b/src/TwoFactorAuth.php @@ -0,0 +1,5 @@ +userMenuItems([ + 'two-factor-authentication' => MenuItem::make() + ->icon('heroicon-o-lock-closed') + ->label(__('filament-two-factor-auth::Two-Factor Authentication')) + ->url(fn (): string => TwoFactor::getUrl()), + ]) + ->pages([ + TwoFactor::class, + ]); + } + + public function boot(Panel $panel): void + { + // + } + + public static function make(): static + { + return app(static::class); + } + + public static function get(): static + { + /** @var static $plugin */ + $plugin = filament(app(static::class)->getId()); + + return $plugin; + } +} diff --git a/src/TwoFactorAuthServiceProvider.php b/src/TwoFactorAuthServiceProvider.php new file mode 100644 index 0000000..4cbc822 --- /dev/null +++ b/src/TwoFactorAuthServiceProvider.php @@ -0,0 +1,283 @@ +name(static::$name) + ->hasCommands($this->getCommands()) + ->hasInstallCommand(function (InstallCommand $command) { + $command + ->publishConfigFile() + ->publishMigrations() + ->askToRunMigrations() + ->askToStarRepoOnGitHub('vormkracht10/filament-two-factor-auth'); + }); + + $configFileName = $package->shortName(); + + if (file_exists($package->basePath("/../config/{$configFileName}.php"))) { + $package->hasConfigFile(); + } + + if (file_exists($package->basePath('/../database/migrations'))) { + $package->hasMigrations($this->getMigrations()); + } + + if (file_exists($package->basePath('/../resources/lang'))) { + $package->hasTranslations(); + } + + if (file_exists($package->basePath('/../resources/views'))) { + $package->hasViews(static::$viewNamespace); + } + } + + public function packageRegistered(): void {} + + public function packageBooted(): void + { + // Asset Registration + // FilamentAsset::register( + // $this->getAssets(), + // $this->getAssetPackageName() + // ); + + // FilamentAsset::registerScriptData( + // $this->getScriptData(), + // $this->getAssetPackageName() + // ); + + // Icon Registration + FilamentIcon::register($this->getIcons()); + + // Handle Stubs + if (app()->runningInConsole()) { + foreach (app(Filesystem::class)->files(__DIR__ . '/../stubs/') as $file) { + $this->publishes([ + $file->getRealPath() => base_path("stubs/filament-two-factor-auth/{$file->getFilename()}"), + ], 'filament-two-factor-auth-stubs'); + } + } + + // Testing + Testable::mixin(new TestsTwoFactorAuth); + + $this->forceFortifyConfig(); + + $this->registerContractsAndComponents(); + + $this->defineRateLimiters(); + + $this->overrideFortifyViews(); + + Route::domain(config('filament.domain')) + ->middleware(config('filament.middleware.base')) + ->name('filament.') + ->group(function () { + /** + * We do not need to override logout response and logout path as: + * - logout response for both filament and fortify does + * basically the same things except fortify handle for api calls + * - for api calls still can use POST fortify's /logout route + * - filament's logout route is at /filament/logout + */ + + /** + * Redeclare filament.auth.login route as fortify override it + * This route name is used multiple places in filament. + */ + Route::prefix(config('filament.path'))->group(function () { + Route::get('/filament-login', fn () => Redirect::route('login')) + ->name('auth.login'); + }); + }); + } + + protected function forceFortifyConfig(): void + { + /** + * This is the default Fortify configuration. These seem not to be used + * in the application. I will leave them here for reference. + */ + Fortify::createUsersUsing(CreateNewUser::class); + Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class); + Fortify::updateUserPasswordsUsing(UpdateUserPassword::class); + Fortify::resetUserPasswordsUsing(ResetUserPassword::class); + + config([ + 'filament.auth.pages.login' => Login::class, + 'fortify.views' => true, + 'fortify.home' => config('filament.home_url'), + 'forms.dark_mode' => config('filament.dark_mode'), + ]); + } + + protected function defineRateLimiters(): void + { + RateLimiter::for('login', function (Request $request) { + $throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())) . '|' . $request->ip()); + + return Limit::perMinute(5)->by($throttleKey); + }); + + RateLimiter::for('two-factor', function (Request $request) { + return Limit::perMinute(5)->by($request->session()->get('login.id')); + }); + } + + protected function overrideFortifyViews(): void + { + Fortify::loginView(function () { + return app()->call(Login::class); + }); + + if (Features::enabled(Features::resetPasswords())) { + Fortify::requestPasswordResetLinkView(function () { + return app()->call(RequestPasswordReset::class); + }); + + Fortify::resetPasswordView(function ($request) { + return app()->call(PasswordReset::class); + }); + } + + if (Features::enabled(Features::emailVerification())) { + Fortify::verifyEmailView(function () { + return view('filament-two-factor-auth::auth.verify-email'); + }); + } + + Fortify::confirmPasswordView(function () { + return app()->call(PasswordConfirmation::class); + }); + + if (Features::enabled(Features::twoFactorAuthentication())) { + Fortify::twoFactorChallengeView(function () { + return app()->call(LoginTwoFactor::class); + }); + } + } + + protected function registerContractsAndComponents(): void + { + Livewire::component((new PasswordReset)->getName(), PasswordReset::class); + Livewire::component((new RequestPasswordReset)->getName(), RequestPasswordReset::class); + Livewire::component((new LoginTwoFactor)->getName(), LoginTwoFactor::class); + Livewire::component((new TwoFactor)->getName(), TwoFactor::class); + + $this->app->singleton(LoginResponseContract::class, LoginResponse::class); + $this->app->singleton(TwoFactorLoginResponseContract::class, TwoFactorLoginResponse::class); + $this->app->singleton(TwoFactorChallengeViewResponse::class, TwoFactorChallengeViewResponse::class); + } + + protected function getAssetPackageName(): ?string + { + return 'vormkracht10/filament-two-factor-auth'; + } + + /** + * @return array + */ + protected function getAssets(): array + { + return [ + // AlpineComponent::make('filament-two-factor-auth', __DIR__ . '/../resources/dist/components/filament-two-factor-auth.js'), + Css::make('filament-two-factor-auth-styles', __DIR__ . '/../resources/dist/filament-two-factor-auth.css'), + Js::make('filament-two-factor-auth-scripts', __DIR__ . '/../resources/dist/filament-two-factor-auth.js'), + ]; + } + + /** + * @return array + */ + protected function getCommands(): array + { + return [ + TwoFactorAuthCommand::class, + ]; + } + + /** + * @return array + */ + protected function getIcons(): array + { + return []; + } + + /** + * @return array + */ + protected function getRoutes(): array + { + return []; + } + + /** + * @return array + */ + protected function getScriptData(): array + { + return []; + } + + /** + * @return array + */ + protected function getMigrations(): array + { + return [ + 'create_filament-two-factor-auth_table', + ]; + } +} diff --git a/tests/Pest.php b/tests/Pest.php index 7fe1500..ef54cb7 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,5 @@ in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php index 14a77a0..ec06d55 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,6 +1,6 @@ 'VendorName\\Skeleton\\Database\\Factories\\' . class_basename($modelName) . 'Factory' + fn (string $modelName) => 'Vormkracht10\\TwoFactorAuth\\Database\\Factories\\' . class_basename($modelName) . 'Factory' ); } @@ -44,7 +44,7 @@ protected function getPackageProviders($app) SupportServiceProvider::class, TablesServiceProvider::class, WidgetsServiceProvider::class, - SkeletonServiceProvider::class, + TwoFactorAuthServiceProvider::class, ]; } @@ -53,7 +53,7 @@ public function getEnvironmentSetUp($app) config()->set('database.default', 'testing'); /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; + $migration = include __DIR__.'/../database/migrations/create_filament-two-factor-auth_table.php.stub'; $migration->up(); */ }