Completed
Push — master ( 983bb1...8feb4f )
by Marceau
02:00 queued 50s
created

ImpersonateManager::getDefaultSessionGuard()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
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
use Exception;
10
11
class ImpersonateManager
12
{
13
    const REMEMBER_PREFIX = 'remember_web';
14
15
    /**
16
     * @var Application
17
     */
18
    private $app;
19
20
    /**
21
     * UserFinder constructor.
22
     *
23
     * @param Application $app
24
     */
25
    public function __construct(Application $app)
26
    {
27
        $this->app = $app;
28
    }
29
30
    /**
31
     * @param   int $id
32
     * @return  Model
33
     * @throws Exception
34
     */
35
    public function findUserById($id, $guardName = null)
36
    {
37
        $userProvider = $this->app['config']->get("auth.guards.$guardName.provider");
38
        $model = $this->app['config']->get("auth.providers.$userProvider.model");
39
40
        if(!$model) {
41
            throw new Exception("Auth guard doesn not exist.", 1);
42
        }
43
44
        /** @var Model $modelInstance */
45
        $modelInstance = call_user_func([
46
            $model,
47
            'findOrFail'
48
        ], $id);
49
50
        return $modelInstance;
51
    }
52
53
    /**
54
     * @return bool
55
     */
56
    public function isImpersonating()
57
    {
58
        return session()->has($this->getSessionKey());
59
    }
60
61
    /**
62
     * @param   void
63
     * @return  int|null
64
     */
65
    public function getImpersonatorId()
66
    {
67
        return session($this->getSessionKey(), null);
68
    }
69
70
    /**
71
     * @return string|null
72
     */
73
    public function getImpersonatorGuardName()
74
    {
75
        return session($this->getSessionGuard(), null);
76
    }
77
78
    /**
79
     * @return string|null
80
     */
81
    public function getImpersonatorGuardUsingName()
82
    {
83
        return session($this->getSessionGuardUsing(), null);
84
    }
85
86
    /**
87
     * @param Model $from
88
     * @param Model $to
89
     * @param string|null $guardName
90
     * @return bool
91
     */
92
    public function take($from, $to, $guardName = null)
93
    {
94
        $this->saveAuthCookieInSession();
95
96
        try {
97
            $currentGuard = $this->getCurrentAuthGuardName();
98
            session()->put($this->getSessionKey(), $from->getKey());
99
            session()->put($this->getSessionGuard(), $currentGuard);
100
            session()->put($this->getSessionGuardUsing(), $guardName);
101
102
            $this->app['auth']->guard($currentGuard)->quietLogout();
103
            $this->app['auth']->guard($guardName)->quietLogin($to);
104
105
        } catch (\Exception $e) {
106
            unset($e);
107
            return false;
108
        }
109
110
        $this->app['events']->dispatch(new TakeImpersonation($from, $to));
111
112
        return true;
113
    }
114
115
    /**
116
     * @return  bool
117
     */
118
    public function leave()
119
    {
120
        try {
121
            $impersonated = $this->app['auth']->guard($this->getImpersonatorGuardUsingName())->user();
122
            $impersonator = $this->findUserById($this->getImpersonatorId(), $this->getImpersonatorGuardName());
123
124
            $this->app['auth']->guard($this->getCurrentAuthGuardName())->quietLogout();
125
            $this->app['auth']->guard($this->getImpersonatorGuardName())->quietLogin($impersonator);
126
127
            $this->extractAuthCookieFromSession();
128
129
            $this->clear();
130
131
        } catch (\Exception $e) {
132
            dump($e->getMessage());
133
            unset($e);
134
            return false;
135
        }
136
137
        $this->app['events']->dispatch(new LeaveImpersonation($impersonator, $impersonated));
138
139
        return true;
140
    }
141
142
    /**
143
     * @return void
144
     */
145
    public function clear()
146
    {
147
        session()->forget($this->getSessionKey());
148
        session()->forget($this->getSessionGuard());
149
        session()->forget($this->getSessionGuardUsing());
150
    }
151
152
    /**
153
     * @return string
154
     */
155
    public function getSessionKey()
156
    {
157
        return config('laravel-impersonate.session_key');
158
    }
159
160
    /**
161
     * @return string
162
     */
163
    public function getSessionGuard()
164
    {
165
        return config('laravel-impersonate.session_guard');
166
    }
167
168
    /**
169
     * @return string
170
     */
171
    public function getSessionGuardUsing()
172
    {
173
        return config('laravel-impersonate.session_guard_using');
174
    }
175
176
    /**
177
     * @return string
178
     */
179
    public function getDefaultSessionGuard()
180
    {
181
        return config('laravel-impersonate.default_impersonator_guard');
182
    }
183
184
    /**
185
     * @return  string
186
     */
187
    public function getTakeRedirectTo()
188
    {
189
        try {
190
            $uri = route(config('laravel-impersonate.take_redirect_to'));
191
        } catch (\InvalidArgumentException $e) {
192
            $uri = config('laravel-impersonate.take_redirect_to');
193
        }
194
195
        return $uri;
196
    }
197
198
    /**
199
     * @return  string
200
     */
201
    public function getLeaveRedirectTo()
202
    {
203
        try {
204
            $uri = route(config('laravel-impersonate.leave_redirect_to'));
205
        } catch (\InvalidArgumentException $e) {
206
            $uri = config('laravel-impersonate.leave_redirect_to');
207
        }
208
209
        return $uri;
210
    }
211
212
    /**
213
     * @return array
214
     */
215
    public function getCurrentAuthGuardName()
216
    {
217
        $guards = array_keys(config('auth.guards'));
218
        foreach ($guards as $guard) {
219
            if ($this->app['auth']->guard($guard)->check()) {
220
                return $guard;
221
            }
222
        }
223
        return null;
224
    }
225
  
226
    /**
227
     * @return void
228
     */
229
    protected function saveAuthCookieInSession()
230
    {
231
        $cookie = $this->findByKeyInArray($this->app['request']->cookies->all(), static::REMEMBER_PREFIX);
232
        $key = $cookie->keys()->first();
233
        $val = $cookie->values()->first();
234
235
        if (! $key || ! $val) {
236
            return;
237
        }
238
239
        session()->put(static::REMEMBER_PREFIX, [
240
            $key,
241
            $val,
242
        ]);
243
    }
244
245
    /**
246
     * @return void
247
     */
248
    protected function extractAuthCookieFromSession()
249
    {
250
        if (! $session = $this->findByKeyInArray(session()->all(), static::REMEMBER_PREFIX)->first()) {
251
            return;
252
        }
253
254
        $this->app['cookie']->queue($session[0], $session[1]);
255
        session()->forget($session);
256
    }
257
258
    /**
259
     * @param array $values
260
     * @param string $search
261
     * @return \Illuminate\Support\Collection
262
     */
263
    protected function findByKeyInArray(array $values, string $search)
264
    {
265
        return collect($values ?? session()->all())
266
            ->filter(function ($val, $key) use ($search) {
267
                return strpos($key, $search) !== false;
268
            });
269
    }
270
}
271