Skip to content

Instantly share code, notes, and snippets.

@geerteltink
Last active January 10, 2022 17:32
Show Gist options
  • Save geerteltink/7d42a7e69f75b328b068b39678b3fbb3 to your computer and use it in GitHub Desktop.
Save geerteltink/7d42a7e69f75b328b068b39678b3fbb3 to your computer and use it in GitHub Desktop.
zend-expressive-authentication with doctrine
<?php
declare(strict_types=1);
use App\Infrastructure\Repository\DoctrineUserRepositoryFactory;
use Zend\Expressive\Authentication\AuthenticationInterface;
use Zend\Expressive\Authentication\Session\PhpSessionFactory;
use Zend\Expressive\Authentication\UserRepositoryInterface;
return [
'dependencies' => [
'factories' => [
AuthenticationInterface::class => PhpSessionFactory::class,
UserRepositoryInterface::class => DoctrineUserRepositoryFactory::class,
],
],
'authentication' => [
'username' => 'email',
'password' => 'password',
'redirect' => '/signin',
],
];
<?php
declare(strict_types=1);
namespace App\Infrastructure\Repository;
use App\Domain\User\User;
use App\Domain\User\UserRepository;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Zend\Expressive\Authentication\UserInterface;
class DoctrineUserRepository implements UserRepository
{
/**
* @var ObjectRepository
*/
private $repository;
public function __construct(
ObjectRepository $repository
) {
$this->repository = $repository;
}
public function authenticate(string $identity, string $password = null) : ?UserInterface
{
/** @var User $user */
$user = $this->repository->findOneBy([
'email' => $identity,
]);
if ($user && $user->verifyPassword($password)) {
return $user;
}
return null;
}
public function getRolesFromUser(string $identity) : array
{
/** @var User $user */
$user = $this->repository->findOneBy([
'email' => $identity,
]);
if (! $user) {
return [];
}
return $user->getUserRoles();
}
}
<?php
declare(strict_types=1);
namespace App\Domain\User;
use Zend\Expressive\Authentication\UserRepositoryInterface;
interface UserRepository extends UserRepositoryInterface
{
// ...
}
@ganapathichidambaram
Copy link

Its not working for Mezzio i think. Or its just template where it's need to be extended.

@geerteltink
Copy link
Author

It's code from 3 years ago. I think it was an example for someone back then.

I see that there is a paginator and criteria import and those are not even used.

@ganapathichidambaram
Copy link

Will you please suggest or refer for mezzio if you have any ?.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment