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 Phalcon\Http\Request; |
12
|
|
|
use Gewaer\Exception\UnauthorizedHttpException; |
13
|
|
|
use Gewaer\Constants\Flags; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class AuthenticationMiddleware |
17
|
|
|
* |
18
|
|
|
* @package Niden\Middleware |
19
|
|
|
*/ |
20
|
|
|
class AuthenticationMiddleware implements MiddlewareInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* Call me |
24
|
|
|
* |
25
|
|
|
* @param Micro $api |
26
|
|
|
* @todo need to check section for auth here |
27
|
|
|
* @return bool |
28
|
|
|
*/ |
29
|
21 |
|
public function call(Micro $api) |
30
|
|
|
{ |
31
|
21 |
|
$auth = $api->getService('auth'); |
32
|
21 |
|
$config = $api->getService('config'); |
33
|
|
|
|
34
|
|
|
// to get the payload |
35
|
21 |
|
$data = $auth->data(); |
36
|
|
|
|
37
|
21 |
|
$api->getDI()->setShared( |
38
|
21 |
|
'userData', |
39
|
|
|
function () use ($config, $data) { |
40
|
16 |
|
$session = new Sessions(); |
41
|
16 |
|
$request = new Request(); |
42
|
|
|
|
43
|
|
|
//all is empty and is dev, ok take use the first user |
44
|
16 |
|
if (empty($data) && empty($data['sessionId']) && strtolower($config->app->env) == Flags::DEVELOPMENT) { |
45
|
1 |
|
return Users::findFirst(1); |
46
|
|
|
} |
47
|
|
|
|
48
|
15 |
|
if (!empty($data) && !empty($data['sessionId'])) { |
49
|
|
|
//user |
50
|
15 |
|
if (!$user = Users::getByEmail($data['email'])) { |
51
|
|
|
throw new UnauthorizedHttpException('User not found'); |
52
|
|
|
} |
53
|
|
|
|
54
|
15 |
|
$ip = !defined('API_TESTS') ? $request->getClientAddress() : '127.0.0.1'; |
55
|
15 |
|
return $session->check($user, $data['sessionId'], (string) $ip, 1); |
56
|
|
|
} else { |
57
|
|
|
throw new UnauthorizedHttpException('User not found'); |
58
|
|
|
} |
59
|
21 |
|
} |
60
|
|
|
); |
61
|
|
|
|
62
|
21 |
|
return true; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|