Completed
Push — master ( fcc0ff...8f456d )
by Mahmoud
03:36
created

VisitorsAuthentication::handle()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 27
rs 8.5806
cc 4
eloc 13
nc 4
nop 2
1
<?php
2
3
namespace App\Containers\Authentication\Middlewares;
4
5
use App\Containers\Authentication\Exceptions\AuthenticationFailedException;
6
use App\Containers\Authentication\Exceptions\MissingVisitorIdException;
7
use App\Containers\User\Actions\CreateVisitorUserAction;
8
use Closure;
9
use Illuminate\Http\Request;
10
use Jenssegers\Agent\Agent;
11
12
/**
13
 * Class VisitorsAuthentication
14
 *
15
 * @author  Mahmoud Zalt  <[email protected]>
16
 */
17
class VisitorsAuthentication
18
{
19
20
    /**
21
     * @var  \Jenssegers\Agent\Agent
22
     */
23
    private $agent;
24
25
    /**
26
     * @var  \App\Containers\User\Actions\CreateVisitorUserAction
27
     */
28
    private $registerVisitorUserAction;
29
30
    /**
31
     * VisitorsAuthentication constructor.
32
     *
33
     * @param \Jenssegers\Agent\Agent                                $agent
34
     * @param \App\Containers\User\Actions\CreateVisitorUserAction $registerVisitorUserAction
35
     */
36
    public function __construct(
37
        Agent $agent,
38
        CreateVisitorUserAction $registerVisitorUserAction
39
    ) {
40
        $this->agent = $agent;
41
        $this->registerVisitorUserAction = $registerVisitorUserAction;
42
    }
43
44
    /**
45
     * Whenever the request doesn't have an Authorization header (token)
46
     * it must have a an Visitor-Id header.
47
     *
48
     * @param  \Illuminate\Http\Request $request
49
     * @param  \Closure                 $next
50
     *
51
     * @return mixed
52
     */
53
    public function handle(Request $request, Closure $next)
54
    {
55
        $token = $request->header('Authorization');
56
57
        if (!$token) {
58
            // read the visitor ID header (set by the API users)
59
            $visitorId = $request->header('Visitor-Id');
60
61
            if (!$visitorId) {
62
                throw new MissingVisitorIdException();
63
            }
64
65
            $device = $this->agent->device();
66
            $platform = $this->agent->platform();
67
68
            $user = $this->registerVisitorUserAction->run($visitorId, $device, $platform);
69
70
            if (!$user) {
71
                throw new AuthenticationFailedException(
72
                    'Something went wrong while trying to create user from the "Visitor-Id": ' . $visitorId
73
                );
74
            }
75
        }
76
77
        // return the response
78
        return $next($request);
79
    }
80
}
81