WebToken::handle()   A
last analyzed

Complexity

Conditions 5
Paths 10

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 26
c 1
b 0
f 0
nc 10
nop 2
dl 0
loc 40
rs 9.1928
1
<?php
2
3
namespace App\Http\Middleware;
4
5
use App\Token;
6
use Auth;
7
use Cache;
8
use Closure;
9
use Config;
10
use Cookie;
11
use Session;
12
13
class WebToken
14
{
15
    private $apiKey;
16
    private $cache_enabled;
17
18
    public function handle($request, Closure $next)
19
    {
20
        $check = null;
21
        $cache_time_forever = Config::get('app.cache_time_forever');
22
        $this->cache_enabled = (bool) Config::get('app.cache_enabled');
23
        $this->apiKey = $request->cookie('apiToken');
24
25
        if (!$this->cache_enabled) {
26
            $cache_time_forever = 0;
27
        }
28
29
        if ($this->apiKey) {
30
            if (Cache::has('t_'.$this->apiKey)) {
31
                $check = Cache::get('t_'.$this->apiKey);
32
            } else {
33
                $check = Cache::remember('t_'.$this->apiKey, $cache_time_forever, function () {
34
                    $m1token = Token::where('api_token', $this->apiKey)->first();
35
36
                    return $m1token;
37
                });
38
            }
39
40
            // $check = Token::where('api_token', $this->apiKey)->first();
41
42
            if ($check) {
43
                $request->request->add(['user_id' => $check->user_id]);
44
                $request->request->add(['token_id' => $check->id]);
45
                $request->request->add(['token_data' => $check->api_token]);
46
                Auth::loginUsingId($check->user_id);
47
            } else {
48
                Cookie::queue(Cookie::forget('apiToken'));
49
                Auth::logout();
50
                Session::flush();
51
            }
52
        } else {
53
            Auth::logout();
54
            Session::flush();
55
        }
56
57
        return $next($request);
58
    }
59
}
60