LoginAs::handle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 2
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Middleware;
4
5
use Closure;
6
use Exception;
7
use App\Services\Auth\Back\User as BackUser;
8
use App\Services\Auth\Front\User as FrontUser;
9
use Illuminate\Contracts\Auth\Authenticatable;
10
11
class LoginAs
12
{
13
    public function handle($request, Closure $next)
14
    {
15
        $segments = array_reverse(request()->segments());
16
17
        if (($segments[1] ?? '') !== 'login') {
18
            return $next($request);
19
        }
20
21
        if (! $this->canLoginAs()) {
22
            throw new Exception("You can't log in as a specific user right now");
23
        }
24
25
        return $this->loginAsAndRedirect($segments[0]);
26
    }
27
28
    protected function canLoginAs(): bool
29
    {
30
        // Just to be sure...
31
32
        if (! app()->environment('local')) {
33
            return false;
34
        }
35
36
        if (! ends_with(request()->getHost(), '.dev')) {
37
            return false;
38
        }
39
40
        if (! in_array(env('DB_USERNAME'), ['homestead', 'root'])) {
41
            return false;
42
        }
43
44
        return true;
45
    }
46
47
    protected function loginAsAndRedirect(string $identifier)
48
    {
49
        $user = $this->getUser($identifier)->getAuthIdentifier();
50
51
        if (empty($user)) {
52
            throw new Exception('The user you\'re trying to log in as doesn\'t exist');
53
        }
54
55
        auth()->loginUsingId($user);
56
57
        return redirect()->to(
58
            str_replace("login/{$identifier}", '', request()->fullUrl())
59
        );
60
    }
61
62
    protected function getUser(string $identifier): Authenticatable
63
    {
64
        if (! str_contains($identifier, '@')) {
65
            $identifier .= '@spatie.be';
66
        }
67
68
        if (request()->isBack()) {
69
            return BackUser::where(['email' => $identifier])->first();
70
        }
71
72
        return FrontUser::where(['email' => $identifier])->first();
73
    }
74
}
75