Skip to content

Commit

Permalink
refactor: replace Config\Services with service helper
Browse files Browse the repository at this point in the history
  • Loading branch information
yassinedoghri committed May 14, 2021
1 parent c7f79d1 commit 91db723
Show file tree
Hide file tree
Showing 16 changed files with 36 additions and 51 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,19 +113,19 @@ The following Services are provided by the package:
Provides access to any of the authentication packages that Myth:Auth knows about. By default
it will return the "Local Authentication" library, which is the basic password-based system.

$authenticate = Config\Services::authentication();
$authenticate = service('authentication');

You can specify the library to use as the first argument:

$authenticate = Config\Services::authentication('jwt');
$authenticate = service('authentication', 'jwt');

**authorization**

Provides access to any of the authorization libraries that Myth:Auth knows about. By default
it will return the "Flat" authorization library, which is a Flat RBAC (role-based access control)
as defined by NIST. It provides user-specific permissions as well as group (role) based permissions.

$authorize = Config\Services::authorization();
$authorize = service('authorization');

**passwords**

Expand All @@ -134,7 +134,7 @@ supports many of [NIST's latest Digital Identity guidelines](https://pages.nist.
validator comes with a dictionary of over 620,000 common/leaked passwords that can be checked against.
A handful of variations on the user's email/username are automatically checked against.

$authenticate = Config\Services::passwords();
$authenticate = service('passwords');

Most of the time you should not need to access this library directly, though, as a new Validation rule
is provided that can be used with the Validation library, `strong_password`. In order to enable this,
Expand Down
4 changes: 2 additions & 2 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ user against. The library does not enforce a specific set of credentials. You ar
combination of fields that exist within the `users` table, but typical uses would be either `email` or `username`.
You must include a field name `password`, though as it will be verified against the hashed version in the database.

$auth = Services::authenticate();
$auth = service('authenticate');

$credentials = [
'email' => $this->request->getPost('email', true),
Expand Down Expand Up @@ -158,7 +158,7 @@ This is done via `$requireActivation` config variable.
Confirmation can be done in many ways. Traditionally, this is usually done by sending an email to the email address that was
used during registration. We use the `Activator` service for this.

$activator = Services::activator();
$activator = service('activator');
$activator->send($user);

By default, we provide one type of activator and this is `EmailActivator`. You can also prepare your own activator,
Expand Down
2 changes: 1 addition & 1 deletion docs/authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ with users for low-level security. While the class can easily be used on it's ow
You can get an instance of the authorization library using the provided Services class, which will automatically be
detected by CodeIgniter.

$authorize = $auth = Config\Services::authorization();
$authorize = $auth = service('authorization');

Once you have this service, you have full access to all of the methods described below.

Expand Down
5 changes: 2 additions & 3 deletions src/AuthTrait.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php namespace Myth\Auth;

use Config\Services;
use CodeIgniter\Router\Exceptions\RedirectException;

trait AuthTrait {
Expand Down Expand Up @@ -168,15 +167,15 @@ public function setupAuthClasses()
/*
* Authentication
*/
$this->authenticate = Services::authentication($this->authenticationLib);
$this->authenticate = service('authentication', $this->authenticationLib);

// Try to log us in automatically.
$this->authenticate->check();

/*
* Authorization
*/
$this->authorize = Services::authorization();
$this->authorize = service('authorization');

$this->classesLoaded = true;
}
Expand Down
3 changes: 1 addition & 2 deletions src/Authentication/Activators/EmailActivator.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php namespace Myth\Auth\Authentication\Activators;

use Config\Email;
use Config\Services;
use Myth\Auth\Entities\User;

/**
Expand All @@ -22,7 +21,7 @@ class EmailActivator extends BaseActivator implements ActivatorInterface
*/
public function send(User $user = null): bool
{
$email = Services::email();
$email = service('email');
$config = new Email();

$settings = $this->getActivatorSettings();
Expand Down
7 changes: 3 additions & 4 deletions src/Authentication/AuthenticationBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use Config\App;
use CodeIgniter\Events\Events;
use CodeIgniter\Model;
use Config\Services;
use Myth\Auth\Entities\User;
use Myth\Auth\Exceptions\AuthException;
use Myth\Auth\Exceptions\UserNotFoundException;
Expand Down Expand Up @@ -85,7 +84,7 @@ public function login(User $user=null, bool $remember = false): bool
$this->user = $user;

// Always record a login attempt
$ipAddress = Services::request()->getIPAddress();
$ipAddress = service('request')->getIPAddress();
$this->recordLoginAttempt($user->email, $ipAddress, $user->id ?? null, true);

// Regenerate the session ID to help protect against session fixation
Expand All @@ -98,7 +97,7 @@ public function login(User $user=null, bool $remember = false): bool
session()->set('logged_in', $this->user->id);

// When logged in, ensure cache control headers are in place
Services::response()->noCache();
service('response')->noCache();

if ($remember && $this->config->allowRemembering)
{
Expand Down Expand Up @@ -244,7 +243,7 @@ public function rememberUser(int $userID)

// Save it to the user's browser in a cookie.
$appConfig = config('App');
$response = \Config\Services::response();
$response = service('response');

// Create the cookie
$response->setCookie(
Expand Down
7 changes: 3 additions & 4 deletions src/Authentication/LocalAuthenticator.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php namespace Myth\Auth\Authentication;

use CodeIgniter\Router\Exceptions\RedirectException;
use \Config\Services;
use Myth\Auth\Entities\User;
use Myth\Auth\Exceptions\AuthException;

Expand All @@ -22,7 +21,7 @@ public function attempt(array $credentials, bool $remember = null): bool
if (empty($this->user))
{
// Always record a login attempt, whether success or not.
$ipAddress = Services::request()->getIPAddress();
$ipAddress = service('request')->getIPAddress();
$this->recordLoginAttempt($credentials['email'] ?? $credentials['username'], $ipAddress, $this->user->id ?? null, false);

$this->user = null;
Expand All @@ -32,7 +31,7 @@ public function attempt(array $credentials, bool $remember = null): bool
if ($this->user->isBanned())
{
// Always record a login attempt, whether success or not.
$ipAddress = Services::request()->getIPAddress();
$ipAddress = service('request')->getIPAddress();
$this->recordLoginAttempt($credentials['email'] ?? $credentials['username'], $ipAddress, $this->user->id ?? null, false);

$this->error = lang('Auth.userIsBanned');
Expand All @@ -44,7 +43,7 @@ public function attempt(array $credentials, bool $remember = null): bool
if (! $this->user->isActivated())
{
// Always record a login attempt, whether success or not.
$ipAddress = Services::request()->getIPAddress();
$ipAddress = service('request')->getIPAddress();
$this->recordLoginAttempt($credentials['email'] ?? $credentials['username'], $ipAddress, $this->user->id ?? null, false);

$param = http_build_query([
Expand Down
5 changes: 2 additions & 3 deletions src/Authentication/Passwords/PwnedValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Myth\Auth\Authentication\Passwords;

use CodeIgniter\Entity;
use CodeIgniter\Config\Services;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use Myth\Auth\Exceptions\AuthException;

Expand Down Expand Up @@ -55,7 +54,7 @@ public function check(string $password, Entity $user = null): bool

try
{
$client = Services::curlrequest([
$client = service('curlrequest', [
'base_uri' => 'https://api.pwnedpasswords.com/',
]);

Expand All @@ -66,7 +65,7 @@ public function check(string $password, Entity $user = null): bool
catch(HTTPException $e)
{
$exception = AuthException::forHIBPCurlFail($e);
Services::logger()->error('[ERROR] {exception}', ['exception' => $exception]);
service('logger')->error('[ERROR] {exception}', ['exception' => $exception]);
throw $exception;
}

Expand Down
3 changes: 1 addition & 2 deletions src/Authentication/Resetters/EmailResetter.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php namespace Myth\Auth\Authentication\Resetters;

use Config\Email;
use CodeIgniter\Config\Services;
use Myth\Auth\Entities\User;

/**
Expand All @@ -22,7 +21,7 @@ class EmailResetter extends BaseResetter implements ResetterInterface
*/
public function send(User $user = null): bool
{
$email = Services::email();
$email = service('email');
$config = new Email();

$settings = $this->getResetterSettings();
Expand Down
5 changes: 2 additions & 3 deletions src/Authorization/FlatAuthorization.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use CodeIgniter\Model;
use CodeIgniter\Events\Events;
use Config\Services;
use Myth\Auth\Authorization\GroupModel;
use Myth\Auth\Authorization\PermissionModel;
use Myth\Auth\Models\UserModel;
Expand Down Expand Up @@ -485,7 +484,7 @@ public function createGroup(string $name, string $description = '')
'description' => $description,
];

$validation = Services::validation(null, false);
$validation = service('validation', null, false);
$validation->setRules([
'name' => 'required|max_length[255]|is_unique[auth_groups.name]',
'description' => 'max_length[255]',
Expand Down Expand Up @@ -631,7 +630,7 @@ public function createPermission(string $name, string $description = '')
'description' => $description,
];

$validation = Services::validation(null, false);
$validation = service('validation', null, false);
$validation->setRules([
'name' => 'required|max_length[255]|is_unique[auth_permissions.name]',
'description' => 'max_length[255]',
Expand Down
4 changes: 1 addition & 3 deletions src/Commands/CreateGroup.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Services;

class CreateGroup extends BaseCommand
{
Expand All @@ -18,8 +17,7 @@ class CreateGroup extends BaseCommand

public function run(array $params = [])
{
$db = db_connect();
$auth = Services::authorization();
$auth = service('authorization');

// consume or prompt for group name
$name = array_shift($params);
Expand Down
6 changes: 2 additions & 4 deletions src/Config/Registrar.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
<?php namespace Myth\Auth\Config;

use Config\Services;

/**
* Helper class that will register our bulk plugins
* and filters with the View Parser class.
Expand All @@ -19,8 +17,8 @@ public static function View()
{
return [
'plugins' => [
'logged_in' => [ function ($str, array $params = []) { return Services::authentication()->check() ? $str : ''; } ],
'logged_out' => [ function ($str, array $params = []) { return ! Services::authentication()->check() ? $str : ''; } ],
'logged_in' => [ function ($str, array $params = []) { return service('authentication')->check() ? $str : ''; } ],
'logged_out' => [ function ($str, array $params = []) { return ! service('authentication')->check() ? $str : ''; } ],
]
];
}
Expand Down
3 changes: 1 addition & 2 deletions src/Filters/LoginFilter.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php namespace Myth\Auth\Filters;

use Config\Services;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
Expand Down Expand Up @@ -48,7 +47,7 @@ public function before(RequestInterface $request, $params = null)
}

// if no user is logged in then send to the login form
$authenticate = Services::authentication();
$authenticate = service('authentication');
if (! $authenticate->check())
{
session()->set('redirect_url', current_url());
Expand Down
5 changes: 2 additions & 3 deletions src/Filters/PermissionFilter.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php namespace Myth\Auth\Filters;

use Config\Services;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
Expand Down Expand Up @@ -35,7 +34,7 @@ public function before(RequestInterface $request, $params = null)
return;
}

$authenticate = Services::authentication();
$authenticate = service('authentication');

// if no user is logged in then send to the login form
if (! $authenticate->check())
Expand All @@ -44,7 +43,7 @@ public function before(RequestInterface $request, $params = null)
return redirect('login');
}

$authorize = Services::authorization();
$authorize = service('authorization');
$result = true;

// Check each requested permission
Expand Down
5 changes: 2 additions & 3 deletions src/Filters/RoleFilter.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php namespace Myth\Auth\Filters;

use Config\Services;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
Expand Down Expand Up @@ -35,7 +34,7 @@ public function before(RequestInterface $request, $params = null)
return;
}

$authenticate = Services::authentication();
$authenticate = service('authentication');

// if no user is logged in then send to the login form
if (! $authenticate->check())
Expand All @@ -44,7 +43,7 @@ public function before(RequestInterface $request, $params = null)
return redirect('login');
}

$authorize = Services::authorization();
$authorize = service('authorization');

// Check each requested permission
foreach ($params as $group)
Expand Down
15 changes: 7 additions & 8 deletions src/Helpers/auth_helper.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php

use Config\Services;

if (! function_exists('logged_in'))
{
Expand All @@ -11,7 +10,7 @@
*/
function logged_in()
{
return Services::authentication()->check();
return service('authentication')->check();
}
}

Expand All @@ -24,7 +23,7 @@ function logged_in()
*/
function user()
{
$authenticate = Services::authentication();
$authenticate = service('authentication');
$authenticate->check();
return $authenticate->user();
}
Expand All @@ -39,7 +38,7 @@ function user()
*/
function user_id()
{
$authenticate = Services::authentication();
$authenticate = service('authentication');
$authenticate->check();
return $authenticate->id();
}
Expand All @@ -64,8 +63,8 @@ function user_id()
*/
function in_groups($groups): bool
{
$authenticate = Services::authentication();
$authorize = Services::authorization();
$authenticate = service('authentication');
$authorize = service('authorization');

if ($authenticate->check())
{
Expand All @@ -88,8 +87,8 @@ function in_groups($groups): bool
*/
function has_permission($permission): bool
{
$authenticate = Services::authentication();
$authorize = Services::authorization();
$authenticate = service('authentication');
$authorize = service('authorization');

if ($authenticate->check())
{
Expand Down

0 comments on commit 91db723

Please sign in to comment.