-
Notifications
You must be signed in to change notification settings - Fork 0
Example
hexdec(uname) edited this page Jun 26, 2018
·
1 revision
Setup your injectable controller in module.config.php
.
This configuration file can be found at any module in Zend Framework.
'controllers' => [
'factories' => [
AuthenticationController::class => InjectableFactory::class
],
],
Create your data repository
The repository will acess your database and get the records.
<?php
class CredentialnRepository
{
public function getRecordsByUsernameAndPassword($username, $password)
{
return [
[
'name' => 'A fake record',
'accessLevel' => 1
]
];
}
}
Create your service for authentication
The authentication service will check if credentials match and then will provide a token.
<?php
class AuthenticationService
{
private $repository;
public function __construct(CredentialRepository $repository)
{
$this->repository = $repository;
}
public function createToken($username, $password): string
{
$rows = $this->repository->getRecordsByUsernameAndPassword($username, $password);
if(count($rows) != 1) {
throw new \InvalidArgumentException('Username or password incorrect');
}
return md5($username . $password);
}
}
Create your controller
<?php
class AuthenticationController extends AbstractActionController
{
private $authenticationService;
public function __construct(AuthenticationService $authenticationService)
{
$this->authenticationService = $authenticationService.
}
public function loginAction()
{
$username = $this->params()->fromPost('username');
$password = $this->params()->fromPost('password');
$token = $this->authenticationService->createToken($username, $password);
return new JsonModel([
'token' => $token
]);
}
}