Files
Faculty-Documentation/app/Http/Controllers/Auth/GoogleController.php

69 lines
2.5 KiB
PHP

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Str;
use App\Models\User;
class GoogleController extends Controller
{
/**
* Redirect the user to the Google authentication page.
*/
public function redirectToGoogle()
{
// Prefer to hint Google to show accounts from the somaiya.edu domain.
// This is only a UI hint — always validate the domain on the callback.
return Socialite::driver('google')->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
'profile_image' => $googleUser->getAvatar(),
]
);
// Update profile image if it changed or wasn't set (for existing users logging in)
if (!$user->profile_image) {
$user->update(['profile_image' => $googleUser->getAvatar()]);
}
// Sync to FacultyProfile
$profile = \App\Models\FacultyProfile::firstOrCreate(['user_id' => $user->id]);
if (!$profile->profile_photo_path) {
$profile->update(['profile_photo_path' => $googleUser->getAvatar()]);
}
Auth::login($user);
return redirect()->route('dashboard');
} catch (\Exception $e) {
return redirect()->route('login')->withErrors(['error' => 'Unable to login using Google. Please try again.']);
}
}
}