AuthenticateUser::execute()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 4
nop 3
dl 0
loc 22
ccs 0
cts 19
cp 0
crap 20
rs 9.7998
c 0
b 0
f 0
1
<?php namespace App;
2
3
use App\Repositories\Eloquent\UserRepository;
4
use Illuminate\Contracts\Auth\Guard;
5
use Illuminate\Support\Facades\Lang;
6
use Illuminate\Support\Facades\Session;
7
use Laravel\Socialite\Contracts\Factory as Socialite;
8
use PDOException;
9
use URL;
10
11
/**
12
 *  Class used by Socialite for Social Logging
13
 */
14
class AuthenticateUser
15
{
16
17
    private $socialite;
18
    private $auth;
19
    private $users;
20
21
    public function __construct(Socialite $socialite, Guard $auth, UserRepository $users)
22
    {
23
        $this->socialite = $socialite;
24
        $this->users = $users;
25
        $this->auth = $auth;
26
    }
27
28
    /**
29
     * @param $request
30
     * @param $listener
31
     * @param $provider
32
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Symfony\Component\HttpFoundation\RedirectResponse
33
     */
34
    public function execute($request, $listener, $provider)
35
    {
36
37
        if (!$request) {
38
            return $this->getAuthorizationFirst($provider);
39
        }
40
        try {
41
            $user = $this->users->findByUserNameOrCreate($this->getSocialUser($provider), $provider);
42
        } catch (PDOException $e) {
43
            return redirect(URL::action('Auth\LoginController@login'))
44
                ->with('message', Lang::get('auth.fb_is_not_sharing_email'));
45
        }
46
47
        if (!is_null($user)) {
48
            $this->auth->login($user, true);
49
        } else {
50
            Session::flash('error', Lang::get('auth.account_already_exists'));
51
52
            return redirect(URL::action('Auth\LoginController@login'))
53
                ->with('message', Lang::get('auth.account_already_exists'));
54
        }
55
        return redirect(route('dashboard'));
56
    }
57
58
    /**
59
     * @param $provider
60
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
61
     */
62
    private function getAuthorizationFirst($provider)
63
    {
64
        return $this->socialite->driver($provider)->redirect();
65
    }
66
67
    /**
68
     * @param $provider
69
     * @return \Laravel\Socialite\Contracts\User
70
     */
71
    private function getSocialUser($provider)
72
    {
73
        return $this->socialite->driver($provider)->user();
74
    }
75
}