PHP code example of horus / sentinel

1. Go to this page and download the library: Download horus/sentinel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

horus / sentinel example snippets


namespace App\Models;

use Horus\Sentinel\Contracts\UserIdentityInterface;

class User implements UserIdentityInterface
{
    public function getId(): int {
        return $this->id;
    }

    public function getPasswordHash(): string {
        return $this->password;
    }

    public function getRoles(): array {
        return [$this->role ?? 'user'];
    }
}
B. UserRepositoryInterface
Você precisa criar um repositório que saiba como buscar os utilizadores na base de dados:



namespace App\Repositories;

use Horus\Sentinel\Contracts\UserRepositoryInterface;
use Horus\Sentinel\Contracts\UserIdentityInterface;
use App\Models\User;

class UserRepository implements UserRepositoryInterface
{
    public function findById(int $id): ?UserIdentityInterface {
        return User::find($id);
    }

    public function findByEmail(string $email): ?UserIdentityInterface {
        // Ex: return User::where('email', $email)->first();
    }
}
C. RateLimiterInterface (Opcional)
Implemente a interface de rate limiting se desejar controlar o número de tentativas de login.

2. Inicializar o Sentinel
No bootstrap da sua aplicação (bootstrap/app.php ou equivalente):


use Horus\Sentinel\Sentinel;
use App\Repositories\UserRepository;
use App\Repositories\RedisRateLimiter;

$appKey = getenv('APP_KEY'); // Chave secreta do seu .env

$sentinel = new Sentinel(
    new UserRepository(),
    new RedisRateLimiter(),
    $appKey
);
Se estiver usando um container de injeção de dependência (DI), registre como singleton:


$container->singleton(Sentinel::class, fn() => $sentinel);
3. Utilização
🔐 Autenticação
php
Copiar
Editar
$email = $_POST['email'];
$password = $_POST['password'];

if ($sentinel->login($email, $password)) {
    header('Location: /dashboard');
    exit;
}
🔒 Proteção de Rotas (Middleware)

class AuthMiddleware {
    public function handle($request, $next) {
        global $sentinel;

        if (!$sentinel->user()) {
            header('Location: /login');
            exit;
        }

        return $next($request);
    }
}
🛡️ CSRF Protection
No formulário:



<form method="POST">
     echo $sentinel->csrfInput();