Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
Signed-off-by: Sam Poyigi <[email protected]>
  • Loading branch information
sampoyigi committed Dec 11, 2024
1 parent c03a845 commit 2591d7c
Show file tree
Hide file tree
Showing 94 changed files with 5,913 additions and 354 deletions.
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ Auth::logout();
For a streamlined approach to authenticating customers in TastyIgniter, you can use the `\Igniter\User\Actions\LoginUser` action class. This class mirrors the authentication process used by the default login form. It also dispatches two key events — `igniter.user.beforeAuthenticate` and `igniter.user.login` — which can be used to hook into the login process for custom behavior or integrations.

```php
use Igniter\User\Actions\LoginUser;
use Igniter\User\Actions\LoginCustomer;

$loginUser = new LoginUser($credentials, $remember);
$loginUser = new LoginCustomer($credentials, $remember);
$loginUser->handle();
```

Expand Down Expand Up @@ -149,7 +149,7 @@ AdminAuth::getProvider()->register($staffData);
For a streamlined approach to registering customers in TastyIgniter, you can use the `\Igniter\User\Actions\RegisterUser` action class. This class mirrors the registration process used by the default registration form. It also dispatches two key events — `igniter.user.beforeRegister` and `igniter.user.register` — which can be used to hook into the registration process for custom behavior or integrations.

```php
use Igniter\User\Actions\RegisterUser;
use Igniter\User\Actions\RegisterCustomer;

$data = [
'first_name' => 'John',
Expand All @@ -158,7 +158,7 @@ $data = [
'password' => 'password',
];

$registerUser = new RegisterUser();
$registerUser = new RegisterCustomer();
$customer = $registerUser->handle($data);

if ($customer->is_activated) {
Expand All @@ -175,9 +175,9 @@ if ($customer->is_activated) {
The `activate` method can be used to activate a customer account.

```php
use Igniter\User\Actions\RegisterUser;
use Igniter\User\Actions\RegisterCustomer;

$registerUser = new RegisterUser();
$registerUser = new RegisterCustomer();
$registerUser->activate();

$registerUser->sendRegisteredMail(['account_login_link' => page_url('account.login')]);
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
],
"require": {
"spatie/laravel-activitylog": "^4.8",
"tastyigniter/core": "^v4.0@beta"
"tastyigniter/core": "^v4.0@beta || ^v4.0@dev"
},
"require-dev": {
"laravel/pint": "^1.2",
Expand Down Expand Up @@ -55,5 +55,5 @@
},
"sort-packages": true
},
"minimum-stability": "beta"
"minimum-stability": "dev"
}
3 changes: 3 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_KEY" value="base64:YzE5YjR2b3hrem1ucmdmc2Fkbm92NW1veHBkMWdpa3k="/>
<env name="DB_CONNECTION" value="mysql"/>
<env name="DB_DATABASE" value="testbench"/>
<env name="DB_USERNAME" value="forge"/>
</php>
<source>
<include>
Expand Down
9 changes: 5 additions & 4 deletions src/Actions/LoginUser.php → src/Actions/LoginCustomer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,22 @@
use Igniter\Flame\Exception\FlashException;
use Igniter\User\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Session;

class LoginUser
class LoginCustomer
{
public function __construct(public array $credentials, public bool $remember = true) {}

public function handle()
{
Event::fire('igniter.user.beforeAuthenticate', [$this, $this->credentials]);
Event::dispatch('igniter.user.beforeAuthenticate', [$this, $this->credentials]);

if (!Auth::attempt($this->credentials, $this->remember)) {

Check failure on line 18 in src/Actions/LoginCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.3) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::attempt().

Check failure on line 18 in src/Actions/LoginCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.2) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::attempt().
throw new FlashException(lang('igniter.user::default.login.alert_invalid_login'));
}

session()->regenerate();
Session::regenerate();

Event::fire('igniter.user.login', [$this], true);
Event::dispatch('igniter.user.login', [$this], true);
}
}
9 changes: 5 additions & 4 deletions src/Actions/LogoutUser.php → src/Actions/LogoutCustomer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

use Igniter\User\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Session;

class LogoutUser
class LogoutCustomer
{
public function handle()
{
Expand All @@ -16,12 +17,12 @@ public function handle()
} else {
Auth::logout();

Check failure on line 18 in src/Actions/LogoutCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.3) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::logout().

Check failure on line 18 in src/Actions/LogoutCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.2) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::logout().

session()->invalidate();
Session::invalidate();

session()->regenerateToken();
Session::regenerateToken();

if ($user) {
Event::fire('igniter.user.logout', [$user]);
Event::dispatch('igniter.user.logout', [$user]);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
use Igniter\User\Models\CustomerGroup;
use Illuminate\Support\Facades\Event;

class RegisterUser
class RegisterCustomer
{
public Customer $customer;

public function handle(array $data = []): Customer
{
Event::fire('igniter.user.beforeRegister', [&$data]);
Event::dispatch('igniter.user.beforeRegister', [&$data]);

$customerGroup = CustomerGroup::getDefault();
$data['customer_group_id'] = $customerGroup?->getKey();
Expand All @@ -24,7 +24,7 @@ public function handle(array $data = []): Customer

$customer = Auth::getProvider()->register($data, $autoActivation);

Check failure on line 25 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.3) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::getProvider().

Check failure on line 25 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.2) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::getProvider().

Event::fire('igniter.user.register', [$customer, $data]);
Event::dispatch('igniter.user.register', [$customer, $data]);

if ($autoActivation) {
Auth::login($customer);

Check failure on line 30 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.3) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::login().

Check failure on line 30 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.2) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::login().
Expand All @@ -35,11 +35,11 @@ public function handle(array $data = []): Customer

public function activate(string $code)
{
throw_unless($customer = Customer::whereActivationCode($code)->first(),
new ApplicationException(lang('igniter.user::default.reset.alert_activation_failed')));
throw_unless($customer = Customer::whereActivationCode($code)->first(), new ApplicationException(

Check failure on line 38 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.3) / PHP Tests

Call to an undefined static method Igniter\User\Models\Customer::whereActivationCode().

Check failure on line 38 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.2) / PHP Tests

Call to an undefined static method Igniter\User\Models\Customer::whereActivationCode().
lang('igniter.user::default.reset.alert_activation_failed'),
));

throw_unless($customer->completeActivation($code),
new ApplicationException(lang('igniter.user::default.reset.alert_activation_failed')));
throw_unless($customer->completeActivation($code), new ApplicationException('User is already active!'));

Auth::login($customer);

Check failure on line 44 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.3) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::login().

Check failure on line 44 in src/Actions/RegisterCustomer.php

View workflow job for this annotation

GitHub Actions / php-tests (8.2) / PHP Tests

Call to an undefined static method Igniter\User\Facades\Auth::login().

Expand Down
4 changes: 2 additions & 2 deletions src/Classes/Notification.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ class Notification extends BaseNotification implements ShouldQueue

protected ?string $iconColor = null;

public static function make(array $parameters = []): static
public static function make(): static
{
return app(static::class, $parameters);
return app(static::class, func_get_args());
}

public function broadcast(array $users = []): static
Expand Down
71 changes: 29 additions & 42 deletions src/Classes/PermissionManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class PermissionManager
{
protected $permissions;
protected $permissions = [];

/**
* @var array A cache of permissions.
Expand Down Expand Up @@ -65,9 +65,7 @@ public function listGroupedPermissions()
$grouped = [];

foreach ($this->listPermissions() as $permission) {
$group = isset($permission->group)
? strtolower($permission->group)
: 'Undefined group';
$group = strtolower(strlen($permission->group) ? $permission->group : 'Undefined group');

$permission->group ??= $group;

Expand Down Expand Up @@ -106,53 +104,46 @@ public function checkPermission($permissions, $checkPermissions, $checkAll)

protected function checkPermissionStartsWith($permission, $permissions)
{
if (strlen($permission) > 1 && ends_with($permission, '*')) {
$checkPermission = substr($permission, 0, -1);

foreach ($permissions as $groupPermission => $permitted) {
// Let's make sure the available permission starts with our permission
if ($checkPermission != $groupPermission
&& starts_with($groupPermission, $checkPermission)
&& $permitted == 1
) {
return true;
}
$checkPermission = (strlen($permission) > 1 && ends_with($permission, '*'))
? substr($permission, 0, -1) : $permission;

foreach ($permissions as $groupPermission => $permitted) {
$groupPermission = (strlen($groupPermission) > 1 && ends_with($groupPermission, '*'))
? substr($groupPermission, 0, -1) : $groupPermission;

// Let's make sure the available permission starts with our permission
if ($checkPermission != $groupPermission
&& (starts_with($groupPermission, $checkPermission) || starts_with($checkPermission, $groupPermission))
&& $permitted == 1
) {
return true;
}
}
}

protected function checkPermissionEndsWith($permission, $permissions)
{
if (strlen($permission) > 1 && starts_with($permission, '*')) {
$checkPermission = substr($permission, 1);

foreach ($permissions as $groupPermission => $permitted) {
// Let's make sure the available permission ends with our permission
if ($checkPermission != $groupPermission
&& ends_with($groupPermission, $checkPermission)
&& $permitted == 1
) {
return true;
}
$checkPermission = (strlen($permission) > 1 && starts_with($permission, '*'))
? substr($permission, 1) : $permission;

foreach ($permissions as $groupPermission => $permitted) {
$groupPermission = (strlen($groupPermission) > 1 && starts_with($groupPermission, '*'))
? substr($groupPermission, 1) : $groupPermission;

// Let's make sure the available permission ends with our permission
if ($checkPermission != $groupPermission
&& (ends_with($groupPermission, $checkPermission) || ends_with($checkPermission, $groupPermission))
&& $permitted == 1
) {
return true;
}
}
}

protected function checkPermissionMatches($permission, $permissions)
{
foreach ($permissions as $groupPermission => $permitted) {
if ((strlen($groupPermission) > 1) && ends_with($groupPermission, '*')) {
$checkMergedPermission = substr($groupPermission, 0, -1);

// Let's make sure the our permission starts with available permission
if ($checkMergedPermission != $permission
&& starts_with($permission, $checkMergedPermission)
&& $permitted == 1
) {
return true;
}
} // Match permissions explicitly.
elseif ($permission == $groupPermission && $permitted == 1) {
if ($permission == $groupPermission && $permitted == 1) {
return true;
}
}
Expand All @@ -164,10 +155,6 @@ protected function checkPermissionMatches($permission, $permissions)

public function registerPermissions($owner, array $definitions)
{
if (!$this->permissions) {
$this->permissions = [];
}

foreach ($definitions as $code => $definition) {
if (!isset($definition['label']) && isset($definition['description'])) {
$definition['label'] = $definition['description'];
Expand Down
4 changes: 2 additions & 2 deletions src/Classes/UserState.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public static function getClearAfterMinutesDropdownOptions()

public function updateState(string $status, string $message, int $clearAfterMinutes = 30)
{
UserPreference::onUser()->set(self::USER_PREFERENCE_KEY, array_merge($this->defaultStateConfig, [
UserPreference::onUser($this->user)->set(self::USER_PREFERENCE_KEY, array_merge($this->defaultStateConfig, [
'status' => $status,
'updatedAt' => now(),
'awayMessage' => e($message),
Expand All @@ -130,7 +130,7 @@ public function updateState(string $status, string $message, int $clearAfterMinu
$this->stateConfigCache = null;
}

protected function getConfig($key = null, $default = null)
public function getConfig($key = null, $default = null)
{
if (is_null($this->stateConfigCache)) {
$this->stateConfigCache = $this->loadConfigFromPreference();
Expand Down
11 changes: 4 additions & 7 deletions src/Console/Commands/ClearUserStateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,15 @@ public function handle(): void
->where('value->clearAfterMinutes', '!=', 0)
->get()
->each(function($preference) {
$state = json_decode($preference->value);
if (!$state->clearAfterMinutes) {
return true;
}

if (now()->lessThan(make_carbon($state->updatedAt)->addMinutes($state->clearAfterMinutes))) {
$clearAfterMinutes = $preference->value['clearAfterMinutes'] ?? 0;
$updatedAt = $preference->value['updatedAt'] ?? null;
if (!$clearAfterMinutes || now()->lessThan(make_carbon($updatedAt)->addMinutes($clearAfterMinutes))) {
return true;
}

UserPreference::query()
->where('id', $preference->id)
->update(['value' => json_encode((new static)->defaultStateConfig)]);
->update(['value' => json_encode((new UserState)->getConfig())]);
});
}
}
2 changes: 1 addition & 1 deletion src/Database/Factories/UserFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function definition(): array
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'activated_at' => $this->faker->dateTime()->format(DateTimeInterface::ATOM),
'is_activated' => $this->faker->boolean(),
'super_user' => $this->faker->boolean(),
'super_user' => false,
'status' => $this->faker->boolean(),
];
}
Expand Down
5 changes: 4 additions & 1 deletion src/Database/Factories/UserRoleFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ public function definition(): array
'code' => $this->faker->slug(2),
'name' => $this->faker->sentence(2),
'description' => $this->faker->paragraph(),
'permissions' => [$this->faker->numberBetween(1, 99)],
'permissions' => [
'Admin.Dashboard' => 1,
'Admin.Users' => 1,
],
];
}
}
15 changes: 1 addition & 14 deletions src/Extension.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,27 +249,14 @@ public function registerFormWidgets(): array
protected function registerEventGlobalParams()
{
if (class_exists(\Igniter\Automation\Classes\EventManager::class)) {
resolve(\Igniter\Automation\Classes\EventManager::class)->registerCallback(function($manager) {
resolve(\Igniter\Automation\Classes\EventManager::class)->registerCallback(function(\Igniter\Automation\Classes\EventManager $manager) {
$manager->registerGlobalParams([
'customer' => Auth::customer(),
]);
});
}
}

protected function registerRequestRebindHandler()
{
$this->app->rebinding('request', function($app, $request) {
$request->setUserResolver(function() use ($app) {
if (!Igniter::runningInAdmin()) {
return $app['admin.auth']->getUser();
}

return $app['main.auth']->user();
});
});
}

protected function configureRateLimiting()
{
RateLimiter::for('web', function(\Illuminate\Http\Request $request) {
Expand Down
Loading

0 comments on commit 2591d7c

Please sign in to comment.