diff --git a/docs/customization/route_config.md b/docs/customization/route_config.md index 7b06c7d70..8596e41b6 100644 --- a/docs/customization/route_config.md +++ b/docs/customization/route_config.md @@ -29,6 +29,16 @@ service('auth')->routes($routes, ['namespace' => '\App\Controllers\Auth']); This will generate the routes with the specified namespace instead of the default Shield namespace. This can be combined with any other options, like `except`. +## Change Prefix + +If you wish, you can prefix all defined authentication routes using the `group` option. This is particularly useful if you want all your routes to be under the same root (for example, `auth/login`, `auth/register`). + +```php +service('auth')->routes($routes, ['group' => 'auth']); +``` + +This generates routes whose paths are all prefixed with `auth`. + ## Use Locale Routes You can use the `{locale}` placeholder in your routes diff --git a/src/Auth.php b/src/Auth.php index fedee8a97..d56d287b8 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -131,14 +131,16 @@ public function authenticate(array $credentials): Result * Usage (in Config/Routes.php): * - auth()->routes($routes); * - auth()->routes($routes, ['except' => ['login', 'register']]) + * - auth()->routes($routes, ['group' => 'auth']) */ public function routes(RouteCollection &$routes, array $config = []): void { $authRoutes = config('AuthRoutes')->routes; $namespace = $config['namespace'] ?? 'CodeIgniter\Shield\Controllers'; + $group = $config['group'] ?? '/'; - $routes->group('/', ['namespace' => $namespace], static function (RouteCollection $routes) use ($authRoutes, $config): void { + $routes->group($group, ['namespace' => $namespace], static function (RouteCollection $routes) use ($authRoutes, $config): void { foreach ($authRoutes as $name => $row) { if (! isset($config['except']) || ! in_array($name, $config['except'], true)) { foreach ($row as $params) { diff --git a/tests/Unit/AuthRoutesTest.php b/tests/Unit/AuthRoutesTest.php index d4e568121..b8b5747f6 100644 --- a/tests/Unit/AuthRoutesTest.php +++ b/tests/Unit/AuthRoutesTest.php @@ -80,4 +80,24 @@ public function testRoutesCustomNamespace(): void $this->assertSame('\Auth\RegisterController::registerView', $routes['register']); } + + public function testRoutesCustomPrefix(): void + { + $collection = single_service('routes'); + $auth = service('auth'); + + $auth->routes($collection, ['group' => 'auth']); + + if (version_compare(CodeIgniter::CI_VERSION, '4.5') >= 0) { + $routes = $collection->getRoutes('GET'); + } else { + $routes = $collection->getRoutes('get'); + } + + $this->assertArrayHasKey('auth/register', $routes); + $this->assertArrayHasKey('auth/login', $routes); + $this->assertArrayHasKey('auth/login/magic-link', $routes); + $this->assertArrayHasKey('auth/logout', $routes); + $this->assertArrayHasKey('auth/auth/a/show', $routes); + } }