|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers\Auth; |
| 4 | + |
| 5 | +use Illuminate\Http\Request; |
| 6 | +use App\Http\Controllers\Controller; |
| 7 | + |
| 8 | +use Auth; |
| 9 | + |
| 10 | +use Carbon\Carbon; |
| 11 | +use Socialite; |
| 12 | + |
| 13 | +use App\User; |
| 14 | + |
| 15 | +class SocialGitHubController extends Controller |
| 16 | +{ |
| 17 | + |
| 18 | + /** |
| 19 | + * Redirect the user to the GitHub authentication page. |
| 20 | + * |
| 21 | + * @return \Illuminate\Http\Response |
| 22 | + */ |
| 23 | + public function redirectToProvider() |
| 24 | + { |
| 25 | + return Socialite::driver('github')->redirect(); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Obtain the user information from GitHub. |
| 30 | + * |
| 31 | + * @return \Illuminate\Http\Response |
| 32 | + */ |
| 33 | + public function handleProviderCallback() |
| 34 | + { |
| 35 | + |
| 36 | + $firstName = null; |
| 37 | + $lastName = null; |
| 38 | + |
| 39 | + $user = Socialite::driver('github')->user(); |
| 40 | + |
| 41 | + $existingUser = User::where('provider_id', $user->getId())->first(); |
| 42 | + |
| 43 | + if ($existingUser) { |
| 44 | + |
| 45 | + $existingUser->last_login_at = Carbon::now(); |
| 46 | + $existingUser->save(); |
| 47 | + |
| 48 | + Auth::login($existingUser); |
| 49 | + |
| 50 | + } else { |
| 51 | + |
| 52 | + if ($user->getName()) { |
| 53 | + |
| 54 | + $name = explode(" ", $user->getName()); |
| 55 | + |
| 56 | + if (count($name) > 1) { |
| 57 | + $firstName = $name[0]; |
| 58 | + $lastName = $name[1]; |
| 59 | + } else { |
| 60 | + $firstName = $name[0]; |
| 61 | + $lastName = null; |
| 62 | + } |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + $newUser = new User(); |
| 67 | + |
| 68 | + $newUser->first_name = $firstName; |
| 69 | + $newUser->last_name = $lastName; |
| 70 | + $newUser->email = $user->getEmail(); |
| 71 | + $newUser->provider = 'github'; |
| 72 | + $newUser->provider_id = $user->getId(); |
| 73 | + $newUser->handle_github = $user->getNickname(); |
| 74 | + $newUser->password = bcrypt(uniqid()); |
| 75 | + $newUser->last_login_at = Carbon::now(); |
| 76 | + |
| 77 | + $newUser->save(); |
| 78 | + |
| 79 | + Auth::login($newUser); |
| 80 | + |
| 81 | + } |
| 82 | + |
| 83 | + flash('Successfully authenticated using GitHub'); |
| 84 | + |
| 85 | + return redirect('/'); |
| 86 | + |
| 87 | + } |
| 88 | + |
| 89 | +} |
0 commit comments