Passed
Pull Request — master (#7)
by Hilmi Erdem
06:41
created

Otp::sendNewOtpToUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
rs 10
c 0
b 0
f 0
ccs 6
cts 6
cp 1
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/*
4
 * @copyright 2018 Hilmi Erdem KEREN
5
 * @license MIT
6
 */
7
8
namespace Erdemkeren\Otp\Http\Middleware;
9
10
use Closure;
11
use Erdemkeren\Otp\OtpFacade;
12
use Erdemkeren\Otp\TokenInterface;
13
use Illuminate\Http\RedirectResponse;
14
use Illuminate\Http\Request;
15
16
class Otp
17
{
18
    /**
19
     * Handle an incoming request.
20
     *
21
     * @param \Illuminate\Http\Request $request
22
     * @param \Closure                 $next
23
     * @param null|string              $guard
24
     *
25
     * @return mixed
26
     */
27 3
    public function handle(Request $request, Closure $next, $guard = null)
28
    {
29 3
        if (! $user = $request->user($guard)) {
30 1
            throw new \LogicException(
31 1
                'The otp access control middleware requires user authentication via laravel guards.'
32
            );
33
        }
34
35 2
        if (! $request->hasCookie('otp_token')) {
36 1
            OtpFacade::sendNewOtpToUser($user);
37
38
            return $this->redirectToOtpPage();
39
        }
40
41 1
        $token = OtpFacade::retrieveByCipherText(
42 1
            $user->getAuthIdentifier(),
43 1
            $request->cookie('otp_token')
0 ignored issues
show
Bug introduced by
It seems like $request->cookie('otp_token') can also be of type array; however, parameter $cipherText of Erdemkeren\Otp\OtpFacade::retrieveByCipherText() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

43
            /** @scrutinizer ignore-type */ $request->cookie('otp_token')
Loading history...
44
        );
45
46 1
        if (! $token || $token->expired()) {
47
            OtpFacade::sendNewOtpToUser($user);
48
49
            return $this->redirectToOtpPage();
50
        }
51
52
        $request->macro('otpToken', function () use ($token): TokenInterface {
53 1
            return $token;
54 1
        });
55
56 1
        return $next($request);
57
    }
58
59
    /**
60
     * Get the redirect url if check do not pass.
61
     *
62
     * @return RedirectResponse
63
     */
64
    protected function redirectToOtpPage(): RedirectResponse
65
    {
66
        session([
67
            'otp_requested'    => true,
68
            'otp_redirect_url' => url()->current(),
69
        ]);
70
71
        return redirect()->route('otp.create');
72
    }
73
}
74