Skip to content

Commit

Permalink
tests and interfaces moving
Browse files Browse the repository at this point in the history
  • Loading branch information
sinbadxiii committed Oct 1, 2021
1 parent de36406 commit 85d26df
Show file tree
Hide file tree
Showing 19 changed files with 380 additions and 63 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/vendor
composer.lock
/.phpunit.*
89 changes: 56 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ You can see an example of an application with authorization and limit here [sinb
- ~~*HTTP Basic аутентификацция*~~
- Активация по email (требуется стандартизировать работу с почтой)
- Восстановление пароля(требуется стандартизировать работу с почтой)
- Тесты
- Перевод документации на английский язык

Phalcon Auth позволит вам создать в своем веб-приложении систему аутентификации.
Expand All @@ -45,9 +44,11 @@ Phalcon Auth позволит вам создать в своем веб-при

## Installation

Phalcon 4 or Phalcon 5
| Phalcon 3 | Phalcon 4 | Phalcon 5 | Phalcon 6
:-------------| :-------------| :-------------| :----------
| :x: | :heavy_check_mark:| :heavy_check_mark: | :question:

PHP 7.2-8.0.
PHP ^7.4-8.0.

Require the project using composer:

Expand Down Expand Up @@ -152,27 +153,6 @@ class Authenticate extends AuthMiddleware
}
```

### Перенаправление неаутентифицированных пользователей

Когда middleware обнаруживает неаутентифицированного пользователя, то выполняет метод `redirectTo()`, по умолчанию идет редирект на нужный вам url (ту же форму логина, например), вы можете изменить это поведение, например вернуть json ответ, если будет идти ajax запрос.

```php

protected function redirectTo()
{
$this->response->setJsonContent(
[
'success' => false,
'message' => 'Authentication failure'
], JSON_UNESCAPED_UNICODE
);

if (!$this->response->isSent()) {
$this->response->send();
}
}
```

and attach it in your dispatcher:

```php
Expand Down Expand Up @@ -225,14 +205,36 @@ class DispatcherProvider implements ServiceProviderInterface
}
```

4. Implement your model Users, example:
### Перенаправление неаутентифицированных пользователей

Когда middleware обнаруживает неаутентифицированного пользователя, то выполняет метод `redirectTo()`, по умолчанию редирект идет на нужный вам url (ту же форму логина, например), вы можете изменить это поведение, например вернуть json ответ, если для аутентификации используеся ajax запрос.

```php

protected function redirectTo()
{
$this->response->setJsonContent(
[
'success' => false,
'message' => 'Authentication failure'
], JSON_UNESCAPED_UNICODE
);

if (!$this->response->isSent()) {
$this->response->send();
}
}
```

4. Implement your model Users fom AuthenticatableInterface and RememberingInterface, example:

```php
namespace Models;

use Sinbadxiii\PhalconAuth\RememberToken\RememberTokenModel;
use Sinbadxiii\PhalconAuth\Contracts\AuthenticatableInterface;
use Sinbadxiii\PhalconAuth\RememberToken\RememberingInterface;
use Sinbadxiii\PhalconAuth\Contracts\RememberingInterface;
use Sinbadxiii\PhalconAuth\Contracts\RememberTokenterface;

class Users extends BaseModel implements AuthenticatableInterface, RememberingInterface
{
Expand Down Expand Up @@ -265,15 +267,15 @@ class Users extends BaseModel implements AuthenticatableInterface, RememberingIn
return $this->password;
}

public function getRememberToken(string $token = null)
public function getRememberToken(string $token = null): RememberTokenterface
{
return $this->getRelated('remember_token', [
'token=:token:',
'bind' => ['token' => $token]
]);
}

public function setRememberToken($value)
public function setRememberToken(RememberTokenterface $value)
{
$this->remember_token = $value;
}
Expand Down Expand Up @@ -467,7 +469,7 @@ class AuthenticateWithBasic extends AuthMiddleware
}
} catch (\Throwable $e) {
$this->message = $e->getMessage();
}
}
$this->unauthenticated();
}

Expand Down Expand Up @@ -569,15 +571,36 @@ Copy file from `config/auth.php` in your folder config and merge your config
'driver' => 'model',
'model' => \Models\Users::class,
],
],
'hash' => [
'method' => 'sha1'
],
// 'users' => [
// 'driver' => 'file',
// 'path' => __DIR__ . "/users.json",
// 'passsword_crypted' => false
// ],
]
],
..

```

Если в качестве источника пользователей будет выбрана не `model`, а `file`, то необходимо будет указать путь к .json файлу в `path`, формата например:

```json
{
"0":{"name":"admin","password": "admin","email": "admin@admin.ru"},
"1":{"name":"admin1","password": "admin1","email": "admin1@admin1.ru"}
}
```

или если включено шифрование паролей в `password_crypted`, то указывать пароль в зашифрованном виде:

```json
{
"0":{"name":"admin1","password": "$2y$10$ME02QlQxWGdDNUdiUTJucuhQHYQlIglb3lG2rfdzvK3UbQXAPrc.q","email": "admin1@admin1.ru"}
}
```

Шифровать пароль необходимо будет с помощью `$this->security->hash()`, который вы используете у себя в приложении.


### License
The MIT License (MIT). Please see [License File](https://github.com/sinbadxiii/phalcon-auth/blob/master/LICENSE) for more information.
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
"php": "^7.4 || ^8.0"
},
"require-dev": {
"mockery/mockery": "^1.4",
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
Expand Down
23 changes: 23 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit stderr="true"
backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutTestsThatDoNotTestAnything="false"
beStrictAboutOutputDuringTests="true"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
failOnRisky="true"
failOnWarning="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
verbose="true">
<testsuites>
<testsuite name="Auth Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
47 changes: 30 additions & 17 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,30 @@
*/
class Auth
{
/**
* @var mixed
*/
protected $config;

/**
* @var mixed
*/
protected $security;

/**
* @var array
*/
protected $customGuards = [];

/**
* @var array
*/
protected $guards = [];

public function __construct($config = null)
public function __construct($config = null, $security = null)
{
if (is_null($config)) {
$config = Di::getDefault()->getShared("config")->auth;
}
$this->config = $config;
$this->config = $config ?? Di::getDefault()->getShared("config")->auth;
$this->security = $security ?? Di::getDefault()->getShared("security");
}

/**
Expand Down Expand Up @@ -53,7 +67,6 @@ public function guard($name = null)
*/
protected function resolve($name)
{

$configGuard = $this->getConfigGuard($name);

if (is_null($configGuard)) {
Expand Down Expand Up @@ -89,7 +102,7 @@ public function createProvider($configGuard = null)
);

return new $driver(
Di::getDefault()->getShared("security"),
$this->security,
$this->config->providers->{$configGuard->provider}
);
}
Expand All @@ -102,16 +115,6 @@ public function getDefaultDriver()
return $this->config->defaults->guard;
}

/**
* @param $method
* @param $params
* @return mixed
*/
public function __call($method, $params)
{
return $this->guard()->{$method}(...$params);
}

public function extend($driver, Closure $callback)
{
$this->customGuards[$driver] = $callback;
Expand All @@ -123,4 +126,14 @@ protected function callCustomGuard($name, Config $config)
{
return $this->customGuards[$config['driver']]($name, $config);
}

/**
* @param $method
* @param $params
* @return mixed
*/
public function __call($method, $params)
{
return $this->guard()->{$method}(...$params);
}
}
2 changes: 2 additions & 0 deletions src/AuthProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class AuthProvider implements ServiceProviderInterface

/**
* @param DiInterface $di
* @param null $config
* @param null $security
*/
public function register(DiInterface $di): void
{
Expand Down
9 changes: 9 additions & 0 deletions src/Contracts/RememberTokenterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Sinbadxiii\PhalconAuth\Contracts;

interface RememberTokenterface
{
public function getToken(): string;
public function getUserAgent(): string;
}
9 changes: 9 additions & 0 deletions src/Contracts/RememberingInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Sinbadxiii\PhalconAuth\Contracts;

interface RememberingInterface
{
public function getRememberToken(): RememberTokenterface;
public function setRememberToken(RememberTokenterface $value);
}
10 changes: 9 additions & 1 deletion src/Middlewares/Authenticate.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@
namespace Sinbadxiii\PhalconAuth\Middlewares;

use Phalcon\Di\Injectable;
use Phalcon\Mvc\Dispatcher;

class Authenticate extends Injectable implements AuthenticatesRequest
{
protected $dispatcher;
/**
* @var
*/
protected Dispatcher $dispatcher;

/**
* @param $event
* @param $dispatcher
*/
public function beforeDispatch($event, $dispatcher)
{
$this->dispatcher = $dispatcher;
Expand Down
7 changes: 4 additions & 3 deletions src/RememberToken/RememberTokenModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@

use Phalcon\Di;
use Phalcon\Mvc\Model;
use Sinbadxiii\PhalconAuth\Contracts\RememberTokenterface;

class RememberTokenModel extends Model
class RememberTokenModel extends Model implements RememberTokenterface
{
/**
* @var integer
Expand Down Expand Up @@ -86,12 +87,12 @@ public function beforeValidationOnUpdate()
$this->updated_at = date(DATE_ATOM);
}

public function getToken()
public function getToken(): string
{
return $this->token;
}

public function getUserAgent()
public function getUserAgent(): string
{
return $this->user_agent;
}
Expand Down
9 changes: 0 additions & 9 deletions src/RememberToken/RememberingInterface.php

This file was deleted.

20 changes: 20 additions & 0 deletions tests/AbstractTestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Sinbadxiii\PhalconAuth\Tests;

use PHPUnit\Framework\TestCase;

/**
* Class AbstractTestCase
* @package Sinbadxiii\PhalconAuth\Tests
*/
abstract class AbstractTestCase extends TestCase
{
public function flushAll()
{
$_SERVER = [];
$_REQUEST = [];
$_POST = [];
$_GET = [];
}
}
Loading

0 comments on commit 85d26df

Please sign in to comment.