Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.x] Adds runtime token id #1

Merged
merged 2 commits into from
Sep 4, 2024
Merged
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
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,16 @@ Route::post('{party}/confirm', function (Request $request, Party $party) {

## ID Generator

By default, a token ID is an ULID, created by [`Str::ulid()`](https://laravel.com/docs/11.x/strings#method-str-ulid). You can change it for anything by setting the `Token::$generator` static property the `boot()` method of your `AppServiceProvider`.
By default, a token ID is an ULID, created by [`Str::ulid()`](https://laravel.com/docs/11.x/strings#method-str-ulid). You can change it for anything by using the `as()` method at runtime. It accepts a string, or a Closure that returns a string.

```php
use Laragear\TokenAction\Facades\Token;
use Illuminate\Support\Str;

$token = Token::store('redis')->as(Str::random(32))->until(60);
```

Alternatively, you may use the `Token::$generator` static property the `boot()` method of your `AppServiceProvider` with a Closure that returns a random string.

```php
namespace App\Providers;
Expand All @@ -342,6 +351,10 @@ class AppServiceProvider extends ServiceProvider
}
```

> [!NOTE]
>
> The string to generate will be [prefixed](#cache) to avoid cache key collisions.

## Configuration

To further configure the package, publish the configuration file:
Expand Down
29 changes: 26 additions & 3 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
namespace Laragear\TokenAction;

use Carbon\CarbonImmutable;
use Closure;
use DateTimeInterface;
use Laragear\TokenAction\Exceptions\TokenNotFound;
use ValueError;
use function is_int;
use function value;

class Builder
{
Expand All @@ -18,6 +20,7 @@
protected DateTimeInterface|int|string|null $expires = null,
protected int $tries = 1,
protected mixed $with = null,
protected Closure|string|null $as = null
)
{
//
Expand Down Expand Up @@ -45,7 +48,7 @@
$this->tries = $tries;

if ($this->tries < 1) {
throw new ValueError("Cannot assign less than 1 tries to a Token.");
throw new ValueError('Cannot assign less than 1 tries to a Token.');
}

return $this;
Expand All @@ -63,6 +66,19 @@
return $this;
}

/**
* The token ID that should be used to store it, without prefix.
*
* @param (\Closure():string)|string $token
* @return $this
*/
public function as(Closure|string $token): static
{
$this->as = $token;

return $this;
}

/**
* Creates a new Token instance, optionally with a custom payload.
*/
Expand Down Expand Up @@ -90,8 +106,15 @@
*/
protected function generateTokenId(): string
{
return (Token::$generator)()
?: throw new ValueError('The Token ID generator should return a non-empty string.');
if ($this->as) {
return value($this->as);
}

if (isset(Token::$generator)) {
return (Token::$generator)();
}

throw new ValueError('The Token ID generator is not set.');

Check warning on line 117 in src/Builder.php

View check run for this annotation

Codecov / codecov/patch

src/Builder.php#L117

Added line #L117 was not covered by tests
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/Facades/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* @method static \Laragear\TokenAction\Builder action(string $action)
* @method static \Laragear\TokenAction\Builder tries(int $tries)
* @method static \Laragear\TokenAction\Builder with(mixed $with)
* @method static \Laragear\TokenAction\Builder as(\Closure|string $as)
* @method static \Laragear\TokenAction\Token until(\DateTimeInterface|int|string $expires)
* @method static \Laragear\TokenAction\Token|null find(string $id)
* @method static \Laragear\TokenAction\Token findOrFail(string $id)
Expand Down
2 changes: 1 addition & 1 deletion src/Store.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ protected function restoreCollection(ModelIdentifier $value): Collection
*/
protected function restoreModel(ModelIdentifier $value): Model
{
return $this->getQueryForModelRestoration( // @phpstan-ignore-line
return $this->getQueryForModelRestoration(
(new $value->class)->setConnection($value->connection), $value->id
)->useWritePdo()->firstOrFail()->load($value->relations ?? []); // @phpstan-ignore-line
}
Expand Down
18 changes: 18 additions & 0 deletions tests/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,24 @@ public function test_with(): void
$this->builder->with(true)->until(now());
}

public function test_as(): void
{
$this->store->expects('put')->withArgs(static function (Token $token): bool {
return 'test-id' === $token->id;
});

$this->builder->as('test-id')->until(now());
}

public function test_as_with_closure(): void
{
$this->store->expects('put')->withArgs(static function (Token $token): bool {
return 'test-id' === $token->id;
});

$this->builder->as(fn() => 'test-id')->until(now());
}

public function test_until_given_datetime(): void
{
$until = now()->addMinute();
Expand Down
Loading