Completed
Push — master ( 05fc39...983bb1 )
by Marceau
01:11
created

ImpersonateManager::saveAuthCookieInSession()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 3
nc 2
nop 0
1
<?php
2
3
namespace Lab404\Impersonate\Services;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Foundation\Application;
7
use Lab404\Impersonate\Events\LeaveImpersonation;
8
use Lab404\Impersonate\Events\TakeImpersonation;
9
10
class ImpersonateManager
11
{
12
    const REMEMBER_PREFIX = 'remember_web';
13
14
    /**
15
     * @var Application
16
     */
17
    private $app;
18
19
    /**
20
     * UserFinder constructor.
21
     *
22
     * @param Application $app
23
     */
24
    public function __construct(Application $app)
25
    {
26
        $this->app = $app;
27
    }
28
29
    /**
30
     * @param   int $id
31
     * @return  Model
32
     */
33
    public function findUserById($id)
34
    {
35
        $model = $this->app['config']->get('auth.providers.users.model');
36
37
        $user = call_user_func([
38
            $model,
39
            'findOrFail'
40
        ], $id);
41
42
        return $user;
43
    }
44
45
    /**
46
     * @return bool
47
     */
48
    public function isImpersonating()
49
    {
50
        return session()->has($this->getSessionKey());
51
    }
52
53
    /**
54
     * @param   void
55
     * @return  int|null
56
     */
57
    public function getImpersonatorId()
58
    {
59
        return session($this->getSessionKey(), null);
60
    }
61
62
    /**
63
     * @param Model $from
64
     * @param Model $to
65
     * @return bool
66
     */
67
    public function take($from, $to)
68
    {
69
        $this->saveAuthCookieInSession();
70
71
        try {
72
            session()->put($this->getSessionKey(), $from->getKey());
73
74
            $this->app['auth']->quietLogout();
75
            $this->app['auth']->quietLogin($to);
76
77
        } catch (\Exception $e) {
78
            unset($e);
79
            return false;
80
        }
81
82
        $this->app['events']->dispatch(new TakeImpersonation($from, $to));
83
84
        return true;
85
    }
86
87
    /**
88
     * @return  bool
89
     */
90
    public function leave()
91
    {
92
        try {
93
            $impersonated = $this->app['auth']->user();
94
            $impersonator = $this->findUserById($this->getImpersonatorId());
95
96
            $this->app['auth']->quietLogout();
97
            $this->app['auth']->quietLogin($impersonator);
98
99
            $this->extractAuthCookieFromSession();
100
101
            $this->clear();
102
103
        } catch (\Exception $e) {
104
            dump($e->getMessage());
105
            unset($e);
106
            return false;
107
        }
108
109
        $this->app['events']->dispatch(new LeaveImpersonation($impersonator, $impersonated));
110
111
        return true;
112
    }
113
114
    /**
115
     * @return void
116
     */
117
    public function clear()
118
    {
119
        session()->forget($this->getSessionKey());
120
    }
121
122
    /**
123
     * @return string
124
     */
125
    public function getSessionKey()
126
    {
127
        return config('laravel-impersonate.session_key');
128
    }
129
130
    /**
131
     * @return  string
132
     */
133
    public function getTakeRedirectTo()
134
    {
135
        try {
136
            $uri = route(config('laravel-impersonate.take_redirect_to'));
137
        } catch (\InvalidArgumentException $e) {
138
            $uri = config('laravel-impersonate.take_redirect_to');
139
        }
140
141
        return $uri;
142
    }
143
144
    /**
145
     * @return  string
146
     */
147
    public function getLeaveRedirectTo()
148
    {
149
        try {
150
            $uri = route(config('laravel-impersonate.leave_redirect_to'));
151
        } catch (\InvalidArgumentException $e) {
152
            $uri = config('laravel-impersonate.leave_redirect_to');
153
        }
154
155
        return $uri;
156
    }
157
158
    /**
159
     * @return void
160
     */
161
    protected function saveAuthCookieInSession()
162
    {
163
        $cookie = $this->findByKeyInArray($this->app['request']->cookies->all(), static::REMEMBER_PREFIX);
164
        $key = $cookie->keys()->first();
165
        $val = $cookie->values()->first();
166
167
        if (! $key || ! $val) {
168
            return;
169
        }
170
171
        session()->put(static::REMEMBER_PREFIX, [
172
            $key,
173
            $val,
174
        ]);
175
    }
176
177
    /**
178
     * @return void
179
     */
180
    protected function extractAuthCookieFromSession()
181
    {
182
        if (! $session = $this->findByKeyInArray(session()->all(), static::REMEMBER_PREFIX)->first()) {
183
            return;
184
        }
185
186
        $this->app['cookie']->queue($session[0], $session[1]);
187
        session()->forget($session);
188
    }
189
190
    /**
191
     * @param array $values
192
     * @param string $search
193
     * @return \Illuminate\Support\Collection
194
     */
195
    protected function findByKeyInArray(array $values, string $search)
196
    {
197
        return collect($values ?? session()->all())
198
            ->filter(function ($val, $key) use ($search) {
199
                return strpos($key, $search) !== false;
200
            });
201
    }
202
}
203