Skip to content

Commit

Permalink
feat: authenticator (#493)
Browse files Browse the repository at this point in the history
Co-authored-by: Tonko Mulder <[email protected]>
  • Loading branch information
brendt and Treggats authored Oct 2, 2024
1 parent e4bb059 commit 5017c5f
Show file tree
Hide file tree
Showing 58 changed files with 1,417 additions and 31 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ vendor/
src/Tempest/database.sqlite
tests/Fixtures/database.sqlite
tests/Unit/Console/test-console.log
src/Tempest/Database/src/database.sqlite
.env
composer.lock
debug.log
tempest.log
public/static
tests/Unit/Log
tests/Unit/Log
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"symplify/monorepo-builder": "^11.2"
},
"replace": {
"tempest/auth": "self.version",
"tempest/cache": "self.version",
"tempest/clock": "self.version",
"tempest/command-bus": "self.version",
Expand All @@ -71,6 +72,7 @@
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Tempest\\Auth\\": "src/Tempest/Auth/src/",
"Tempest\\Cache\\": "src/Tempest/Cache/src/",
"Tempest\\Clock\\": "src/Tempest/Clock/src/",
"Tempest\\CommandBus\\": "src/Tempest/CommandBus/src",
Expand Down Expand Up @@ -105,6 +107,7 @@
},
"autoload-dev": {
"psr-4": {
"Tempest\\Auth\\Tests\\": "src/Tempest/Auth/tests",
"Tempest\\Cache\\Tests\\": "src/Tempest/Cache/tests",
"Tempest\\Clock\\Tests\\": "src/Tempest/Clock/tests",
"Tempest\\CommandBus\\Tests\\": "src/Tempest/CommandBus/tests",
Expand Down
10 changes: 10 additions & 0 deletions src/Tempest/Auth/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Exclude build/test files from the release
.github/ export-ignore
tests/ export-ignore
.gitattributes export-ignore
.gitignore export-ignore
phpunit.xml export-ignore
README.md export-ignore

# Configure diff output for .php and .phar files.
*.php diff=php
9 changes: 9 additions & 0 deletions src/Tempest/Auth/LICENCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 Brent Roose [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 changes: 17 additions & 0 deletions src/Tempest/Auth/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "tempest/auth",
"description": "A flexible authentication package for Tempest, providing user authentication and authorization.",
"require": {
"php": "^8.3",
"tempest/core": "dev-main",
"tempest/http": "dev-main",
"tempest/database": "dev-main"
},
"autoload": {
"psr-4": {
"Tempest\\Auth\\": "src"
}
},
"license": "MIT",
"minimum-stability": "dev"
}
13 changes: 13 additions & 0 deletions src/Tempest/Auth/phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.4/phpunit.xsd" bootstrap="vendor/autoload.php" executionOrder="depends,defects" beStrictAboutOutputDuringTests="true" displayDetailsOnPhpunitDeprecations="true" failOnPhpunitDeprecation="false" failOnRisky="true" failOnWarning="true">
<testsuites>
<testsuite name="Tempest Auth">
<directory>tests</directory>
</testsuite>
</testsuites>
<source restrictNotices="true" restrictWarnings="true" ignoreIndirectDeprecations="true">
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
18 changes: 18 additions & 0 deletions src/Tempest/Auth/src/Allow.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Attribute;
use UnitEnum;

#[Attribute(Attribute::TARGET_METHOD)]
final readonly class Allow
{
public function __construct(
/** @var string|UnitEnum|class-string<\Tempest\Auth\Authorizer> $permission */
public string|UnitEnum $permission,
) {
}
}
23 changes: 23 additions & 0 deletions src/Tempest/Auth/src/AuthBootstrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Tempest\Core\KernelEvent;
use Tempest\EventBus\EventHandler;
use Tempest\Http\Router;

final readonly class AuthBootstrap
{
public function __construct(
private Router $router
) {
}

#[EventHandler(KernelEvent::BOOTED)]
public function __invoke(): void
{
$this->router->addMiddleware(AuthorizerMiddleware::class);
}
}
17 changes: 17 additions & 0 deletions src/Tempest/Auth/src/AuthConfig.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

final class AuthConfig
{
public function __construct(
/** @var class-string<\Tempest\Auth\Authenticator> */
public string $authenticatorClass = SessionAuthenticator::class,

/** @var class-string<\Tempest\Database\DatabaseModel> */
public string $userModelClass = User::class,
) {
}
}
14 changes: 14 additions & 0 deletions src/Tempest/Auth/src/Authenticator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

interface Authenticator
{
public function login(CanAuthenticate $user): void;

public function logout(): void;

public function currentUser(): ?CanAuthenticate;
}
20 changes: 20 additions & 0 deletions src/Tempest/Auth/src/AuthenticatorInitializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Tempest\Container\Container;
use Tempest\Container\Initializer;
use Tempest\Container\Singleton;

final readonly class AuthenticatorInitializer implements Initializer
{
#[Singleton]
public function initialize(Container $container): Authenticator
{
$authConfig = $container->get(AuthConfig::class);

return $container->get($authConfig->authenticatorClass);
}
}
10 changes: 10 additions & 0 deletions src/Tempest/Auth/src/Authorizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

interface Authorizer
{
public function authorize(CanAuthorize $user): bool;
}
58 changes: 58 additions & 0 deletions src/Tempest/Auth/src/AuthorizerMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Tempest\Container\Container;
use Tempest\Http\HttpMiddleware;
use Tempest\Http\MatchedRoute;
use Tempest\Http\Request;
use Tempest\Http\Response;
use Tempest\Http\Responses\Forbidden;

final readonly class AuthorizerMiddleware implements HttpMiddleware
{
public function __construct(
private Authenticator $authenticator,
private MatchedRoute $matchedRoute,
private Container $container,
) {
}

public function __invoke(Request $request, callable $next): Response
{
$attribute = $this->matchedRoute
->route
->handler
->getAttribute(Allow::class);

if ($attribute === null) {
return $next($request);
}

$user = $this->authenticator->currentUser();

if (! $user instanceof CanAuthorize) {
return new Forbidden();
}

$permission = $attribute->permission;

if (is_a($permission, Authorizer::class, true)) {
/** @var class-string<\Tempest\Auth\Authorizer> $permission */
/** @var Authorizer $authorizer */
$authorizer = $this->container->get($permission);

$isAllowed = $authorizer->authorize($user);
} else {
$isAllowed = $user->hasPermission($permission);
}

if (! $isAllowed) {
return new Forbidden();
}

return $next($request);
}
}
11 changes: 11 additions & 0 deletions src/Tempest/Auth/src/CanAuthenticate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Tempest\Database\DatabaseModel;

interface CanAuthenticate extends DatabaseModel
{
}
12 changes: 12 additions & 0 deletions src/Tempest/Auth/src/CanAuthorize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use UnitEnum;

interface CanAuthorize
{
public function hasPermission(string|UnitEnum $permission): bool;
}
7 changes: 7 additions & 0 deletions src/Tempest/Auth/src/Config/auth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

declare(strict_types=1);

use Tempest\Auth\AuthConfig;

return new AuthConfig();
29 changes: 29 additions & 0 deletions src/Tempest/Auth/src/CreatePermissionsTable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Tempest\Database\Migration;
use Tempest\Database\QueryStatements\CreateTableStatement;
use Tempest\Database\QueryStatements\DropTableStatement;

final readonly class CreatePermissionsTable implements Migration
{
public function getName(): string
{
return '0000-00-01_create_permissions_table';
}

public function up(): CreateTableStatement
{
return (new CreateTableStatement('permissions'))
->primary()
->varchar('name');
}

public function down(): DropTableStatement
{
return DropTableStatement::forModel(Permission::class);
}
}
30 changes: 30 additions & 0 deletions src/Tempest/Auth/src/CreateUserPermissionTable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Tempest\Database\Migration;
use Tempest\Database\QueryStatements\CreateTableStatement;
use Tempest\Database\QueryStatements\DropTableStatement;

final readonly class CreateUserPermissionTable implements Migration
{
public function getName(): string
{
return '0000-00-02_create_user_permissions_table';
}

public function up(): CreateTableStatement
{
return (new CreateTableStatement('user_permissions'))
->primary()
->belongsTo('user_permissions.user_id', 'users.id')
->belongsTo('user_permissions.permission_id', 'permissions.id');
}

public function down(): DropTableStatement
{
return DropTableStatement::forModel(Permission::class);
}
}
32 changes: 32 additions & 0 deletions src/Tempest/Auth/src/CreateUsersTable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Tempest\Auth;

use Tempest\Database\Migration;
use Tempest\Database\QueryStatements\CreateTableStatement;
use Tempest\Database\QueryStatements\DropTableStatement;

final readonly class CreateUsersTable implements Migration
{
public function getName(): string
{
return '0000-00-00_create_users_table';
}

public function up(): CreateTableStatement
{
return (new CreateTableStatement('users'))
->primary()
->varchar('name')
->varchar('email')
->datetime('emailValidatedAt', nullable: true)
->text('password');
}

public function down(): DropTableStatement
{
return DropTableStatement::forModel(User::class);
}
}
Loading

0 comments on commit 5017c5f

Please sign in to comment.