storePasswordHashInSession()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
nc 2
nop 1
dl 0
loc 8
c 0
b 0
f 0
cc 2
rs 10
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('chief') || ! $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('chief')->getAuthPassword()) {
28
                $this->logout($request);
29
            }
30
        }
31
32
        if (! $request->session()->has('chief_password_hash')) {
33
            $this->storePasswordHashInSession($request);
34
        }
35
36
        if ($request->session()->get('chief_password_hash') !== $request->user('chief')->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('chief')) {
54
            return;
55
        }
56
57
        $request->session()->put([
58
            'chief_password_hash' => $request->user('chief')->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()->remove('chief_password_hash');
75
76
        throw new AuthenticationException();
77
    }
78
}
79