Nano Auth is a library that allows you to create authentication for your apps.
Strictly requires PHP 7.4.
Via Composer
$ composer require midorikocak/nanoauth
The Authentication class has 4 public methods that you can use:
<?php
declare(strict_types=1);
namespace midorikocak\nanoauth;
interface AuthenticationInterface
{
public function login(string $username, string $password): bool;
public function logout(): void;
public function isLogged(): bool;
public function getLoggedUser();
}
To use it you should supply with a user repository.
$db = new Database(new PDO('sqlite::memory:'));
$userRepository = new UserRepository($db);
$auth = new Authentication($userRepository);
A user object that we can authenticate should implemennt UserInterface
.
<?php
declare(strict_types=1);
namespace midorikocak\nanoauth;
interface UserInterface
{
public function __construct(?string $id, string $username, string $email, string $password);
public function getPassword(): string;
public function getUsername(): string;
public function getEmail(): string;
public function getId(): ?string;
public function setId(string $id): void;
}
To interact with user data, we need to supply user repository to our authentication object. If you want to use your own
implementation of user repository, you can implement your own UserInnterface
.
Here repository constructor expects a NanoDB
object.
$userRepository = new UserRepository($db);
$auth = new Authentication($userRepository);
To add authentication and authorization capabilities,
you can use AuthorizationTrait
in your App classes.
Let's say we created our app in this way:
<?php
declare(strict_types=1);
use midorikocak\nanodb\Database;
use midorikocak\nanoauth\UserRepository;
use midorikocak\nanoauth\Authentication;
$db = new Database(new PDO('sqlite::memory:'));
$userRepository = new UserRepository($db);
$auth = new Authentication($userRepository);
$entryRepository = new Journal($db);
$app = new App($entryRepository);
$this->app->setAuthentication($this->auth);
To check login we should trigger checkLogin()
method in our public methods.
<?php
declare(strict_types=1);
use midorikocak\nanodb\Database;
use midorikocak\nanoauth\UserRepository;
use midorikocak\nanoauth\Authentication;
use midorikocak\nanoauth\AuthorizationTrait;
class App
{
use AuthorizationTrait;
private Journal $journal;
public function __construct(Journal $journal)
{
$this->journal = $journal;
}
public function addEntry(string $content)
{
$this->checkLogin();
$entry = new Entry($content);
$this->journal->save($entry);
}
}
Mostly educational purposes.
Please see CHANGELOG for more information on what has changed recently.
$ composer test
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.