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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
"azure-oss/storage-blob-flysystem": "^1.2",
"brianium/paratest": "^7.14",
"carthage-software/mago": "1.0.0-beta.28",
"depotwarehouse/oauth2-twitch": "^1.3",
"guzzlehttp/psr7": "^2.6.1",
"league/flysystem-aws-s3-v3": "^3.25.1",
"league/flysystem-ftp": "^3.25.1",
Expand Down Expand Up @@ -88,6 +87,7 @@
"tempest/blade": "dev-main",
"thenetworg/oauth2-azure": "^2.2",
"twig/twig": "^3.16",
"vertisan/oauth2-twitch-helix": "^2.0",
"wohali/oauth2-discord-new": "^1.2"
},
"replace": {
Expand Down
1 change: 1 addition & 0 deletions docs/2-features/17-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ Tempest provides a different configuration object for each OAuth provider. Below
- **Microsoft** authentication using {b`Tempest\Auth\OAuth\Config\MicrosoftOAuthConfig`},
- **Slack** authentication using {b`Tempest\Auth\OAuth\Config\SlackOAuthConfig`},
- **Apple** authentication using {b`Tempest\Auth\OAuth\Config\AppleOAuthConfig`},
- **Twitch** authentication using {b`Tempest\Auth\OAuth\Config\TwitchHelixOAuthConfig`},
- Any other OAuth platform using {b`Tempest\Auth\OAuth\Config\GenericOAuthConfig`}.

## Testing
Expand Down
2 changes: 1 addition & 1 deletion packages/auth/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"adam-paterson/oauth2-slack": "^1.1",
"wohali/oauth2-discord-new": "^1.2",
"smolblog/oauth2-twitter": "^1.0",
"depotwarehouse/oauth2-twitch": "^1.3"
"vertisan/oauth2-twitch-helix": "^2.0"
},
"autoload": {
"psr-4": {
Expand Down
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,
) {}
}
15 changes: 15 additions & 0 deletions packages/auth/src/Installer/oauth/twitchhelix.config.stub.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

use Tempest\Auth\OAuth\Config\TwitchHelixOAuthConfig;
use Tempest\Auth\OAuth\SupportedOAuthProvider;

use function Tempest\env;

return new TwitchHelixOAuthConfig(
clientId: env('OAUTH_TWITCH_CLIENT_ID') ?? '',
clientSecret: env('OAUTH_TWITCH_CLIENT_SECRET') ?? '',
redirectTo: [\Tempest\Auth\Installer\oauth\OAuthControllerStub::class, 'callback'],
tag: SupportedOAuthProvider::TWITCH,
);
73 changes: 73 additions & 0 deletions packages/auth/src/OAuth/Config/TwitchHelixOAuthConfig.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth\OAuth\Config;

use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
use Tempest\Auth\OAuth\OAuthConfig;
use Tempest\Auth\OAuth\OAuthUser;
use Tempest\Mapper\ObjectFactory;
use UnitEnum;
use Vertisan\OAuth2\Client\Provider\TwitchHelix;
use Vertisan\OAuth2\Client\Provider\TwitchHelixResourceOwner;

final class TwitchHelixOAuthConfig implements OAuthConfig
{
public string $provider = TwitchHelix::class;

public function __construct(
/**
* The client ID for the TwitchHelix OAuth application.
*/
public string $clientId,

/**
* The client secret for the TwitchHelix OAuth application.
*/
public string $clientSecret,

/**
* The controller action to redirect to after the user authorizes the application.
*/
public string|array $redirectTo,

/**
* The scopes to request from TwitchHelix.
*
* @var string[]
*/
public array $scopes = ['user:read:email'],

/**
* Identifier for this OAuth configuration.
*/
public null|string|UnitEnum $tag = null,
) {}

public function createProvider(): AbstractProvider
{
return new TwitchHelix([
'clientId' => $this->clientId,
'clientSecret' => $this->clientSecret,
'redirectUri' => $this->redirectTo,
]);
}

/**
* @param TwitchHelixResourceOwner $resourceOwner
*/
public function mapUser(ObjectFactory $factory, ResourceOwnerInterface $resourceOwner): OAuthUser
{
return $factory->withData([
'id' => (string) $resourceOwner->getId(),
'email' => $resourceOwner->getEmail(),
'name' => $resourceOwner->getDisplayName(),
'nickname' => $resourceOwner->getDisplayName(),
'avatar' => $resourceOwner->getProfileImageUrl(),
'provider' => $this->provider,
'raw' => $resourceOwner->toArray(),
])->to(OAuthUser::class);
}
}
Loading
Loading