with(['hd' => 'somaiya.edu'])->redirect(); } /** * Obtain the user information from Google. */ public function handleGoogleCallback() { try { $googleUser = Socialite::driver('google')->user(); // Validate that the user belongs to the somaiya.edu domain. // Google may return a 'hd' (hosted domain) claim; fall back to parsing the email. $email = $googleUser->getEmail(); $hostedDomain = data_get($googleUser->user, 'hd'); $domain = $hostedDomain ?: (strpos($email, '@') !== false ? substr(strrchr($email, "@"), 1) : null); if ($domain !== 'somaiya.edu') { return redirect()->route('login')->withErrors(['error' => 'Please sign in using a somaiya.edu account.']); } $user = User::firstOrCreate( ['email' => $email], [ 'name' => $googleUser->getName() ?: $email, 'password' => bcrypt(Str::random(16)), // Generate a random password ] ); Auth::login($user); return redirect()->route('dashboard'); } catch (\Exception $e) { return redirect()->route('login')->withErrors(['error' => 'Unable to login using Google. Please try again.']); } } }