|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Gewaer\Middleware; |
|
6
|
|
|
|
|
7
|
|
|
use Phalcon\Mvc\Micro; |
|
8
|
|
|
use Phalcon\Mvc\Micro\MiddlewareInterface; |
|
9
|
|
|
use Baka\Auth\Models\Sessions; |
|
10
|
|
|
use Gewaer\Models\Users; |
|
11
|
|
|
use Gewaer\Exception\UnauthorizedHttpException; |
|
12
|
|
|
use Gewaer\Constants\Flags; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Class AuthenticationMiddleware. |
|
16
|
|
|
* |
|
17
|
|
|
* @package Niden\Middleware |
|
18
|
|
|
*/ |
|
19
|
|
|
class AuthenticationMiddleware extends TokenBase |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* Call me. |
|
23
|
|
|
* |
|
24
|
|
|
* @param Micro $api |
|
25
|
|
|
* @todo need to check section for auth here |
|
26
|
|
|
* @return bool |
|
27
|
|
|
*/ |
|
28
|
69 |
|
public function call(Micro $api) |
|
29
|
|
|
{ |
|
30
|
69 |
|
$config = $api->getService('config'); |
|
31
|
69 |
|
$request = $api->getService('request'); |
|
32
|
|
|
|
|
33
|
69 |
|
if ($this->isValidCheck($request, $api)) { |
|
34
|
|
|
/** |
|
35
|
|
|
* This is where we will find if the user exists based on |
|
36
|
|
|
* the token passed using Bearer Authentication. |
|
37
|
|
|
*/ |
|
38
|
61 |
|
$data = $this->getToken($request->getBearerTokenFromHeader()); |
|
39
|
|
|
|
|
40
|
61 |
|
$api->getDI()->setShared( |
|
41
|
61 |
|
'userData', |
|
42
|
|
|
function () use ($config, $data, $request) { |
|
43
|
61 |
|
$session = new Sessions(); |
|
44
|
|
|
|
|
45
|
|
|
//all is empty and is dev, ok take use the first user |
|
46
|
61 |
|
if (empty($data->getClaim('sessionId')) && strtolower($config->app->env) == Flags::DEVELOPMENT) { |
|
47
|
|
|
return Users::findFirst(1); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
61 |
|
if (!empty($data->getClaim('sessionId'))) { |
|
51
|
|
|
//user |
|
52
|
61 |
|
if (!$user = Users::getByEmail($data->getClaim('email'))) { |
|
53
|
|
|
throw new UnauthorizedHttpException('User not found'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
61 |
|
$ip = !defined('API_TESTS') ? $request->getClientAddress() : '127.0.0.1'; |
|
57
|
61 |
|
return $session->check($user, $data->getClaim('sessionId'), (string) $ip, 1); |
|
58
|
|
|
} else { |
|
59
|
|
|
throw new UnauthorizedHttpException('User not found'); |
|
60
|
|
|
} |
|
61
|
61 |
|
} |
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
69 |
|
return true; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|