Passed
Push — dependabot/npm_and_yarn/string... ( b56eb5...bc569b )
by
unknown
45:46 queued 33s
created

AuthenticateChiefSession::handle()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 10.5454

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 13
nop 2
dl 0
loc 24
ccs 7
cts 12
cp 0.5833
crap 10.5454
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\Chief\App\Http\Middleware;
4
5
use Closure;
6
use Illuminate\Auth\AuthenticationException;
7
use Illuminate\Support\Facades\Auth;
8
9
class AuthenticateChiefSession
10
{
11
    protected $auth;
12
13
    public function __construct()
14
    {
15
        $this->auth = Auth::guard('chief');
16
    }
17
18
    public function handle($request, Closure $next)
19
    {
20
        if (! $request->user() || ! $request->session()) {
21
            return $next($request);
22
        }
23
24
        if ($this->auth->viaRemember()) {
25
            $passwordHash = explode('|', $request->cookies->get($this->auth->getRecallerName()))[2];
26
27
            if ($passwordHash != $request->user()->getAuthPassword()) {
28
                $this->logout($request);
29
            }
30
        }
31
32
        if (! $request->session()->has('password_hash')) {
33
            $this->storePasswordHashInSession($request);
34
        }
35
36
        if ($request->session()->get('password_hash') !== $request->user()->getAuthPassword()) {
37
            $this->logout($request);
38
        }
39
        
40
        return tap($next($request), function () use ($request) {
41
            $this->storePasswordHashInSession($request);
42
        });
43
    }
44
45
    /**
46
     * Store the user's current password hash in the session.
47
     *
48
     * @param  \Illuminate\Http\Request  $request
49
     * @return void
50
     */
51
    protected function storePasswordHashInSession($request)
52
    {
53
        if (! $request->user()) {
54
            return;
55
        }
56
        
57
        $request->session()->put([
58
            'password_hash' => $request->user()->getAuthPassword(),
59
            ]);
60
    }
61
62
    /**
63
     * Log the user out of the application.
64
     *
65
     * @param  \Illuminate\Http\Request  $request
66
     * @return void
67
     *
68
     * @throws \Illuminate\Auth\AuthenticationException
69
     */
70
    protected function logout($request)
71
    {
72
        $this->auth->logout();
73
74
        $request->session()->flush();
75
76
        throw new AuthenticationException;
77
    }
78
}
79