SocialiteAuth::prepareDriver()   A
last analyzed

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 1
1
<?php
2
3
namespace STS\SocialiteAuth;
4
5
use Closure;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use Laravel\Socialite\Contracts\User;
8
use Laravel\Socialite\Facades\Socialite;
9
10
class SocialiteAuth
11
{
12
    /**
13
     * @var array
14
     */
15
    protected $config;
16
17
    /**
18
     * @var \Closure
19
     */
20
    protected $prepareDriver = null;
21
22
    /**
23
     * @var \Closure
24
     */
25
    protected $verifyUser = null;
26
27
    /**
28
     * @var \Closure
29
     */
30
    protected $handleNewUser = null;
31
32
    public function __construct(array $config)
33
    {
34
        $this->config = $config;
35
    }
36
37
    public function getDriver()
38
    {
39
        $driver = Socialite::driver($this->config['driver']);
40
41
        if($this->prepareDriver) {
42
            call_user_func($this->prepareDriver, $driver);
43
        }
44
45
        return $driver;
46
    }
47
48
    public function prepareDriver(Closure $prepareDriver)
49
    {
50
        $this->prepareDriver = $prepareDriver;
51
    }
52
53
    /**
54
     * Provide custom logic for verifying a user before login.
55
     *
56
     * @param \Closure
57
     */
58
    public function beforeLogin(Closure $beforeLogin)
59
    {
60
        $this->verifyUser = $beforeLogin;
61
    }
62
63
    /**
64
     * Provide custom handler for setting up a new user.
65
     *
66
     * @param Closure $handleNewUser
67
     */
68
    public function newUser(Closure $handleNewUser)
69
    {
70
        $this->handleNewUser = $handleNewUser;
71
    }
72
73
    /**
74
     * Verify that the user meets login requirements
75
     * according to the custom logic provided.
76
     *
77
     * @param Authenticatable
78
     *
79
     * @return bool
80
     */
81
    public function verifyBeforeLogin(Authenticatable $user): bool
82
    {
83
        return $this->verifyUser
84
            ? call_user_func($this->verifyUser, $user)
85
            : true;
86
    }
87
88
    /**
89
     * @param $user
90
     *
91
     * @return bool|Authenticatable
92
     */
93
    public function handleNewUser(User $user)
94
    {
95
        if ($this->handleNewUser) {
96
            return call_user_func($this->handleNewUser, $user);
97
        }
98
99
        if ($this->config['match'] == false) {
100
            $user = Identity::fromSocialite($user);
101
            session()->put($this->sessionKeyFor($user->getAuthIdentifier()), $user->toArray());
102
103
            return $user;
104
        }
105
    }
106
107
    public function sessionKeyFor($identifier)
108
    {
109
        return 'socialite-auth.' . str_replace('.','-',$identifier);
110
    }
111
}
112