Browse Source

reAuth implemented

Maurits van der Schee 5 years ago
parent
commit
20e4d8bc9d

+ 5
- 0
src/Tqdev/PhpCrudApi/Api.php View File

@@ -1,4 +1,5 @@
1 1
 <?php
2
+
2 3
 namespace Tqdev\PhpCrudApi;
3 4
 
4 5
 use Psr\Http\Message\ResponseInterface;
@@ -24,6 +25,7 @@ use Tqdev\PhpCrudApi\Middleware\FirewallMiddleware;
24 25
 use Tqdev\PhpCrudApi\Middleware\IpAddressMiddleware;
25 26
 use Tqdev\PhpCrudApi\Middleware\JoinLimitsMiddleware;
26 27
 use Tqdev\PhpCrudApi\Middleware\JwtAuthMiddleware;
28
+use Tqdev\PhpCrudApi\Middleware\ReAuthMiddleware;
27 29
 use Tqdev\PhpCrudApi\Middleware\MultiTenancyMiddleware;
28 30
 use Tqdev\PhpCrudApi\Middleware\PageLimitsMiddleware;
29 31
 use Tqdev\PhpCrudApi\Middleware\Router\SimpleRouter;
@@ -73,6 +75,9 @@ class Api implements RequestHandlerInterface
73 75
                 case 'dbAuth':
74 76
                     new DbAuthMiddleware($router, $responder, $properties, $reflection, $db);
75 77
                     break;
78
+                case 'reAuth':
79
+                    new ReAuthMiddleware($router, $responder, $properties, $reflection, $db);
80
+                    break;
76 81
                 case 'validation':
77 82
                     new ValidationMiddleware($router, $responder, $properties, $reflection);
78 83
                     break;

+ 16
- 8
src/Tqdev/PhpCrudApi/Column/ReflectionService.php View File

@@ -1,4 +1,5 @@
1 1
 <?php
2
+
2 3
 namespace Tqdev\PhpCrudApi\Column;
3 4
 
4 5
 use Tqdev\PhpCrudApi\Cache\Cache;
@@ -19,10 +20,18 @@ class ReflectionService
19 20
         $this->db = $db;
20 21
         $this->cache = $cache;
21 22
         $this->ttl = $ttl;
22
-        $this->database = $this->loadDatabase(true);
23
+        $this->database = null;
23 24
         $this->tables = [];
24 25
     }
25 26
 
27
+    private function database(): ReflectedDatabase
28
+    {
29
+        if (!$this->database) {
30
+            $this->database = $this->loadDatabase(true);
31
+        }
32
+        return $this->database;
33
+    }
34
+
26 35
     private function loadDatabase(bool $useCache): ReflectedDatabase
27 36
     {
28 37
         $data = $useCache ? $this->cache->get('ReflectedDatabase') : '';
@@ -42,7 +51,7 @@ class ReflectionService
42 51
         if ($data != '') {
43 52
             $table = ReflectedTable::fromJson(json_decode(gzuncompress($data)));
44 53
         } else {
45
-            $tableType = $this->database->getType($tableName);
54
+            $tableType = $this->database()->getType($tableName);
46 55
             $table = ReflectedTable::fromReflection($this->db->reflection(), $tableName, $tableType);
47 56
             $data = gzcompress(json_encode($table, JSON_UNESCAPED_UNICODE));
48 57
             $this->cache->set("ReflectedTable($tableName)", $data, $this->ttl);
@@ -62,12 +71,12 @@ class ReflectionService
62 71
 
63 72
     public function hasTable(string $tableName): bool
64 73
     {
65
-        return $this->database->hasTable($tableName);
74
+        return $this->database()->hasTable($tableName);
66 75
     }
67 76
 
68 77
     public function getType(string $tableName): string
69 78
     {
70
-        return $this->database->getType($tableName);
79
+        return $this->database()->getType($tableName);
71 80
     }
72 81
 
73 82
     public function getTable(string $tableName): ReflectedTable
@@ -80,18 +89,17 @@ class ReflectionService
80 89
 
81 90
     public function getTableNames(): array
82 91
     {
83
-        return $this->database->getTableNames();
92
+        return $this->database()->getTableNames();
84 93
     }
85 94
 
86 95
     public function getDatabaseName(): string
87 96
     {
88
-        return $this->database->getName();
97
+        return $this->database()->getName();
89 98
     }
90 99
 
91 100
     public function removeTable(string $tableName): bool
92 101
     {
93 102
         unset($this->tables[$tableName]);
94
-        return $this->database->removeTable($tableName);
103
+        return $this->database()->removeTable($tableName);
95 104
     }
96
-
97 105
 }

+ 20
- 11
src/Tqdev/PhpCrudApi/Database/GenericDB.php View File

@@ -1,4 +1,5 @@
1 1
 <?php
2
+
2 3
 namespace Tqdev\PhpCrudApi\Database;
3 4
 
4 5
 use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
@@ -20,25 +21,30 @@ class GenericDB
20 21
     private function getDsn(string $address, int $port, string $database): string
21 22
     {
22 23
         switch ($this->driver) {
23
-            case 'mysql':return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
24
-            case 'pgsql':return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
25
-            case 'sqlsrv':return "$this->driver:Server=$address,$port;Database=$database";
24
+            case 'mysql':
25
+                return "$this->driver:host=$address;port=$port;dbname=$database;charset=utf8mb4";
26
+            case 'pgsql':
27
+                return "$this->driver:host=$address port=$port dbname=$database options='--client_encoding=UTF8'";
28
+            case 'sqlsrv':
29
+                return "$this->driver:Server=$address,$port;Database=$database";
26 30
         }
27 31
     }
28 32
 
29 33
     private function getCommands(): array
30 34
     {
31 35
         switch ($this->driver) {
32
-            case 'mysql':return [
36
+            case 'mysql':
37
+                return [
33 38
                     'SET SESSION sql_warnings=1;',
34 39
                     'SET NAMES utf8mb4;',
35 40
                     'SET SESSION sql_mode = "ANSI,TRADITIONAL";',
36 41
                 ];
37
-            case 'pgsql':return [
42
+            case 'pgsql':
43
+                return [
38 44
                     "SET NAMES 'UTF8';",
39 45
                 ];
40
-            case 'sqlsrv':return [
41
-                ];
46
+            case 'sqlsrv':
47
+                return [];
42 48
         }
43 49
     }
44 50
 
@@ -49,16 +55,19 @@ class GenericDB
49 55
             \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
50 56
         );
51 57
         switch ($this->driver) {
52
-            case 'mysql':return $options + [
58
+            case 'mysql':
59
+                return $options + [
53 60
                     \PDO::ATTR_EMULATE_PREPARES => false,
54 61
                     \PDO::MYSQL_ATTR_FOUND_ROWS => true,
55 62
                     \PDO::ATTR_PERSISTENT => true,
56 63
                 ];
57
-            case 'pgsql':return $options + [
64
+            case 'pgsql':
65
+                return $options + [
58 66
                     \PDO::ATTR_EMULATE_PREPARES => false,
59 67
                     \PDO::ATTR_PERSISTENT => true,
60 68
                 ];
61
-            case 'sqlsrv':return $options + [
69
+            case 'sqlsrv':
70
+                return $options + [
62 71
                     \PDO::SQLSRV_ATTR_DIRECT_QUERY => false,
63 72
                     \PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
64 73
                 ];
@@ -74,7 +83,7 @@ class GenericDB
74 83
         $this->pdo = new LazyPdo($dsn, $username, $password, $options);
75 84
         $commands = $this->getCommands();
76 85
         foreach ($commands as $command) {
77
-            $this->pdo->query($command);
86
+            $this->pdo->addInitCommand($command);
78 87
         }
79 88
         $this->reflection = new GenericReflection($this->pdo, $driver, $database);
80 89
         $this->definition = new GenericDefinition($this->pdo, $driver, $database);

+ 18
- 7
src/Tqdev/PhpCrudApi/Database/LazyPdo.php View File

@@ -1,4 +1,5 @@
1 1
 <?php
2
+
2 3
 namespace Tqdev\PhpCrudApi\Database;
3 4
 
4 5
 class LazyPdo extends \PDO
@@ -6,7 +7,8 @@ class LazyPdo extends \PDO
6 7
     private $dsn;
7 8
     private $user;
8 9
     private $password;
9
-    private $options = array();
10
+    private $options;
11
+    private $commands;
10 12
 
11 13
     private $pdo = null;
12 14
 
@@ -16,28 +18,37 @@ class LazyPdo extends \PDO
16 18
         $this->user = $user;
17 19
         $this->password = $password;
18 20
         $this->options = $options;
21
+        $this->commands = array();
19 22
         // explicitly NOT calling super::__construct
20 23
     }
21 24
 
25
+    public function addInitCommand(string $command)/*: void*/
26
+    {
27
+        $this->commands[] = $command;
28
+    }
29
+
22 30
     private function pdo()
23 31
     {
24 32
         if (!$this->pdo) {
25 33
             $this->pdo = new \PDO($this->dsn, $this->user, $this->password, $this->options);
34
+            foreach ($this->commands as $command) {
35
+                $this->pdo->query($command);
36
+            }
26 37
         }
27 38
         return $this->pdo;
28 39
     }
29 40
 
30
-    public function reauthenticate(/*?string*/ $user, /*?string*/ $password): bool
41
+    public function reauthenticate(/*?string*/$user, /*?string*/ $password): bool
31 42
     {
32 43
         $this->user = $user;
33 44
         $this->password = $password;
34 45
         if ($this->pdo) {
35
-            $this->pdo = new \PDO($this->dsn, $this->user, $this->password, $this->options);
36
-            return false; 
46
+            $this->pdo = null;
47
+            return false;
37 48
         }
38 49
         return true;
39 50
     }
40
-    
51
+
41 52
     public function inTransaction(): bool
42 53
     {
43 54
         // Do not call parent method if there is no pdo object
@@ -46,7 +57,7 @@ class LazyPdo extends \PDO
46 57
 
47 58
     public function setAttribute($attribute, $value): bool
48 59
     {
49
-        if ($this->pdo) { 
60
+        if ($this->pdo) {
50 61
             return $this->pdo()->setAttribute($attribute, $value);
51 62
         }
52 63
         $this->options[$attribute] = $value;
@@ -107,4 +118,4 @@ class LazyPdo extends \PDO
107 118
     {
108 119
         return call_user_func_array(array($this->pdo(), 'query'), func_get_args());
109 120
     }
110
-}
121
+}

+ 1
- 0
src/Tqdev/PhpCrudApi/Middleware/DbAuthMiddleware.php View File

@@ -1,4 +1,5 @@
1 1
 <?php
2
+
2 3
 namespace Tqdev\PhpCrudApi\Middleware;
3 4
 
4 5
 use Psr\Http\Message\ResponseInterface;

+ 0
- 34
src/Tqdev/PhpCrudApi/Middleware/ReauthMiddleware.php View File

@@ -1,34 +0,0 @@
1
-<?php
2
-namespace Tqdev\PhpCrudApi\Middleware;
3
-
4
-use Psr\Http\Message\ResponseInterface;
5
-use Psr\Http\Message\ServerRequestInterface;
6
-use Psr\Http\Server\RequestHandlerInterface;
7
-use Tqdev\PhpCrudApi\Column\ReflectionService;
8
-use Tqdev\PhpCrudApi\Controller\Responder;
9
-use Tqdev\PhpCrudApi\Database\GenericDB;
10
-use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
11
-use Tqdev\PhpCrudApi\Middleware\Router\Router;
12
-use Tqdev\PhpCrudApi\Record\Condition\ColumnCondition;
13
-use Tqdev\PhpCrudApi\Record\ErrorCode;
14
-use Tqdev\PhpCrudApi\Record\OrderingInfo;
15
-use Tqdev\PhpCrudApi\RequestUtils;
16
-
17
-class ReauthMiddleware extends Middleware
18
-{
19
-    private $reflection;
20
-    private $db;
21
-
22
-    public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection, GenericDB $db)
23
-    {
24
-        parent::__construct($router, $responder, $properties);
25
-        $this->reflection = $reflection;
26
-        $this->db = $db;
27
-    }
28
-
29
-    public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
30
-    {
31
-        if (isset($_SESSION['username']))
32
-        return $next->handle($request);
33
-    }
34
-}

+ 20
- 2
test.php View File

@@ -1,4 +1,5 @@
1 1
 <?php
2
+
2 3
 use Tqdev\PhpCrudApi\Api;
3 4
 use Tqdev\PhpCrudApi\Config;
4 5
 use Tqdev\PhpCrudApi\Database\GenericDB;
@@ -76,6 +77,23 @@ function runTest(Config $config, string $file, string $category): int
76 77
     return $success;
77 78
 }
78 79
 
80
+function getUsername(Config $config)
81
+{
82
+    if (!isset($config->getMiddlewares()['reAuth']['usernameHandler'])) {
83
+        return $config->getUsername();
84
+    }
85
+    return $config->getMiddlewares()['reAuth']['usernameHandler']();
86
+}
87
+
88
+function getPassword(Config $config)
89
+{
90
+    if (!isset($config->getMiddlewares()['reAuth']['passwordHandler'])) {
91
+        return $config->getPassword();
92
+    }
93
+    return $config->getMiddlewares()['reAuth']['passwordHandler']();
94
+}
95
+
96
+
79 97
 function loadFixture(string $dir, Config $config)
80 98
 {
81 99
     $driver = $config->getDriver();
@@ -86,8 +104,8 @@ function loadFixture(string $dir, Config $config)
86 104
         $config->getAddress(),
87 105
         $config->getPort(),
88 106
         $config->getDatabase(),
89
-        $config->getUsername(),
90
-        $config->getPassword()
107
+        getUsername($config),
108
+        getPassword($config)
91 109
     );
92 110
     $pdo = $db->pdo();
93 111
     $file = preg_replace('/--.*$/m', '', $file);

+ 9
- 3
tests/config/base.php View File

@@ -1,10 +1,10 @@
1 1
 <?php
2 2
 $settings = [
3 3
     'database' => 'php-crud-api',
4
-    'username' => 'php-crud-api',
5
-    'password' => 'php-crud-api',
4
+    'username' => 'incorrect_username',
5
+    'password' => 'incorrect_password',
6 6
     'controllers' => 'records,columns,cache,openapi,geojson',
7
-    'middlewares' => 'cors,dbAuth,jwtAuth,basicAuth,authorization,validation,ipAddress,sanitation,multiTenancy,pageLimits,joinLimits,customization',
7
+    'middlewares' => 'cors,reAuth,dbAuth,jwtAuth,basicAuth,authorization,validation,ipAddress,sanitation,multiTenancy,pageLimits,joinLimits,customization',
8 8
     'dbAuth.mode' => 'optional',
9 9
     'dbAuth.returnedColumns' => 'id,username,password',
10 10
     'jwtAuth.mode' => 'optional',
@@ -12,6 +12,12 @@ $settings = [
12 12
     'jwtAuth.secret' => 'axpIrCGNGqxzx2R9dtXLIPUSqPo778uhb8CA0F4Hx',
13 13
     'basicAuth.mode' => 'optional',
14 14
     'basicAuth.passwordFile' => __DIR__ . DIRECTORY_SEPARATOR . '.htpasswd',
15
+    'reAuth.usernameHandler' => function () {
16
+        return 'php-crud-api';
17
+    },
18
+    'reAuth.passwordHandler' => function () {
19
+        return 'php-crud-api';
20
+    },
15 21
     'authorization.tableHandler' => function ($operation, $tableName) {
16 22
         return !($tableName == 'invisibles' && !isset($_SESSION['claims']['name']) && empty($_SESSION['username']) && empty($_SESSION['user']));
17 23
     },

Loading…
Cancel
Save