Completed
Push — develop ( 06396b...c3acb5 )
by Niclas Leon
12s
created

app/Http/Controllers/AuthController.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Socialite;
6
use Auth;
7
use App\User;
8
use Exception;
9
10
class AuthController extends Controller
11
{
12
    /**
13
     * Redirect the user to the GitHub authentication page.
14
     *
15
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
16
     */
17
    public function redirectToProvider()
18
    {
19
        return Socialite::driver('github')->scopes([])->redirect();
20
    }
21
22
    /**
23
     * Obtain the user information from GitHub.
24
     *
25
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
26
     */
27
    public function handleProviderCallback()
28
    {
29
        try {
30
            $user = Socialite::driver('github')->user();
31
            $authUser = $this->findOrCreateUser($user);
32
33
            Auth::login($authUser, true);
34
        } catch (Exception $e) {
35
            // just catch it...
36
        }
37
38
        return redirect('/');
39
    }
40
41
    /**
42
     * Log the current user out.
43
     *
44
     * @return Response
0 ignored issues
show
The type App\Http\Controllers\Response was not found. Did you mean Response? If so, make sure to prefix the type with \.
Loading history...
45
     */
46
    public function signOut()
47
    {
48
        Auth::logout();
49
50
        return redirect('/');
51
    }
52
53
    /**
54
     * Return user if exists; create and return if doesn't
55
     *
56
     * @param $githubUser
57
     * @return User
58
     */
59
    private function findOrCreateUser($user)
60
    {
61
        $authUser = [
62
            'name' => $user->name ? $user->name : $user->nickname,
63
            'github_username' => $user->nickname,
64
            'github_id' => $user->id,
65
            'github_token' => $user->token,
66
            'github_avatar' => $user->avatar,
67
        ];
68
69
        $databaseUser = User::where('github_id', $user->id)->first();
70
71
        if ($databaseUser) {
72
            $databaseUser->fill($authUser);
73
            $databaseUser->save();
74
75
            return $databaseUser;
76
        }
77
78
        return User::create($authUser);
79
    }
80
}
81