Нет описания

LoginController.php 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Http\Controllers\Auth;
  3. use App\Http\Controllers\Controller;
  4. use Socialite;
  5. use Illuminate\Foundation\Auth\AuthenticatesUsers;
  6. use Illuminate\Foundation\Auth\User;
  7. use Illuminate\Http\Request;
  8. class LoginController extends Controller
  9. {
  10. /*
  11. |--------------------------------------------------------------------------
  12. | Login Controller
  13. |--------------------------------------------------------------------------
  14. |
  15. | This controller handles authenticating users for the application and
  16. | redirecting them to your home screen. The controller uses a trait
  17. | to conveniently provide its functionality to your applications.
  18. |
  19. */
  20. use AuthenticatesUsers;
  21. /**
  22. * Where to redirect users after login.
  23. *
  24. * @var string
  25. */
  26. protected $redirectTo = '/dashboard';
  27. /**
  28. * Create a new controller instance.
  29. *
  30. * @return void
  31. */
  32. public function __construct()
  33. {
  34. $this->middleware('guest')->except('logout');
  35. }
  36. /**
  37. * Redirect the user to the GitHub authentication page.
  38. *
  39. * @return \Illuminate\Http\Response
  40. */
  41. public function redirectToProvider()
  42. {
  43. return Socialite::driver('google')->redirect();
  44. }
  45. /**
  46. * Obtain the user information from GitHub.
  47. *
  48. * @return \Illuminate\Http\Response
  49. */
  50. public function handleProviderCallback()
  51. {
  52. // $user = Socialite::driver('google')->user();
  53. try {
  54. $user = Socialite::driver('google')->user();
  55. } catch (Exception $e) {
  56. return redirect('/login');
  57. }
  58. // only allow people with @company.com to login
  59. if(explode("@", $user->email)[1] !== 'upr.edu'){
  60. return redirect()->to('/');
  61. }
  62. // check if they're an existing user
  63. $existingUser = User::where('email', $user->email)->first();
  64. if($existingUser){
  65. // log them in
  66. auth()->login($existingUser, true);
  67. } else if (User::all()->count() === 0) {
  68. // create a new user
  69. $newUser = new User;
  70. $newUser->name = $user->name;
  71. $newUser->email = $user->email;
  72. $newUser->google_id = $user->id;
  73. $newUser->save();
  74. auth()->login($newUser, true);
  75. }
  76. return redirect()->to('/');
  77. }
  78. public function logout(Request $request) {
  79. auth()->logout();
  80. return redirect('/');
  81. }
  82. }