Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions packages/auth/src/Installer/AuthenticationInstaller.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ final class AuthenticationInstaller implements Installer
{
use PublishesFiles;

public bool $installOAuth = false;

private(set) string $name = 'auth';

public function __construct(
Expand All @@ -31,17 +33,28 @@ public function __construct(

public function install(): void
{
$migration = $this->publish(__DIR__ . '/basic-user/CreateUsersTableMigration.stub.php', src_path('Authentication/CreateUsersTable.php'));
$this->publish(__DIR__ . '/basic-user/UserModel.stub.php', src_path('Authentication/User.php'));
// First question, ask whether to also install OAuth, as it changes the stubs to publish
$this->installOAuth = $this->shouldInstallOAuth();

// Get the appropriate stubs
$stubPath = $this->installOAuth ? 'oauth' : 'basic-user';

// Publish the stubs
$migration = $this->publish(__DIR__ . "/{$stubPath}/CreateUsersTableMigration.stub.php", src_path('Authentication/CreateUsersTable.php'));
$this->publish(__DIR__ . "/{$stubPath}/UserModel.stub.php", src_path('Authentication/User.php'));
$this->publish(__DIR__ . '/basic-user/MustBeAuthenticated.stub.php', src_path('Authentication/MustBeAuthenticated.php'));
$this->publish(__DIR__ . '/basic-user/LoginController.stub.php', src_path('Authentication/LoginController.php'));
$this->publishImports();

// Offer to migrate
if ($migration && $this->shouldMigrate()) {
$this->migrationManager->executeUp(
migration: $this->container->get(to_fqcn($migration, root: root_path())),
);
}

if ($this->shouldInstallOAuth()) {
// Run the OAuth installer now
if ($this->installOAuth) {
$this->container->get(OAuthInstaller::class)->install();
}
}
Expand Down
2 changes: 0 additions & 2 deletions packages/auth/src/Installer/OAuthInstaller.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,12 @@ private function publishController(SupportedOAuthProvider $provider): void
'redirect-route',
'callback-route',
"'user-model-fqcn'",
'provider_db_column',
],
replace: [
"\\{$providerFqcn}::{$provider->name}",
"/auth/{$name}",
"/auth/{$name}/callback",
"\\{$userModelFqcn}::class",
"{$name}_id",
],
),
);
Expand Down
66 changes: 66 additions & 0 deletions packages/auth/src/Installer/basic-user/LoginController.stub.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Tempest\Auth\Installer;

use App\Authentication\User;
use Tempest\Auth\Authentication\Authenticator;
use Tempest\Cryptography\Password\PasswordHasher;
use Tempest\Http\Responses\Redirect;
use Tempest\Http\Session\PreviousUrl;
use Tempest\Router\Get;
use Tempest\Router\Post;
use Tempest\View\View;

use function Tempest\Database\query;
use function Tempest\View\view;

final readonly class LoginController
{
public function __construct(
private Authenticator $authenticator,
private PasswordHasher $passwordHasher,
private PreviousUrl $previousUrl,
) {}

#[Get('/auth/login')]
public function showLoginForm(): View
{
// TODO: implement, the code below is an example, and does not include a login form, customise to suit your application

return view('./your.login.view.php');
}

// This method is not required if you are implementing an OAuth-only approach
#[Post('/auth/login')]
public function login(LoginRequest $request): Redirect
{
// TODO: implement, the code below is an example, customise to suit your application

$user = query(User::class)
->select()
->where('email', $request->email)
->first();

if (! $user || ! $this->passwordHasher->verify($request->password, $user->password)) {
return new Redirect('/login')->flash('error', 'Invalid credentials');
}

$this->authenticator->authenticate($user);

// Get the intended URL and redirect there, or default to home
// getIntended() automatically consumes/removes the stored URL
$intendedUrl = $this->previousUrl->getIntended('/dashboard');

return new Redirect($intendedUrl)
->flash('success', 'Logged in successfully');
}

#[Post('/auth/logout')]
public function logout(): Redirect
{
$this->authenticator->deauthenticate();

return new Redirect('/')
->flash('success', 'You have been logged out');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Tempest\Auth\Installer;

use Tempest\Auth\Authentication\Authenticator;
use Tempest\Core\Priority;
use Tempest\Discovery\SkipDiscovery;
use Tempest\Http\Request;
use Tempest\Http\Response;
use Tempest\Http\Responses\Redirect;
use Tempest\Http\Session\PreviousUrl;
use Tempest\Router\HttpMiddleware;
use Tempest\Router\HttpMiddlewareCallable;

#[SkipDiscovery]
#[Priority(Priority::HIGHEST)]
final readonly class MustBeAuthenticated implements HttpMiddleware
{
public function __construct(
private Authenticator $authenticator,
private PreviousUrl $previousUrl,
) {}

// TODO: implement, the code below is an example, customise to suit your application

public function __invoke(Request $request, HttpMiddlewareCallable $next): Response
{
// Check if user is authenticated
$user = $this->authenticator->current();

if ($user === null) {
// Store the intended URL
$this->previousUrl->setIntended($request->path);

// Redirect to login if not authenticated
return new Redirect('/auth/login')
->flash('error', 'You must be logged in to access this page');
}

// User is authenticated, continue with request
return $next($request);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Tempest\Auth\Installer;

use Tempest\Database\MigratesUp;
use Tempest\Database\QueryStatement;
use Tempest\Database\QueryStatements\CreateTableStatement;
use Tempest\Discovery\SkipDiscovery;

#[SkipDiscovery]
final class CreateUsersTableMigration implements MigratesUp
{
public string $name = '0000-00-00_create_users_table';

public function up(): QueryStatement
{
return new CreateTableStatement('users')
->primary()
->string('email')
->string('password', nullable: true)
->string('name', nullable: true)
->string('nickname', nullable: true)
->string('avatar', nullable: true)
->string('oauth_id', nullable: true)
->string('oauth_raw', nullable: true)
->string('oauth_provider', nullable: true);
}
}
18 changes: 14 additions & 4 deletions packages/auth/src/Installer/oauth/OAuthControllerStub.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Tempest\Discovery\SkipDiscovery;
use Tempest\Http\Request;
use Tempest\Http\Responses\Redirect;
use Tempest\Http\Session\PreviousUrl;
use Tempest\Router\Get;

use function Tempest\Database\query;
Expand All @@ -21,6 +22,7 @@
public function __construct(
#[Tag('tag_name')]
private OAuthClient $oauth,
private PreviousUrl $previousUrl,
) {}

#[Get('redirect-route')]
Expand All @@ -32,19 +34,27 @@ public function redirect(): Redirect
#[Get('callback-route')]
public function callback(Request $request): Redirect
{
// TODO: implement, the code below is an example
// TODO: implement, the code below is an example, customise to suit your application

$this->oauth->authenticate(
request: $request,
map: fn (OAuthUser $user): Authenticatable => query('user-model-fqcn')->updateOrCreate([
'provider_db_column' => $user->id,
'oauth_id' => $user->id,
], [
'provider_db_column' => $user->id,
'oauth_id' => $user->id,
'username' => $user->nickname,
'email' => $user->email,
'name' => $user->name,
'nickname' => $user->nickname,
'avatar' => $user->avatar,
'oauth_raw' => $user->raw,
'oauth_provider' => 'tag_name',
]),
);

return new Redirect('/');
$intendedUrl = $this->previousUrl->getIntended('/dashboard');

return new Redirect($intendedUrl)
->flash('success', 'Logged in successfully');
}
}
27 changes: 27 additions & 0 deletions packages/auth/src/Installer/oauth/UserModel.stub.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Tempest\Auth\Installer;

use Tempest\Auth\Authentication\Authenticatable;
use Tempest\Database\Hashed;
use Tempest\Database\PrimaryKey;
use Tempest\Discovery\SkipDiscovery;

#[SkipDiscovery]
final class UserModel implements Authenticatable
{
public PrimaryKey $id;

public function __construct(
public string $email,
#[Hashed]
#[\SensitiveParameter]
public ?string $password,
public ?string $name,
public ?string $nickname,
public ?string $avatar,
public ?string $oauth_id,
public ?array $oauth_raw,
public ?string $oauth_provider,
) {}
}
26 changes: 26 additions & 0 deletions src/Tempest/Framework/Authentication/CreateUsersTable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Tempest\Framework\Authentication;

use Tempest\Database\MigratesUp;
use Tempest\Database\QueryStatement;
use Tempest\Database\QueryStatements\CreateTableStatement;

final class CreateUsersTable implements MigratesUp
{
public string $name = '0000-00-00_create_users_table';

public function up(): QueryStatement
{
return new CreateTableStatement('users')
->primary()
->string('email')
->string('password', nullable: true)
->string('name', nullable: true)
->string('nickname', nullable: true)
->string('avatar', nullable: true)
->string('oauth_id', nullable: true)
->string('oauth_raw', nullable: true)
->string('oauth_provider', nullable: true);
}
}
20 changes: 11 additions & 9 deletions tests/Integration/Auth/Installer/OAuthInstallerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,17 @@ public function install_oauth_provider(
): void {
$this->console
->call('install auth --oauth')
->confirm()
->deny()
->deny()
->input($provider->value)
->confirm()
->confirm()
->confirm()
->confirm()
->confirm()
->confirm() // Running the installer, continue?
->deny() // Publish CreateUsersTable?
->deny() // Publish User?
->deny() // Publish MustBeAuthenticated?
->deny() // Publish LoginController?
->input($provider->value) // Pick provider
->confirm() // Confirm provider
->confirm() // Publish $ProviderController
->confirm() // Publish $provider.config.php
->confirm() // Add to .env
->confirm() // Install dependencies
->assertSee('The selected OAuth provider is installed in your project')
->assertSuccess();

Expand Down
Loading