wip social

This commit is contained in:
Masroor Ehsan 2025-01-05 20:04:35 +06:00
parent ff007945f6
commit 7e4bcd6309

View File

@ -3,7 +3,11 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\User; use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Facades\Socialite;
class SocialLoginController extends Controller class SocialLoginController extends Controller
@ -11,7 +15,7 @@ class SocialLoginController extends Controller
public function redirect(string $driver) public function redirect(string $driver)
{ {
return Socialite::driver($driver) return Socialite::driver($driver)
->scopes(['name', 'email']) ->scopes(['openid', 'profile', 'name', 'email'])
->redirect(); ->redirect();
} }
@ -27,10 +31,11 @@ public function handleProviderCallback(string $driver)
Auth::login($user); Auth::login($user);
$updates = []; $updates = [];
if ($user->profile_photo_path == null) { if (blank($user->profile_photo_path)) {
$updates['profile_photo_path'] = $social->getAvatar(); $updates['profile_photo_path'] = $this->buildAvatarUrl($social->getAvatar(), $social->token);
$updates['profile_photo_path'] = $this->fetchAvatar($social->getAvatar(), $social->token, $user->profilePhotoDisk());
} }
if ($user->email == null) { if (blank($user->email)) {
$updates['email'] = $social->getEmail(); $updates['email'] = $social->getEmail();
} }
$updates = array_purge($updates); $updates = array_purge($updates);
@ -38,13 +43,47 @@ public function handleProviderCallback(string $driver)
$user->update($updates); $user->update($updates);
} }
return redirect()->route('dashboard'); return redirect()->route('staff.worklist.index');
} else { } else {
$provider = ucfirst($driver); $provider = ucfirst($driver);
return redirect() return redirect()
->route('login') ->route('login')
->withErrors("Email {$social->getEmail()} not found for {$provider} login."); ->withErrors("Email or username not found for {$provider} login.");
} }
} }
public function buildAvatarUrl(?string $avatar_url, ?string $access_token): ?string
{
if (blank($avatar_url)) {
return null;
}
if (filled($access_token)) {
$avatar_url .= "?access_token={$access_token}";
}
return $avatar_url;
}
public function fetchAvatar(?string $avatar_url, ?string $access_token, string $disk): ?string
{
$url = $this->buildAvatarUrl($avatar_url, $access_token);
if (blank($url)) {
return null;
}
try {
$response = Http::get($url);
if ($response->successful()) {
$filename = 'avatars/' . Str::uuid() . '.jpg';
Storage::disk($disk)->put($filename, $response->body());
return $filename;
}
} catch (Exception) {
}
return null;
}
} }