midorikocak/nanoauth

Nano Auth 是一个库,允许您为您的应用程序创建身份验证。

v1.1.2 2020-03-28 19:36 UTC

This package is auto-updated.

Last update: 2024-09-08 06:47:27 UTC


README

Nano Auth

Nano Auth

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Nano Auth 是一个库,允许您为您的应用程序创建身份验证。

要求

严格要求 PHP 7.4。

安装

通过 Composer

$ composer require midorikocak/nanoauth

用法

身份验证

身份验证类有 4 个公共方法可供使用

<?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();
}

要使用它,您应该提供用户存储库。

$db = new Database(new PDO('sqlite::memory:'));
$userRepository = new UserRepository($db);
$auth = new Authentication($userRepository);

用户

我们可以进行身份验证的用户对象应该实现 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;
}

用户存储库

为了与用户数据交互,我们需要向我们的身份验证对象提供用户存储库。如果您想使用您自己的用户存储库实现,您可以实现自己的 UserInterface。这里存储库构造函数期望一个 NanoDB 对象。

$userRepository = new UserRepository($db);
$auth = new Authentication($userRepository);

授权

要添加身份验证和授权功能,您可以在您的应用程序类中使用 AuthorizationTrait

假设我们这样创建了我们的应用程序

<?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);

要检查登录,我们应该在我们的公开方法中触发 checkLogin() 方法。

<?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);
    }
}

动机

主要是教育目的。

变更日志

请参阅 CHANGELOG 了解最近更改的更多信息。

测试

$ composer test

贡献

请参阅 CONTRIBUTINGCODE_OF_CONDUCT 了解详细信息。

安全性

如果您发现任何与安全性相关的问题,请通过电子邮件 mtkocak@gmail.com 而不是使用问题跟踪器。

鸣谢

许可

MIT 许可证 (MIT)。请参阅 许可文件 了解更多信息。