phalcon / cphalcon

High performance, full-stack PHP framework delivered as a C extension.
https://phalcon.io
BSD 3-Clause "New" or "Revised" License
10.79k stars 1.96k forks source link

[NFR]: Phalcon Authentication #16273

Open sinbadxiii opened 1 year ago

sinbadxiii commented 1 year ago

Hi Guys!

I want to add Auth to Phalcon. I made this library - Phalcon Auth. It works well.

The basis is built on guards and adapters. As guards, there can be Sessions for the web and Tokens for the api.

Adapters can be application Models , such as App\Models\Users, Stream such as json file, or just an array of users in Memory.

Because There are no usual middleware in the Phalcon, I implemented an Access layer, which allows you to separate user access into guests and users (also you can create custom access, for example for admins).

To start authentication, you need to create a service provider auth, for example, standard sessions and users model.

use Phalcon\Auth\Manager;
use App\Models\User;
use Phalcon\Auth\Adapter\Model;
use Phalcon\Auth\Guard\Session;

$di->setShared("auth", function () use ($config, $di) {
    $manager = new Manager();

    $configAdapter = [
        'model' => User::class,
    ];

    $adapter = new Model($this->getSecurity(), $configAdapter);
    $guard   = new Session(
        $adapter,
        $this->getSession(),
        $this->getCookies(),
        $this->getRequest(),
        $this->getEventsManager()
    );

    $manager->addGuard("web", $guard, true);

    return $manager;
});

And in the controller restrict access to only authenticated users

<?php

declare(strict_types=1);

namespace App\Controllers;

class ProfileController extends Phalcon\Mvc\Controller
{
    public function onConstruct()
    {
        $this->auth->access("auth");
    }

    public function indexAction()
    {
    }
}

There is support for HTTP Basic Auth, and you can also connect JWT token authentication using a third-party library Phalcon Auth JWT.

If everyone likes it, I can create a PR :)

niden commented 1 year ago

I have been keeping an eye on that project for some time now. That is great work.

If you don't mind I would like to check the project out a bit more and with an example to understand the code flow and operation. By the looks of it, it can be just "copied" over to the core framework. To maintain it though we will need to understand how it works first.

sinbadxiii commented 1 year ago

@niden oh, of course I understand what it needs to check. Thanks!

I support both versions: Zephir and PHP https://github.com/sinbadxiii/phalcon-auth They are the same.

There is an example app https://github.com/sinbadxiii/phalcon-auth-example

Indeed, the components of the library have been made independent and can be just copied into the main core without problems almost :)

ghost commented 1 year ago

This is good, its kind of what i have been asking for https://github.com/phalcon/phalcon/issues/162 Thank you!