1. Go to this page and download the library: Download sinbadxiii/phalcon-auth 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/ */
sinbadxiii / phalcon-auth example snippets
use Sinbadxiii\PhalconAuth\Manager;
use App\Models\User;
use Sinbadxiii\PhalconAuth\Adapter\Model;
use Sinbadxiii\PhalconAuth\Guard\Session;
$auth = new Manager();
$configAdapter = [
'model' => User::class,
];
$adapter = new Model($this->getSecurity(), $configAdapter);
$guard = new Session(
$adapter,
$this->getSession(),
$this->getCookies(),
$this->getRequest(),
$this->getEventsManager()
);
$auth->addGuard("web", $guard, true);
return $auth;
use Sinbadxiii\PhalconAuth\Manager;
use App\Models\User;
use Sinbadxiii\PhalconAuth\Adapter\Model;
use Sinbadxiii\PhalconAuth\Guard\Session;
$auth = new Manager();
$configAdapter = [
'model' => User::class,
];
$adapter = new Model($this->getSecurity(), $configAdapter);
$guard = new Session(
$adapter,
$this->getSession(),
$this->getCookies(),
$this->getRequest(),
$this->getEventsManager()
);
$auth->addGuard("web", $guard, true);
return $auth;
[
...
'inputKey' => 'auth_token', //имя параметра с токеном
'storageKey' => 'auth_token', //имя поля в хранилище пользователей
...
]
use Sinbadxiii\PhalconAuth\Manager;
use App\Models\User;
use Sinbadxiii\PhalconAuth\Adapter\Model;
use Sinbadxiii\PhalconAuth\Guard\Token;
$auth = new Manager();
$configAdapter = [
'model' => User::class,
];
$configGuard = [
'inputKey' => 'auth_token',
'storageKey' => 'auth_token',
];
$adapter = new Model($this->getSecurity(), $configAdapter);
$guard = new Token(
$adapter,
$configGuard
$this->getRequest()
);
$auth->addGuard("api", $guard, true);
return $auth;
declare(strict_types=1);
namespace Sinbadxiii\PhalconAuth\Guard;
use Sinbadxiii\PhalconAuth\AuthenticatableInterface;
interface GuardInterface
{
public function check(): bool;
public function user();
public function setUser(AuthenticatableInterface $user);
public function id();
public function guest(): bool;
public function validate(array $credentials = []): bool;
}
declare(strict_types=1);
namespace App\Controllers;
class ProfileController extends ControllerBase
{
public function onConstruct()
{
$this->auth->access("auth");
}
public function indexAction()
{
}
}
declare(strict_types=1);
namespace App\Controllers;
class RegisterController extends ControllerBase
{
public function onConstruct()
{
$this->auth->access("guest");
}
public function indexAction()
{
}
}
class Auth extends AbstractAccess
{
/**
* @return bool
*/
public function allowedIf(): bool
{
if ($this->auth->check()) {
return true;
}
return false;
}
}
namespace Sinbadxiii\PhalconAuth\Access;
/**
* Class Guest
* @package Sinbadxiii\PhalconAuth\Access
*/
class Guest extends AbstractAccess
{
/**
* @return bool
*/
public function allowedIf(): bool
{
if ($this->auth->guest()) {
return true;
}
return false;
}
}
namespace App\Security\Access;
use Sinbadxiii\PhalconAuth\Access\Auth as AuthAccess;;
class Auth extends AuthAccess
{
public function redirectTo()
{
if (isset($this->response)) {
return $this->response->redirect("/login")->send();
}
}
}
namespace App\Security\Access;
use Sinbadxiii\PhalconAuth\Access\Guest as GuestAccess;
class Guest extends GuestAccess
{
public function redirectTo()
{
if (isset($this->response)) {
return $this->response->redirect("/profile")->send();
}
}
}
namespace Sinbadxiii\PhalconAuth\Access;
/**
* Interface for Sinbadxiii\PhalconAuth\Access
*/
interface AccessInterface
{
public function setExceptActions(...$actions): void;
public function setOnlyActions(...$actions): void;
public function isAllowed(): bool;
public function redirectTo();
public function allowedIf(): bool;
}
namespace App\Security\Access;
use Sinbadxiii\PhalconAuth\Access\AbstractAccess;
class Admin extends AbstractAccess
{
/**
* @return bool
*/
public function allowedIf(): bool
{
if ($user = $this->auth->user() and $user->getRole() === "admin") {
return true;
}
return false;
}
/**
* @return void
* @throws Exception
*/
public function redirectTo()
{
if (isset($this->response)) {
return $this->response->redirect("/admin-login")->send();
}
}
}
namespace App\Security\Access;
use Sinbadxiii\PhalconAuth\Access\AbstractAccess;
use Sinbadxiii\PhalconAuth\Exception;
class AuthWithBasic extends AbstractAccess
{
/**
* @return bool
*/
public function allowedIf(): bool
{
if ($this->auth->basic("email")) {
return true;
}
return false;
}
/**
* @return void
* @throws Exception
*/
public function redirectTo()
{
throw new Exception("Basic: Invalid credentials.");
}
}
declare(strict_types=1);
namespace App\Security;
use App\Security\Access\Auth;
use App\Security\Access\Guest;
use Sinbadxiii\PhalconAuth\Access\Authenticate as AuthMiddleware;
/**
* Class Authenticate
* @package App\Security
*/
class Authenticate extends AuthMiddleware
{
protected array $accessList = [
'auth' => Auth::class,
'guest' => Guest::class
];
}
$di->setShared('dispatcher', function () use ($di) {
$dispatcher = new Phalcon\Mvc\Dispatcher();
$eventsManager = $di->getShared('eventsManager');
$eventsManager->attach('dispatch', new App\Security\Authenticate());
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
declare(strict_types=1);
namespace App\Security;
use App\Security\Access\Auth;
use App\Security\Access\Admin;
use App\Security\Access\Guest;
use Sinbadxiii\PhalconAuth\Access\Authenticate as AuthMiddleware;
/**
* Class Authenticate
* @package App\Security
*/
class Authenticate extends AuthMiddleware
{
protected array $accessList = [
'auth' => Auth::class,
'guest' => Guest::class,
'admin' => Admin::class,
];
}
namespace App\Models;
use Phalcon\Mvc\Model;
class User extends Model
{
public $id;
public $username;
public $name;
public $email;
public $password;
public $published;
public $created_at;
public $updated_at;
public function initialize()
{
$this->setSource("users");
}
}
namespace App\Models;
use Phalcon\Encryption\Security\Random;
use Phalcon\Mvc\Model;
use Sinbadxiii\PhalconAuth\RememberingInterface;
use Sinbadxiii\PhalconAuth\AuthenticatableInterface;
use Sinbadxiii\PhalconAuth\RememberTokenInterface;
class User extends Model implements AuthenticatableInterface, RememberingInterface
{
public $id;
public $username;
public $name;
public $email;
public $password;
public $published;
public $created_at;
public $updated_at;
public function initialize()
{
$this->setSource("users");
$this->hasOne(
'id',
RememberToken::class,
'user_id',
[
'alias' => "remember_token"
]
);
}
public function setPassword(string $password)
{
$this->password = $this->getDI()->get("security")->hash($password);
return $this;
}
public function getAuthIdentifier()
{
return $this->id;
}
public function getAuthPassword()
{
return $this->password;
}
public function getRememberToken(string $token = null): ?RememberTokenInterface
{
return $this->getRelated('remember_token', [
'token=:token:',
'bind' => ['token' => $token]
]);
}
public function setRememberToken(RememberTokenInterface $value)
{
$this->remember_token = $value;
}
public function createRememberToken(): RememberTokenInterface
{
$random = new Random();
$token = $random->base64(60);
$rememberToken = new RememberToken();
$rememberToken->token = $token;
$rememberToken->user_agent = $this->getDI()->get("request")->getUserAgent();
$rememberToken->ip = $this->getDI()->get("request")->getClientAddress();
$this->setRememberToken($rememberToken);
$this->save();
return $rememberToken;
}
}
declare(strict_types=1);
namespace App\Models;
use Phalcon\Mvc\Model;
use Sinbadxiii\PhalconAuth\RememberTokenInterface;
class RememberToken extends Model implements RememberTokenInterface
{
/**
* @var integer
*/
public $id;
/**
* @var integer
*/
public $user_id;
/**
* @var string
*/
public $token;
/**
* @var string
*/
public $ip;
/**
* @var string
*/
public $user_agent;
/**
* @var integer
*/
public $created_at;
/**
* @var integer
*/
public $updated_at;
/**
* @var integer
*/
public $expired_at;
public function initialize()
{
$this->setSource("users_remember_tokens");
}
public function getToken(): string
{
return $this->token;
}
public function getUserAgent(): string
{
return $this->user_agent;
}
public function beforeValidationOnCreate()
{
$this->created_at = date(DATE_ATOM);
$this->updated_at = date(DATE_ATOM);
if (!$this->expired_at) {
$this->expired_at = date(DATE_ATOM);
}
}
public function beforeValidationOnSave()
{
if (!$this->created_at) {
$this->created_at = date(DATE_ATOM);
}
if (!$this->expired_at) {
$this->expired_at = date(DATE_ATOM);
}
$this->updated_at = date(DATE_ATOM);
}
public function beforeValidationOnUpdate()
{
$this->updated_at = date(DATE_ATOM);
}
}
namespace Sinbadxiii\PhalconAuth;
interface AuthenticatableInterface
{
public function getAuthIdentifier();
public function getAuthPassword();
}
namespace Sinbadxiii\PhalconAuth;
interface RememberingInterface
{
public function getRememberToken(): ?RememberTokenInterface;
public function createRememberToken(): RememberTokenInterface;
}
use Sinbadxiii\PhalconAuth\Adapter\Model;
use Sinbadxiii\PhalconAuth\Guard\Session;
use Sinbadxiii\PhalconAuth\Manager;
$security = $this->getSecurity();
$adapter = new Model($security);
$adapter->setModel(App\Models\User::class);
$guard = new Session(
$adapter,
$this->getSession(),
$this->getCookies(),
$this->getRequest(),
$this->getEventsManager()
);
$manager = new Manager();
$manager->addGuard("web", $guard);
$manager->setDefaultGuard($guard);
return $manager;
namespace App\Models;
use Phalcon\Auth\AuthenticatableInterface;
class UserSimple implements AuthenticatableInterface
{
/**
*
* @var integer
*/
public $id;
/**
*
* @var string
*/
public string $username;
/**
*
* @var string
*/
public string $name;
/**
*
* @var string
*/
public string $email;
/**
*
* @var string
*/
public string $password;
/**
*
* @var integer
*/
public $published;
public function __construct($data)
{
foreach ($data as $field => $value) {
$this->$field = $value;
}
}
/**
* @return int
*/
public function getAuthIdentifier(): mixed
{
return $this->id;
}
/**
* @return string
*/
public function getAuthPassword(): string
{
return $this->password;
}
}
$security = $this->getSecurity();
$adapter = new \Sinbadxiii\PhalconAuth\Adapter\Stream($security);
$adapter->setModel(App\Models\UserSimple::class);
$adapter->setFileSource(__DIR__ . "/users.json");
$guard = new \Sinbadxiii\PhalconAuth\Guard\Session(
$adapter,
$this->getSession(),
$this->getCookies(),
$this->getRequest(),
$this->getEventsManager()
);
$manager = new Manager();
$manager->addGuard("web", $guard, true); //третий аргумент - назначить охранника по дефолту
return $manager;
namespace Sinbadxiii\PhalconAuth\Adapter;
use Sinbadxiii\PhalconAuth\AuthenticatableInterface;
interface AdapterInterface
{
public function findFirstByCredentials(array $credentials);
public function findFirstById($id);
public function validateCredentials(AuthenticatableInterface $user, array $credentials): bool;
}
declare(strict_types=1);
namespace Sinbadxiii\PhalconAuth\Adapter;
use Sinbadxiii\PhalconAuth\AuthenticatableInterface;
use Sinbadxiii\PhalconAuth\RememberingInterface;
use Sinbadxiii\PhalconAuth\RememberTokenInterface;
interface AdapterWithRememberTokenInterface
{
public function findFirstByToken($identifier, $token, $user_agent): ?AuthenticatableInterface;
public function createRememberToken(RememberingInterface $user): RememberTokenInterface;
}
$di->setShared('auth', function () {
$manager = new \Sinbadxiii\PhalconAuth\ManagerFactory();
return $manager;
});
$di->setShared("auth", function () {
$config = $this->getConfig()->auth_config_other;
$manager = new \Sinbadxiii\PhalconAuth\ManagerFactory($config->toArray());
return $manager;
});
$di->setShared('auth', function () {
$auth = new \Sinbadxiii\PhalconAuth\ManagerFactory();
$request = $this->getRequest();
$manager->extendGuard("jwt", function ($adapter, $config) use ($request) {
return new JwtGuard($adapter, $config, $request);
});
return $auth;
});
$di->setShared("auth", function () {
$authManager = new Phalcon\Auth\ManagerFactory();
$authManager->extendProviderAdapter("mongo", function($security, $configProvider) {
return new App\Security\Adapter\Mongo($security, $configProvider);
});
return $authManager;
});
$this->auth->access("auth")
declare(strict_types=1);
namespace App\Controllers;
class ProfileController extends ControllerBase
{
public function onConstruct()
{
$this->auth->access("auth");
}
public function indexAction()
{
}
}
$this->auth->check();
//check authentication
public function loginFormAction()
{
if ($this->auth->check()) {
//redirect to profile page
return $this->response->redirect(
"/profile", true
);
}
}
$this->auth->user(); //get the user
$this->auth->id(); //get user id